import {z} from 'zod' export type ApprovalAutomation = {auto_cancel: boolean, cancel_before_scheduled_in_seconds?: (number | null) | undefined}; export type AcceptanceAutomation = {auto_cancel: boolean, cancel_before_scheduled_in_seconds?: (number | null) | undefined}; export type OpsGroupOrderTrackingAutomation = {mode?: ('auto' | 'auto_start' | 'auto_stop' | 'null' | null) | undefined, lead_time?: (number | null) | undefined, lag_time?: (number | null) | undefined, type: 'manual' | 'shift' | 'order' | 'route' | 'order_and_route', approval?: (ApprovalAutomation | unknown) | undefined, acceptance?: (AcceptanceAutomation | unknown) | undefined}; export type WorkStatusAutomation = {mode?: ('auto' | 'auto_start' | 'auto_stop' | 'null' | null) | undefined, type: 'manual' | 'tracking' | 'available'}; export type LocationGeometry = {type: 'Point', coordinates: Array}; export type OpsGroupHomeRequest = {geometry: LocationGeometry, address?: (string | null) | undefined}; export type OpsGroupDateSchedule = {start_time: string, end_time: string, date: string, priority?: (number | null) | undefined}; export type OpsGroupRecurringSchedule = {start_time: string, end_time: string, day_of_week: 'SUNDAY' | 'MONDAY' | 'TUESDAY' | 'WEDNESDAY' | 'THURSDAY' | 'FRIDAY' | 'SATURDAY', priority?: (number | null) | undefined}; export type PostOpsGroupRequest = {ops_group_handle: string, ops_group_label: string, route_start_location?: ('driver_home' | 'ops_group_home' | 'live_location') | undefined, route_completion_type?: ('end_at_last_order' | 'return_to_start_location' | 'manual') | undefined, objective_fn?: ('minimise_time' | 'minimise_distance' | 'null' | null) | undefined, order_tracking_mode?: (string | null) | undefined, order_tracking_automation?: (OpsGroupOrderTrackingAutomation | unknown) | undefined, work_status_automation?: (Array | null) | undefined, ops_group_home?: (OpsGroupHomeRequest | unknown) | undefined, default_shift_start_time?: (string | null) | undefined, default_shift_end_time?: (string | null) | undefined, route_capacity?: (number | null) | undefined, route_max_distance?: (number | null) | undefined, operations_radius?: (number | null) | undefined, enforce_operations_radius?: (boolean | null) | undefined, timezone?: string | undefined, shift_availability_mode?: ('auto' | 'manual' | 'null' | null) | undefined, schedule?: (Array | null) | undefined, app_config?: ({[key: string]: unknown} | null) | undefined}; export type CreateApiWorkersOpsGroupsArgs = {body: PostOpsGroupRequest}; export type CreateApiWorkersOpsGroupsOptions = {baseUrl?: string | undefined, BasicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const locationGeometry = z.object({type: z.literal("Point"), coordinates: z.array(z.number())}); export const opsGroupHome = z.object({geometry: locationGeometry, address: z.string().nullable().optional()}); export const opsGroupDateSchedule = z.object({start_time: z.string(), end_time: z.string(), date: z.string(), priority: z.number().int().nullable().optional()}); export const opsGroupRecurringSchedule = z.object({start_time: z.string(), end_time: z.string(), day_of_week: z.enum(["SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"]), priority: z.number().int().nullable().optional()}); export const approvalAutomation = z.object({auto_cancel: z.boolean(), cancel_before_scheduled_in_seconds: z.number().int().nullable().optional()}); export const acceptanceAutomation = z.object({auto_cancel: z.boolean(), cancel_before_scheduled_in_seconds: z.number().int().nullable().optional()}); export const opsGroupOrderTrackingAutomation = z.object({mode: z.enum(["auto", "auto_start", "auto_stop", "null"]).nullable().optional(), lead_time: z.number().int().gte(0).lte(86399).nullable().optional(), lag_time: z.number().int().gte(0).lte(86399).nullable().optional(), type: z.enum(["manual", "shift", "order", "route", "order_and_route"]), approval: z.union([approvalAutomation, z.unknown()]).optional(), acceptance: z.union([acceptanceAutomation, z.unknown()]).optional()}); export const workStatusAutomation = z.object({mode: z.enum(["auto", "auto_start", "auto_stop", "null"]).nullable().optional(), type: z.enum(["manual", "tracking", "available"])}); export const postOpsGroupResponse = z.object({ops_group_handle: z.string(), ops_group_label: z.string(), timezone: z.string(), route_start_location: z.string().optional(), route_completion_type: z.string().optional(), objective_fn: z.string().optional(), ops_group_home: opsGroupHome.optional(), default_shift_start_time: z.string().optional(), default_shift_end_time: z.string().optional(), route_capacity: z.number().int(), route_max_distance: z.number().int(), deleted: z.boolean().optional(), deleted_at: z.string().optional(), shift_availability_mode: z.string(), order_tracking_mode: z.string().nullable().optional(), schedule: z.array(z.union([opsGroupDateSchedule, opsGroupRecurringSchedule])).nullable().optional(), order_tracking_automation: z.union([opsGroupOrderTrackingAutomation, z.unknown()]).optional(), work_status_automation: z.array(workStatusAutomation).nullable().optional(), app_config: z.record(z.string(), z.unknown()).nullable().optional(), operations_radius: z.number().int().nullable().optional(), enforce_operations_radius: z.boolean().nullable().optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Create Ops Group * * POST /workers/ops-groups/ * * Also accepts auth: TokenAuth */ export const createApiWorkersOpsGroups = async (args: CreateApiWorkersOpsGroupsArgs, options?: CreateApiWorkersOpsGroupsOptions) => { const {baseUrl = "https://v3.api.hypertrack.com", fetch: fetchFn = fetch, BasicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (BasicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${BasicAuth.username}:${BasicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/workers/ops-groups/${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(postOpsGroupResponse, await res.json()) };