import {z} from 'zod' export type AppSchemasDocumentDiscount = {percentage?: (number | null) | undefined, factor?: (number | null) | undefined, base?: (number | null) | undefined, amount?: (number | null) | undefined, discount_type_id?: (string | null) | undefined, descripcion?: (string | null) | undefined, descuento_con_impuesto?: (boolean | null) | undefined}; export type ISC = {codigo: string, monto: number, porcentaje?: number | undefined, base?: number | undefined, factor?: (number | null) | undefined, total?: (number | null) | undefined}; export type AppSchemasDocumentDocumentItemCreate = {item_id?: (number | null) | undefined, unidad: string | null, codigo?: (string | null) | undefined, descripcion: string, nota?: (string | null) | undefined, documento_id?: (number | null) | undefined, cantidad?: number | undefined, precio: number, total?: (number | null) | undefined, tipo_tax: number | number | null, porcentaje_igv?: (number | null) | undefined, descuento: number, codigo_descuento?: (string | null) | undefined, descuento_con_impuesto?: (boolean | null) | undefined, incluye_tax?: (boolean | null) | undefined, discount?: (AppSchemasDocumentDiscount | null) | undefined, isc?: (ISC | null) | undefined, bolsa_tax?: (number | null) | undefined, has_plastic_bag_taxes?: (boolean | null) | undefined, monto_icbper?: (number | null) | undefined, total_icbper?: (number | null) | undefined}; export type PaymentConditionCreate = {tipo_de_condicion?: (string | number) | undefined, forma_de_pago: number | string | null, fecha?: (string | null) | undefined, monto: number, id?: (number | null) | undefined, description?: string | undefined, name?: (string | null) | undefined}; export type AppSchemasDocumentDocumentTotalCreate = {monto_descuento_global?: number | undefined, descuento_con_impuesto?: (boolean | null) | undefined, monto_otros_cargos?: number | undefined, rc?: number | undefined, total_rc?: number | undefined, monto_anticipo?: number | undefined}; export type DocumentRetentionCreate = {codigo?: (string | null) | undefined}; export type AppSchemasDocumentDocumentDetractionCreate = {codigo?: (string | null) | undefined, forma_de_pago?: (string | null) | undefined}; export type DocumentTransportChargeCreate = {ubigeo_origen?: (string | null) | undefined, direccion_origen?: (string | null) | undefined, ubigeo_destino?: (string | null) | undefined, direccion_destino?: (string | null) | undefined, valor_referencial_servicio_de_transporte?: (string | null) | undefined, valor_referencial_carga_efectiva?: (string | null) | undefined, valor_referencial_carga_util?: (string | null) | undefined, detalle_del_viaje?: (string | null) | undefined}; export type AppSchemasDocumentDocumentAnticipationCreate = {tipo_documento?: (string | null) | undefined, codigo_tipo_documento?: (number | string | null) | undefined, serie?: (string | null) | undefined, numero?: (number | null) | undefined, total?: (number | null) | undefined}; export type AppSchemasDocumentAnticipationCreate = {total: number | null, total_value: number | null, total_taxed: number | null, documents: Array | null}; export type DocumentGuideCreate = {tipo_documento: string, tipo_documento_codigo?: (number | string | null) | undefined, serie: string, numero: string}; export type DocumentInvoiceCreate = {tipo_documento?: (string | null) | undefined, codigo_tipo_documento?: (number | string | null) | undefined, serie?: (string | null) | undefined, numero?: (number | null) | undefined}; export type SupplierOut = {proveedor_tipo_documento: string, proveedor_denominacion: string, proveedor_numero_documento: string, proveedor_email?: (string | string | null) | undefined, proveedor_telefono?: (string | null) | undefined, proveedor_distrito_id?: (string | null) | undefined, proveedor_direccion?: (string | null) | undefined, document_type_code?: (number | string | null) | undefined, id?: (number | null) | undefined, user_id?: (number | null) | undefined}; export type DeliveryStatus = 'pendiente' | 'parcial' | 'completo'; export type PaymentVerificationStatusEnum = 'por_confirmar' | 'confirmado' | 'rechazado' | 'anulado'; export type PaymentAttachmentOutInput = {name: string, url: string, path?: (string | null) | undefined, size?: (number | null) | undefined, content_type?: (string | null) | undefined, extension?: (string | null) | undefined}; export type PaymentDocumentInput = {id?: (number | null) | undefined, tipo_de_condicion?: number | undefined, forma_de_pago?: number | undefined, metodo_pago_nombre?: (string | null) | undefined, referencia?: (string | null) | undefined, monto?: (number | null) | undefined, moneda_id?: (number | null) | undefined, fecha?: (string | null) | undefined, estado?: (string | null) | undefined, verification_status?: (PaymentVerificationStatusEnum | null) | undefined, serie?: (string | null) | undefined, numero?: (number | null) | undefined, adjunto?: (PaymentAttachmentOutInput | null) | undefined}; export type PurchaseCreate = {serie?: (string | null) | undefined, numero?: (number | string | null) | undefined, fecha_de_emision?: (string | string | null) | undefined, hora_de_emision?: (string | string | null) | undefined, fecha_de_vencimiento?: (string | null) | undefined, tasa_de_cambio?: (number | null) | undefined, tipo_operacion?: (number | string | null) | undefined, moneda?: (string | null) | undefined, moneda_id?: (number | string | null) | undefined, establecimiento_id?: (number | null) | undefined, tipo_documento_id?: (number | string | null) | undefined, proveedor_id?: (number | null) | undefined, fecha_entrega?: (string | null) | undefined, estado_doc?: (string | null) | undefined, estado_pago?: (string | null) | undefined, items?: (Array | null) | undefined, condicion_de_pago?: (Array | null) | undefined, totales?: (AppSchemasDocumentDocumentTotalCreate | null) | undefined, retencion?: (DocumentRetentionCreate | null) | undefined, codigo_retencion?: (string | null) | undefined, retencion_id?: (number | null) | undefined, detraccion?: (AppSchemasDocumentDocumentDetractionCreate | null) | undefined, datos_transporte_carga?: (DocumentTransportChargeCreate | null) | undefined, anticipos?: (Array | null) | undefined, anticipo?: (AppSchemasDocumentAnticipationCreate | null) | undefined, documento_relacionados?: (Array | null) | undefined, documento_afectado?: (DocumentInvoiceCreate | null) | undefined, observaciones?: (string | null) | undefined, total_venta?: (number | null) | undefined, total_exportacion?: (number | null) | undefined, total_exonerado?: (number | null) | undefined, total_inafecto?: (number | null) | undefined, total_gratuito?: (number | null) | undefined, total_gravado?: (number | null) | undefined, total_igv?: (number | null) | undefined, total_valor?: (number | null) | undefined, total_pagado?: (number | null) | undefined, total_descuento?: (number | null) | undefined, total_cargo?: (number | null) | undefined, total_rc?: (number | null) | undefined, total_retencion?: (number | null) | undefined, total_icbp?: (number | null) | undefined, total_base_isc?: (number | null) | undefined, total_isc?: (number | null) | undefined, descuento?: (AppSchemasDocumentDiscount | null) | undefined, taxe?: (number | null) | undefined, user_id?: (number | null) | undefined, company_id?: (number | null) | undefined, is_demo?: (boolean | null) | undefined, body_request: unknown, logs?: (Array | null) | undefined, orden_compra_id?: (number | null) | undefined, condicion_pago_id: number | null, proveedor?: (SupplierOut | null) | undefined, estado_entrega?: (DeliveryStatus | null) | undefined, pagos?: (Array | null) | undefined}; export type CreateApiPurchasesArgs = {'X-Company-Token': string, body: PurchaseCreate}; export type CreateApiPurchasesOptions = {baseUrl: string, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const purchaseItemOut = z.object({id: z.number().int(), item_id: z.number().int().nullable().optional(), quantity: z.number(), value: z.number().nullable().optional(), unit_value: z.number().nullable().optional(), price: z.number().nullable().optional(), total: z.number(), total_value: z.number().nullable().optional(), total_base_igv: z.number().nullable().optional(), total_igv: z.number().nullable().optional(), total_taxes: z.number().nullable().optional(), total_discount: z.number().nullable().optional(), price_with_taxes: z.boolean().nullable().optional(), item: z.unknown(), taxe: z.unknown(), discount: z.unknown()}); export const purchaseOut = z.object({id: z.number().int(), orden_compra_id: z.number().int().nullable().optional(), serie: z.string().nullable().optional(), number: z.union([z.number().int(), z.string()]).nullable().optional(), document_type_id: z.number().int().nullable().optional(), proveedor_id: z.number().int().nullable().optional(), proveedor: z.record(z.string(), z.unknown()).nullable().optional(), establecimiento_id: z.number().int().nullable().optional(), tipo_moneda_id: z.number().int().nullable().optional(), tasa_de_cambio: z.number().nullable().optional(), fecha_emision: z.string().nullable().optional(), fecha_entrega: z.string().nullable().optional(), estado_doc: z.string().nullable().optional(), estado_pago: z.string().nullable().optional(), estado_entrega: z.string().nullable().optional(), taxe: z.number().nullable().optional(), total_gravado: z.number().nullable().optional(), total_igv: z.number().nullable().optional(), total_valor: z.number().nullable().optional(), total: z.number().nullable().optional(), total_descuento: z.number().nullable().optional(), observations: z.string().nullable().optional(), condicion_de_pago: z.array(z.record(z.string(), z.unknown())).nullable().optional(), items: z.array(purchaseItemOut).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 }; /** * Store * * POST /purchases */ export const createApiPurchases = async (args: CreateApiPurchasesArgs, options: CreateApiPurchasesOptions) => { 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(/\/+$/, '')}/purchases${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(purchaseOut, await res.json()) };