import {z} from 'zod' export type CreateApiPlansPlanIdStopsLiveCreateArgs = {planId: string, body: {address: {addressName?: (string | null) | undefined, addressLineOne?: (string | null) | undefined, addressLineTwo?: (string | null) | undefined, city?: (string | null) | undefined, state?: (string | null) | undefined, zip?: (string | null) | undefined, country?: (string | null) | undefined, latitude?: (number | null) | undefined, longitude?: (number | null) | undefined}, timing?: ({timeWindows?: (Array<{earliestAttemptTime: {hour: number, minute: number} | null, latestAttemptTime: {hour: number, minute: number} | null}>) | undefined, earliestAttemptTime?: ({hour: number, minute: number} | null) | undefined, latestAttemptTime?: ({hour: number, minute: number} | null) | undefined, estimatedAttemptDuration?: (number | null) | undefined} | null) | undefined, recipient?: ({externalId?: (string | null) | undefined, email?: (string | null) | undefined, phone?: (string | null) | undefined, name?: (string | null) | undefined} | null) | undefined, orderInfo?: ({products?: Array | undefined, invoiceNumber?: (string | null) | undefined, sellerOrderId?: (string | null) | undefined, sellerName?: (string | null) | undefined, sellerWebsite?: (string | null) | undefined} | null) | undefined, paymentOnDelivery?: ({amount?: (number | null) | undefined, currency?: ('AED' | 'ARS' | 'AUD' | 'BRL' | 'CAD' | 'CHF' | 'CLP' | 'CNY' | 'COP' | 'DKK' | 'EGP' | 'EUR' | 'GBP' | 'HKD' | 'HUF' | 'ILS' | 'INR' | 'JPY' | 'KRW' | 'MYR' | 'MXN' | 'NOK' | 'NZD' | 'PEN' | 'RON' | 'RUB' | 'SAR' | 'SEK' | 'SGD' | 'TRY' | 'USD' | 'UYU' | 'ZAR' | null) | undefined} | null) | undefined, proofOfAttemptRequirements?: ({enabled?: (boolean | null) | undefined} | null) | undefined, allowedDrivers?: (Array | null) | undefined, activity?: ('delivery' | 'pickup' | null) | undefined, optimizationOrder?: ('first' | 'last' | 'default' | null) | undefined, packageCount?: (number | null) | undefined, weight?: ({amount: number, unit: 'kilogram' | 'pound' | 'metric-ton'} | null) | undefined, notes?: (string | null) | undefined, clientId?: (string | null) | undefined, barcodes?: Array | undefined, customProperties?: ({[key: string]: string | null} | null) | undefined, serviceInfo?: ({identifier?: (string | null) | undefined, slaStartsAt?: (number | null) | undefined} | null) | undefined}}; export type CreateApiPlansPlanIdStopsLiveCreateOptions = {baseUrl?: string | undefined, BasicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const stopIdSchema = z.string(); export const planIdSchema = z.string(); export const routeIdSchema = z.string(); export const driverIdSchema = z.string(); export const routeSchema = z.object({id: routeIdSchema, title: z.string(), stopCount: z.number(), driver: driverIdSchema.nullable(), state: z.object({completed: z.boolean(), completedAt: z.number().nullable(), distributed: z.boolean(), distributedAt: z.number().nullable(), notifiedRecipients: z.boolean(), notifiedRecipientsAt: z.number().nullable(), started: z.boolean(), startedAt: z.number().nullable()}).nullable(), plan: planIdSchema.nullable()}); export const timeOfDaySchema = z.object({hour: z.number().int().gte(0).lte(23), minute: z.number().int().gte(0).lte(59)}); export const stopSchema = z.object({id: stopIdSchema, address: z.object({address: z.string(), addressLineOne: z.string(), addressLineTwo: z.string(), latitude: z.number().gte(-90).lte(90).nullable(), longitude: z.number().gte(-180).lte(180).nullable(), placeId: z.string().nullable(), placeTypes: z.array(z.string())}), barcodes: z.array(z.string()), allowedDrivers: z.array(z.string()), estimatedTravelDuration: z.number().nullable(), estimatedTravelDistance: z.number().nullable(), notes: z.string().nullable(), packageCount: z.number().nullable(), weight: z.object({amount: z.number().gte(0), unit: z.enum(["kilogram", "pound", "metric-ton"])}).nullable(), type: z.enum(["start", "stop", "end"]), packageLabel: z.string().nullable(), stopPosition: z.number().nullable(), trackingLink: z.string().nullable(), webAppLink: z.string(), orderInfo: z.object({products: z.array(z.string()), invoiceNumber: z.string().nullable(), sellerName: z.string().nullable(), sellerOrderId: z.string().nullable(), sellerWebsite: z.string().nullable()}), placeInVehicle: z.object({x: z.enum(["left", "right"]).nullable(), y: z.enum(["front", "back", "middle"]).nullable(), z: z.enum(["floor", "shelf"]).nullable()}).nullable(), recipient: z.object({name: z.string().nullable(), email: z.string().nullable(), phone: z.string().nullable(), externalId: z.string().nullable()}), activity: z.enum(["delivery", "pickup"]).optional(), deliveryInfo: z.object({attempted: z.boolean(), attemptedAt: z.number().nullable(), timeAtStopInfo: z.union([z.object({status: z.literal("available"), value: z.object({arrivedAt: z.number().nullable(), departedAt: z.number().nullable(), isEstimated: z.boolean().nullable()})}), z.object({status: z.literal("restricted"), requiredFeature: z.string().optional(), upgradeUrl: z.string().optional(), restrictionCode: z.literal("subscription_not_supported").optional()}), z.object({status: z.literal("pending"), pendingReason: z.literal("not_yet_arrived").optional()})]), attemptedLocation: z.object({latitude: z.number(), longitude: z.number()}).nullable(), driverProvidedInternalNotes: z.string().nullable(), driverProvidedRecipientNotes: z.string().nullable(), photoUrls: z.array(z.string()), recipientProvidedNotes: z.string().nullable(), signatureUrl: z.string().nullable(), signeeName: z.string().nullable(), succeeded: z.boolean(), state: z.enum(["delivered_to_recipient", "delivered_to_third_party", "delivered_to_mailbox", "delivered_to_safe_place", "delivered_to_pickup_point", "delivered_other", "picked_up_from_customer", "picked_up_unmanned", "picked_up_from_locker", "picked_up_other", "failed_not_home", "failed_cant_find_address", "failed_no_parking", "failed_no_time", "failed_package_not_available", "failed_other", "failed_missing_required_proof", "failed_payment_not_received", "unattempted"])}).nullable(), paymentOnDelivery: z.object({amount: z.number().int().gte(0).lte(9007199254740991).nullable(), currency: z.string()}).nullable(), proofOfAttemptRequirements: z.object({enabled: z.boolean().nullable()}), plan: planIdSchema, route: routeSchema.nullable(), eta: z.union([z.object({status: z.literal("available"), value: z.object({estimatedArrivalAt: z.number(), estimatedLatestArrivalAt: z.number(), estimatedEarliestArrivalAt: z.number()})}), z.object({status: z.literal("restricted"), requiredFeature: z.string().optional(), upgradeUrl: z.string().optional(), restrictionCode: z.literal("subscription_not_supported").optional()}), z.object({status: z.literal("pending"), pendingReason: z.literal("not_optimized").optional()})]), timing: z.object({timeWindows: z.array(z.object({earliestAttemptTime: timeOfDaySchema.nullable(), latestAttemptTime: timeOfDaySchema.nullable()})), estimatedAttemptDuration: z.number().nullable(), earliestAttemptTime: timeOfDaySchema.nullable(), latestAttemptTime: timeOfDaySchema.nullable()}), optimizationOrder: z.enum(["first", "last", "default"]).optional(), customProperties: z.record(z.string(), z.string().nullable()).nullable(), clientId: z.string().nullable(), serviceInfo: z.union([z.object({status: z.literal("available"), value: z.union([z.object({identifier: z.string(), name: z.string(), slaStartsAt: z.number(), slaDueDate: z.object({day: z.number().int().gte(1).lte(31), month: z.number().int().gte(1).lte(12), year: z.number().int().gte(2000).lte(2100)}), slaDueTime: timeOfDaySchema.nullable(), deliveryHorizon: z.object({unit: z.union([z.enum(["days", "hours"]), z.string()]), value: z.number()}), price: z.object({value: z.number(), currency: z.union([z.enum(["AED", "ARS", "AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "COP", "DKK", "EGP", "EUR", "GBP", "HKD", "HUF", "ILS", "INR", "JPY", "KRW", "MYR", "MXN", "NOK", "NZD", "PEN", "RON", "RUB", "SAR", "SEK", "SGD", "TRY", "USD", "UYU", "ZAR"]), z.string()])}), hasPaymentOnDelivery: z.boolean(), definedAt: z.number()}), z.object({identifier: z.unknown(), slaStartsAt: z.number()})])}), z.object({status: z.literal("empty")}), z.object({status: z.literal("restricted"), requiredFeature: z.string().optional(), upgradeUrl: z.string().optional(), restrictionCode: z.literal("subscription_not_supported").optional()})])}); export const createApiPlansPlanIdStopsLiveCreateResponse = z.object({pending: z.boolean(), stop: stopSchema}); 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 a new stop * * POST /plans/{planId}/stops:liveCreate */ export const createApiPlansPlanIdStopsLiveCreate = async (args: CreateApiPlansPlanIdStopsLiveCreateArgs, options?: CreateApiPlansPlanIdStopsLiveCreateOptions) => { const {baseUrl = "https://api.spoke.com/public/v1", 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(/\/+$/, '')}/plans/${encodeURIComponent(String(args.planId))}/stops:liveCreate${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(createApiPlansPlanIdStopsLiveCreateResponse, await res.json()) };