import {z} from 'zod' export type LikeEqFilter = {like: string} | {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 GetApiServiceEntriesArgs = {start_cursor?: string | undefined, per_page?: number | undefined, filter?: ({reference?: LikeEqFilter | undefined, status?: IncludeFilter | undefined, labels?: IncludeFilter | undefined, completed_at?: LtLteGtGteFilter | undefined, created_at?: LtLteGtGteFilter | undefined, updated_at?: LtLteGtGteFilter | undefined}) | undefined, sort?: ({id?: SortAscDescDefaultDesc | undefined, completed_at?: SortAscDesc | undefined, updated_at?: SortAscDesc | undefined, created_at?: SortAscDesc | undefined}) | undefined}; export type GetApiServiceEntriesOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, accountToken?: string | undefined, fetch?: typeof fetch | undefined}; export const likeEqFilter = z.union([z.object({like: z.string()}), 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 autoIntegrateRepairOrderStatus = z.enum(["approved", "auto_approved", "awaiting_reconciliation", "awaiting_invoice", "awaiting_payment", "completed", "failed_reconciliation", "invoiced", "needs_approval", "needs_reapproval", "paid", "rejected"]).nullable(); export const nullableId = z.number().int().gte(1).nullable(); export const vehicleMeterEntry = z.object({id: z.number().int().optional(), created_at: z.string().optional(), updated_at: z.string().optional(), auto_voided_at: z.string().nullable().optional(), category: z.enum(["starting", "ending", "nightly", "manual"]).nullable().optional(), meter_type: z.literal("secondary").nullable().optional(), meterable_id: nullableId.optional(), meterable_type: z.enum(["FuelEntry", "Issue", "PurchaseDetail", "ServiceEntry", "SubmittedInspectionItem", "VehicleAssignment", "WorkOrder"]).nullable().optional(), value: z.string().optional(), vehicle_id: nullableId.optional(), void: z.boolean().optional(), type: z.literal("GpsMeterEntry").nullable().optional(), date: z.string().optional()}).nullable(); export const attachmentPermissions = z.object({read_photos: z.boolean().optional(), manage_photos: z.boolean().optional(), read_documents: z.boolean().optional(), manage_documents: z.boolean().optional()}).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 vehicleMini = z.object({id: z.number().int(), name: z.string(), color: z.string().nullable().optional(), license_plate: z.string().nullable().optional(), vin: z.string().nullable().optional(), year: z.string().nullable().optional(), make: z.string().nullable().optional(), model: z.string().nullable().optional(), trim: z.string().nullable().optional(), registration_expiration_month: z.number().int().gte(0).lte(12).nullable().optional(), registration_state: z.string().nullable().optional(), default_image_url_small: z.string().nullable().optional()}); export const discountType = z.enum(["fixed", "percentage"]).nullable(); export const serviceEntrySummary = z.object({auto_integrate_repair_order_status: autoIntegrateRepairOrderStatus, images_count: z.number().int().gte(0), documents_count: z.number().int().gte(0), comments_count: z.number().int().gte(0), id: z.number().int(), completed_at: z.string().nullable(), reference: z.string().nullable(), started_at: z.string().nullable(), status: z.enum(["pending", "completed"]), general_notes: z.string().nullable(), vehicle_id: z.number().int(), vendor_id: z.number().int().nullable(), work_order_id: z.number().int().nullable(), is_sample: z.boolean(), primary_meter_entry: vehicleMeterEntry, secondary_meter_entry: vehicleMeterEntry.optional(), attachment_permissions: attachmentPermissions.optional(), custom_fields: customFields.optional(), labels: labels, vendor: vendorMini.optional(), vehicle: vehicleMini.optional(), discount_type: discountType.optional(), discount_percentage: z.string().nullable().optional(), tax_1_type: z.string().optional(), tax_1_percentage: z.string().nullable().optional(), tax_2_type: z.string().nullable().optional(), tax_2_percentage: z.string().nullable().optional(), labor_subtotal_cents: z.number().int().optional(), parts_subtotal_cents: z.number().int().optional(), fees_cents: z.number().int().optional(), subtotal_cents: z.number().int().optional(), discount_cents: z.number().int().optional(), tax_1_cents: z.number().int().optional(), tax_2_cents: z.number().int().optional(), total_amount_cents: z.number().int().optional(), labor_time_in_seconds: z.number().int().nullable().optional()}); export const getApiServiceEntriesResponse = 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({reference: likeEqFilter.optional()}), z.object({status: includeFilter.optional()}), z.object({labels: includeFilter.optional()}), z.object({completed_at: ltLteGtGteFilter.optional()}), z.object({created_at: ltLteGtGteFilter.optional()}), z.object({updated_at: ltLteGtGteFilter.optional()})])).optional(), sorted_by: z.array(z.union([z.object({completed_at: sortAscDesc.optional()}), z.object({updated_at: sortAscDesc.optional()}), z.object({created_at: sortAscDesc.optional()}), z.object({id: sortAscDesc.optional()})])).optional(), records: z.array(serviceEntrySummary).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 Service Entries * * GET /service_entries */ export const getApiServiceEntries = async (args: GetApiServiceEntriesArgs, options?: GetApiServiceEntriesOptions) => { 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(/\/+$/, '')}/service_entries${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(getApiServiceEntriesResponse, await res.json()) };