import {z} from 'zod' export type PurchaseOrderSortOptions = 'createdAt' | 'reference'; export type SortDirection = 'ascending' | 'descending'; export type GetApiV1FinancePurchaseOrdersArgs = {'Customer-Id': number, sortBy?: PurchaseOrderSortOptions | undefined, direction?: SortDirection | undefined, id?: Array | undefined, jobId?: Array | undefined, jobGroupId?: Array | undefined, contactId?: Array | undefined, reference?: Array | undefined, createdAtFrom?: string | undefined, createdAtTo?: string | undefined, pageNumber?: number | undefined, pageSize?: number | undefined}; export type GetApiV1FinancePurchaseOrdersOptions = {baseUrl?: string | undefined, bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const currencyRead = z.enum(["EUR", "AUD", "GBP", "BGN", "CAD", "CZK", "DKK", "HUF", "ILS", "LVL", "LTL", "MXN", "NZD", "NOK", "PLN", "RON", "RUB", "ZAR", "SEK", "CHF", "AED", "USD", "UNKNOWN"]); export const customFieldType = z.enum(["boolean", "integer", "decimal", "text", "list", "statement", "date", "note", "time", "systemList"]); export const customFieldEmbeddedDefinitionModel = z.object({caption: z.string().optional(), type: customFieldType.optional(), listOptions: z.array(z.string()).nullable().optional(), isRequired: z.boolean().optional(), isEditable: z.boolean().optional(), default: z.string().nullable().optional()}); export const customFieldSystemListType = z.enum(["resource", "vehicle", "webUser"]); export const systemListValueMetadataModel = z.object({label: z.string().nullable().optional(), entityType: customFieldSystemListType.optional()}); export const customFieldReadModel = z.object({definitionId: z.number().int().optional(), value: z.string().nullable().optional(), definition: customFieldEmbeddedDefinitionModel.optional(), systemListValueMetadata: systemListValueMetadataModel.optional()}); export const readPurchaseOrderModel = z.object({id: z.number().int().optional(), jobId: z.number().int().nullable().optional(), jobGroupId: z.number().int().nullable().optional(), contactId: z.number().int().optional(), seriesId: z.number().int().nullable().optional(), contractId: z.number().int().nullable().optional(), supplierId: z.number().int().nullable().optional(), createdAt: z.string().optional(), reference: z.string().optional(), currencyCode: currencyRead.optional(), deliverySiteContactId: z.number().int().nullable().optional(), clientNotes: z.string().optional(), internalNotes: z.string().optional(), sentAt: z.string().nullable().optional(), cancelledAt: z.string().nullable().optional(), receivedAt: z.string().nullable().optional(), cost: z.number().nullable().optional(), totalExclTax: z.number().optional(), totalInclTax: z.number().optional(), totalPaid: z.number().optional(), salesOpportunityId: z.number().int().nullable().optional(), customFields: z.array(customFieldReadModel).optional()}); export const pagedResponseReadPurchaseOrderModel = z.object({items: z.array(readPurchaseOrderModel).optional(), pageNumber: z.number().int().optional(), pageSize: z.number().int().optional(), pageItemCount: z.number().int().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 }; /** * Get a list of purchase orders * * GET /v1/finance/purchaseOrders */ export const getApiV1FinancePurchaseOrders = async (args: GetApiV1FinancePurchaseOrdersArgs, options?: GetApiV1FinancePurchaseOrdersOptions) => { const {baseUrl = "https://api.bigchange.com", fetch: fetchFn = fetch, bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args['Customer-Id'] != null) headers.set("Customer-Id", String(args['Customer-Id'])) if (args.sortBy != null) query.append("sortBy", String(args.sortBy)) if (args.direction != null) query.append("direction", String(args.direction)) for (const item of args.id ?? []) query.append("id", String(item)) for (const item of args.jobId ?? []) query.append("jobId", String(item)) for (const item of args.jobGroupId ?? []) query.append("jobGroupId", String(item)) for (const item of args.contactId ?? []) query.append("contactId", String(item)) for (const item of args.reference ?? []) query.append("reference", String(item)) if (args.createdAtFrom != null) query.append("createdAtFrom", String(args.createdAtFrom)) if (args.createdAtTo != null) query.append("createdAtTo", String(args.createdAtTo)) if (args.pageNumber != null) query.append("pageNumber", String(args.pageNumber)) if (args.pageSize != null) query.append("pageSize", String(args.pageSize)) if (bearer !== undefined) headers.set('authorization', `Bearer ${bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/finance/purchaseOrders${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(pagedResponseReadPurchaseOrderModel, await res.json()) };