import {z} from 'zod' export type Order = {id: string, pickup: {lat?: number | undefined, lng?: number | undefined}, dropoffs?: (Array<{lat?: number | undefined, lng?: number | undefined}>) | undefined, service_time?: number | undefined, vehicle_preferences?: ({required_all_of_attributes?: Array<{attribute: string, value: string, operator: string}> | undefined, required_any_of_attributes?: Array<{attribute: string, value: string, operator: string}> | undefined, exclude_all_of_attributes?: Array<{attribute: string, value: string, operator: string}> | undefined}) | undefined, priority?: number | undefined, attributes?: Record | undefined}; export type Location = {lat: number, lon: number}; export type Vehicle = {id: string, location: Location, attributes?: Record | undefined, remaining_waypoints?: Array | undefined, priority?: number | undefined}; export type CreateApiOptimizationDriverAssignmentV1Args = {key: unknown, body: {orders: Array, vehicles: Array, filter: {radius?: number | undefined, pickup_eta?: number | undefined, driving_distance?: number | undefined}, options?: ({travel_cost?: ('driving_eta' | 'driving_distance' | 'straight_line_distance') | undefined, dropoff_details?: boolean | undefined, order_attribute_priority_mappings?: Array<{attribute: string, value: string, operator: string, priority: string}> | undefined, vehicle_attribute_priority_mappings?: Array<{attribute: string, value: string, operator: string, priority: string}> | undefined}) | undefined}}; export type CreateApiOptimizationDriverAssignmentV1Options = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const location = z.object({lat: z.number().gte(-90).lte(90), lon: z.number().gte(-180).lte(180)}); export const createApiOptimizationDriverAssignmentV1Response = z.object({status: z.number().int().optional(), message: z.string().optional(), result: z.object({trips: z.array(z.object({trip_id: z.string().optional(), vehicle: z.object({id: z.string().optional(), steps: z.object({type: z.enum(["pickup", "dropoff", "ongoing"]).optional(), order_id: z.string().optional(), location: location.optional(), distance: z.number().int().optional(), eta: z.number().int().optional()}).optional(), vehicle_current_location: location.optional()}).optional()})).optional(), unassigned_orders: z.array(z.object({order_id: z.string().optional(), unassigned_reason: z.string().optional()})).optional(), available_vehicles: z.array(z.string()).optional(), alternate_assignments: z.array(z.object({order_id: z.string().optional(), assignments: z.array(z.object({vehicle_id: z.string().optional(), pickup_eta: z.number().int().optional()})).optional()})).optional()}).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 }; /** * Assign Drivers to Orders * * POST /optimization/driver-assignment/v1 */ export const createApiOptimizationDriverAssignmentV1 = async (args: CreateApiOptimizationDriverAssignmentV1Args, options?: CreateApiOptimizationDriverAssignmentV1Options) => { const {baseUrl = "https://api.nextbillion.io", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.key != null) query.append("key", String(args.key)) if (apiKey !== undefined) query.set("key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/optimization/driver-assignment/v1${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(createApiOptimizationDriverAssignmentV1Response, await res.json()) };