import {z} from 'zod' export type PersonOut = {cliente_tipo_documento: string, cliente_denominacion: string, cliente_numero_documento: string, cliente_email?: (string | string | null) | undefined, cliente_telefono?: (string | null) | undefined, distrito_id?: (string | null) | undefined, cliente_direccion?: (string | null) | undefined, document_type_code?: (number | string | null) | undefined, id?: (number | null) | undefined, user_id?: (number | null) | undefined}; export type Receiver = {destinatario_tipo_documento: string, destinatario_denominacion: string, destinatario_numero_documento: string, destinatario_email?: (string | string | null) | undefined, destinatario_telefono?: string | undefined, distrito_id?: (string | null) | undefined, destinatario_direccion?: string | undefined, document_type_code?: (number | string | null) | undefined, id?: (number | null) | undefined, user_id?: (number | null) | undefined}; export type Dispatcher = {codigo_tipo_documento_identidad?: string | undefined, transportista_numero_documento: string, transportista_denominacion: string, numero_registro_mtc?: string | undefined}; export type Driver = {conductor_tipo_documento: string, conductor_numero_documento: string, conductor_nombres_y_apellidos: string, conductor_numero_de_placa: string, conductor_numero_licencia: string, numero_de_autorizacion?: string | undefined}; export type SecondaryVehicle = {conductor_numero_de_placa: string, tuc?: string | undefined}; export type SecondaryConductor = {conductor_tipo_documento: string, conductor_numero_documento: string, conductor_nombres_y_apellidos: string, conductor_numero_licencia: string}; export type Delivery = {ubigeo: string, direccion: string, anexo_de_llegada?: (string | null) | undefined}; export type Origin = {ubigeo: string, direccion: string, anexo_de_partida?: (string | null) | undefined}; export type Purchase = {comprador_tipo_documento: string, comprador_numero_documento: string, comprador_denominacion: string}; export type Supplier = {proveedor_tipo_documento: string, proveedor_numero_documento: string, proveedor_denominacion: string}; export type Subcontractor = {subcontratador_tipo_documento: string, subcontratador_numero_documento: string, subcontratador_denominacion: string}; export type Third = {tercero_tipo_documento: string, tercero_numero_documento: string, tercero_denominacion: string}; export type Document = {tipo: string, serie?: (string | null) | undefined, numero: string}; export type DispatchItemCreate = {item_id?: (number | null) | undefined, guia_id?: (number | null) | undefined, codigo: string | null, cantidad?: number | undefined, descripcion: string, unidad: string | null, nota?: (string | null) | undefined, codigo_dam?: (string | null) | undefined}; export type DispatchCreate = {id?: (number | null) | undefined, tipo_documento: string | null, document_type_id?: number | undefined, serie?: string | undefined, numero?: (number | string) | undefined, fecha_de_emision?: (string | null) | undefined, hora_de_emision?: (string | null) | undefined, fecha_de_traslado: string, customer_id?: (number | null) | undefined, cliente?: (PersonOut | null) | undefined, receiver_id?: (number | null) | undefined, destinatario?: (Receiver | null) | undefined, establishment_id?: number | undefined, establishment_destiny_id?: (number | null) | undefined, peso_bruto_unidad: string | null, transshipment_indicator?: (boolean | null) | undefined, codigo_puerto?: (string | null) | undefined, numero_de_bultos?: (string | null) | undefined, peso_bruto_total: string | null, numero_container?: (string | null) | undefined, motivo_traslado?: (string | null) | undefined, codigo_modo_transporte?: (string | null) | undefined, transportista?: (Dispatcher | null) | undefined, conductor?: (Driver | null) | undefined, documentos: unknown, vehiculos_secundarios?: (Array | null) | undefined, conductores_secundarios?: (Array | null) | undefined, observaciones: string | null, descripcion_motivo_traslado?: (string | null) | undefined, pagador_flete?: (string | null) | undefined, user_id?: (number | null) | undefined, company_id?: (number | null) | undefined, is_demo?: boolean | undefined, filename?: (string | null) | undefined, external_id?: (string | null) | undefined, pdf?: (string | null) | undefined, xml?: (string | null) | undefined, cdr?: (string | null) | undefined, state_type_id?: (number | null) | undefined, direccion_llegada: Delivery, direccion_partida: Origin, num_ticket_sunat?: (string | null) | undefined, hash?: (string | null) | undefined, qr?: (string | null) | undefined, comprador?: (Purchase | null) | undefined, proveedor?: (Supplier | null) | undefined, subcontratador?: (Subcontractor | null) | undefined, tercero?: (Third | null) | undefined, indicador_de_transbordo?: (number | null) | undefined, numero_orden?: (string | null) | undefined, codigo?: (string | null) | undefined, orden_de_compra?: (string | null) | undefined, registro_vehiculo_conductor?: (boolean | null) | undefined, logs: unknown, documento_relacionados?: (Array | null) | undefined, body_request: unknown, items: Array, formato_pdf?: (string | null) | undefined, envio_indicador?: (number | string | null) | undefined, send_email_customer?: boolean | undefined}; export type CreateApiDispatchesArgs = {'X-Company-Token': string, body: DispatchCreate}; export type CreateApiDispatchesOptions = {baseUrl: string, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const dispatchDataOut = z.object({numero: z.string(), archivo: z.string(), hash: z.string().optional(), qr: z.string().optional(), tipo_estado: z.string().optional(), descripcion_estado: z.string().optional()}); export const dispatchFileOut = z.object({pdf: z.string().nullable().optional(), descargar_pdf: z.string().optional(), xml: z.string().optional(), cdr: z.string().optional()}); export const dispatchApiOut = z.object({exito: z.boolean().optional(), mensaje: z.string().optional(), data: dispatchDataOut, archivos: dispatchFileOut, eventos: z.array(z.unknown()).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 }; /** * Store * * POST /dispatches */ export const createApiDispatches = async (args: CreateApiDispatchesArgs, options: CreateApiDispatchesOptions) => { const {baseUrl, fetch: fetchFn = fetch, HTTPBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-Company-Token'] != null) headers.set("X-Company-Token", String(args['X-Company-Token'])) if (HTTPBearer !== undefined) headers.set('authorization', `Bearer ${HTTPBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/dispatches${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(dispatchApiOut, await res.json()) };