import {z} from 'zod' export type EqFilter = {eq: string}; export type IncludeFilter = {include: string}; export type LtLteGtGteFilter = {lt: string} | {lte: string} | {gt: string} | {gte: string}; export type SortAscDescDefaultDesc = 'asc' | 'desc'; export type SortAscDesc = 'asc' | 'desc'; export type GetApiPurchaseOrdersArgs = {start_cursor?: string | undefined, per_page?: number | undefined, filter?: ({number?: EqFilter | undefined, part_location_id?: EqFilter | undefined, rejected_by_id?: EqFilter | undefined, submitted_for_approval_by_id?: EqFilter | undefined, purchased_by_id?: EqFilter | undefined, created_by_id?: EqFilter | undefined, approved_by_id?: EqFilter | undefined, vendor_id?: EqFilter | undefined, state?: IncludeFilter | undefined, labels?: IncludeFilter | undefined, created_at?: LtLteGtGteFilter | undefined, updated_at?: LtLteGtGteFilter | undefined}) | undefined, sort?: ({id?: SortAscDescDefaultDesc | undefined, created_at?: SortAscDesc | undefined, updated_at?: SortAscDesc | undefined}) | undefined}; export type GetApiPurchaseOrdersOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, accountToken?: string | undefined, fetch?: typeof fetch | undefined}; export const eqFilter = z.object({eq: z.string()}); export const includeFilter = z.object({include: z.string()}); export const ltLteGtGteFilter = z.union([z.object({lt: z.string()}), z.object({lte: z.string()}), z.object({gt: z.string()}), z.object({gte: z.string()})]); export const sortAscDesc = z.enum(["asc", "desc"]); export const purchaseOrderState = z.enum(["draft", "submitted_for_approval", "rejected", "approved", "purchased", "received_partial", "received_full", "closed"]).nullable(); export const customFields = z.object({}).nullable(); export const id = z.number().int().gte(1); export const labels = z.array(z.object({id: id.optional(), name: z.string().optional()})); export const vendorMini = z.object({name: z.string(), phone: z.string().nullable(), city: z.string().nullable(), region: z.string().nullable(), postal_code: z.string().nullable(), country: z.string().nullable(), external_id: z.string().nullable()}).nullable(); export const purchaseOrderSummary = z.object({id: z.number().int(), number: z.number().int(), description: z.string().nullable(), state: purchaseOrderState, documents_count: z.number().int(), comments_count: z.number().int(), watchers_count: z.number().int(), discount_type: z.string().nullable(), tax_1_type: z.string().nullable(), tax_2_type: z.string().nullable(), submitted_for_approval_at: z.string().nullable(), rejected_at: z.string().nullable(), approved_at: z.string().nullable(), purchased_at: z.string().nullable(), received_partial_at: z.string().nullable(), received_full_at: z.string().nullable(), closed_at: z.string().nullable(), created_at: z.string().nullable(), updated_at: z.string().nullable(), discount_cents: z.number().int().nullable(), tax_1_cents: z.number().int().nullable(), tax_1_percentage: z.string().nullable(), tax_2_cents: z.number().int().nullable(), tax_2_percentage: z.string().nullable(), subtotal_cents: z.number().int().nullable(), shipping_cents: z.number().int().nullable(), total_amount_cents: z.number().int().nullable(), vendor_id: z.number().int().nullable(), approved_by_id: z.number().int().nullable(), created_by_id: z.number().int().nullable(), closed_by_id: z.number().int().nullable(), purchased_by_id: z.number().int().nullable(), rejected_by_id: z.number().int().nullable(), received_partial_by_id: z.number().int().nullable(), received_full_by_id: z.number().int().nullable(), submitted_for_approval_by_id: z.number().int().nullable(), purchase_order_status_id: z.number().int().nullable(), part_location_id: z.number().int().nullable(), custom_fields: customFields.optional(), labels: labels, vendor: vendorMini}); export const getApiPurchaseOrdersResponse = z.object({start_cursor: z.string().nullable().optional(), next_cursor: z.string().nullable().optional(), per_page: z.number().int().optional(), estimated_remaining_count: z.number().int().optional(), filtered_by: z.array(z.union([z.object({number: eqFilter.optional()}), z.object({part_location_id: eqFilter.optional()}), z.object({rejected_by_id: eqFilter.optional()}), z.object({submitted_for_approval_by_id: eqFilter.optional()}), z.object({purchased_by_id: eqFilter.optional()}), z.object({created_by_id: eqFilter.optional()}), z.object({approved_by_id: eqFilter.optional()}), z.object({vendor_id: eqFilter.optional()}), z.object({state: includeFilter.optional()}), z.object({labels: includeFilter.optional()}), z.object({created_at: ltLteGtGteFilter.optional()}), z.object({updated_at: ltLteGtGteFilter.optional()})])).optional(), sorted_by: z.array(z.union([z.object({updated_at: sortAscDesc.optional()}), z.object({created_at: sortAscDesc.optional()}), z.object({id: sortAscDesc.optional()})])).optional(), records: z.array(purchaseOrderSummary).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 }; /** * List Purchase Orders * * GET /purchase_orders */ export const getApiPurchaseOrders = async (args: GetApiPurchaseOrdersArgs, options?: GetApiPurchaseOrdersOptions) => { const {baseUrl = "https://secure.fleetio.com/api", fetch: fetchFn = fetch, apiKey, accountToken} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.start_cursor != null) query.append("start_cursor", String(args.start_cursor)) if (args.per_page != null) query.append("per_page", String(args.per_page)) if (args.filter != null) query.append("filter", JSON.stringify(args.filter)) if (args.sort != null) query.append("sort", JSON.stringify(args.sort)) if (apiKey !== undefined) headers.set("Authorization", apiKey) if (accountToken !== undefined) headers.set("Account-Token", accountToken) const url = `${baseUrl.replace(/\/+$/, '')}/purchase_orders${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(getApiPurchaseOrdersResponse, await res.json()) };