import {z} from 'zod' export type QuoteStop = {sequence: number, stopActivity: 'PICKUP' | 'DELIVERY', address: {city: string, stateOrProvince: string, postalCode?: (string | null) | undefined, country: 'US' | 'CA' | 'MX'}}; export type QuoteEquipmentType = 'DRY_VAN' | 'REEFER' | 'FLATBED' | 'FLATBED_WITH_TARPS' | 'FLATBED_OVERDIMENSION' | 'FLATBED_STRETCH' | 'STEP_DECK' | 'STEP_DECK_OR_REM_GOOSENECK_RGN' | 'DOUBLE_DROP' | 'LOWBOY' | 'LOWBOY_OR_REM_GOOSENECK_RGN' | 'LOWBOY_OVERDIMENSION' | 'REMOVABLE_GOOSENECK' | 'CONESTOGA' | 'STRETCH_TRAILER' | 'WALKING_FLOOR' | 'OTHER'; export type AccessorialsEnum = string; export type QuoteReferenceNumberName = 'TENDER_NUMBER' | 'PO_NUMBER' | 'BOL_NUMBER' | 'OTHER'; export type QuoteContact = {role: 'QUOTE_OWNER' | 'QUOTE_REQUESTER', name?: (string | null) | undefined, email?: (string | null) | undefined}; export type QuoteEmailAddress = {name?: (string | null) | undefined, address: string}; export type QuoteEmail = {direction?: 'INBOUND' | undefined, messageId?: (string | null) | undefined, sentAt?: (string | null) | undefined, subject?: (string | null) | undefined, participants?: ({from?: QuoteEmailAddress | undefined, to?: Array | undefined, cc?: Array | undefined}) | undefined, body?: (string | null) | undefined, summary?: (string | null) | undefined, classification?: (string | null) | undefined, attachmentCount?: (number | null) | undefined} | null; export type RateQuoteRequest = {mode: 'DRAYAGE' | 'EXPEDITE' | 'FTL' | 'LTL' | 'PARTIAL', rateType: 'CONTRACT' | 'DEDICATED' | 'PROJECT' | 'SPOT', stops: Array, equipment: {equipmentType: QuoteEquipmentType}, weight?: ({value?: number | undefined, unit?: ('LB' | 'KG') | undefined} | null) | undefined, dimensions?: ({lengthInches?: number | undefined, widthInches?: number | undefined, heightInches?: number | undefined} | null) | undefined, commodity?: (string | null) | undefined, pickupDate?: (string | null) | undefined, totalMiles?: (number | null) | undefined, tarpSize?: (string | null) | undefined, isHazmat?: (boolean | null) | undefined, hazmatUnNumber?: (string | null) | undefined, accessorials?: (Array | null) | undefined, customerName?: (string | null) | undefined, augmentQuoteId: string, numberTruckloads?: (number | null) | undefined, wellspaceInches?: (number | null) | undefined, referenceNumbers?: (Array<{name: QuoteReferenceNumberName, value: string}> | null) | undefined, contacts?: Array | undefined, email?: QuoteEmail | undefined, customData?: ({[key: string]: unknown} | null) | undefined}; export type CreateApiRatesQuoteArgs = {body: RateQuoteRequest}; export type CreateApiRatesQuoteOptions = {baseUrl?: string | undefined, httpBasic?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const accessorialsEnum = z.string(); export const rateAccessorial = z.object({code: accessorialsEnum, label: z.string().nullable().optional(), amount: z.number(), basis: z.enum(["FLAT", "PER_MILE", "PER_STOP"])}); export const rate = z.object({source: z.string(), linehaul: z.number(), fuelSurcharge: z.number(), fuelSurchargePct: z.number().nullable().optional(), allInTotal: z.number(), costPerMile: z.number().nullable().optional(), marginPct: z.number().nullable().optional(), accessorials: z.array(rateAccessorial).optional()}); export const rateQuoteResponse = z.object({augmentQuoteId: z.string(), externalId: z.string().nullable().optional(), quotedAt: z.string(), currency: z.enum(["USD", "CAD"]), totalMiles: z.number().nullable().optional(), rates: z.array(rate), noRateReason: z.enum(["LANE_NOT_SERVICED", "NO_CAPACITY", "EQUIPMENT_NOT_SUPPORTED", "HAZMAT_NOT_SUPPORTED", "OVERSIZE_OUT_OF_SCOPE", "COMMODITY_RESTRICTED", "CUSTOMER_NOT_FOUND", "MISSING_REQUIRED_INPUT", "RATE_UNAVAILABLE", "OTHER", "null"]).nullable().optional(), noRateDetail: z.string().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 }; /** * Request a rate quote * * POST /rates/quote */ export const createApiRatesQuote = async (args: CreateApiRatesQuoteArgs, options?: CreateApiRatesQuoteOptions) => { const {baseUrl = "https://rates.example.com/v1", fetch: fetchFn = fetch, httpBasic} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (httpBasic !== undefined) headers.set('authorization', `Basic ${btoa(`${httpBasic.username}:${httpBasic.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/rates/quote${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(rateQuoteResponse, await res.json()) };