import {z} from 'zod' export type LtLteGtGteFilter = {lt: string} | {lte: string} | {gt: string} | {gte: string}; export type EqFilter = {eq: string}; export type SortAscDesc = 'asc' | 'desc'; export type SortAscDescDefaultDesc = 'asc' | 'desc'; export type GetApiChargingEntriesArgs = {start_cursor?: string | undefined, per_page?: number | undefined, filter?: ({created_at?: LtLteGtGteFilter | undefined, ended_at?: LtLteGtGteFilter | undefined, started_at?: LtLteGtGteFilter | undefined, vehicle_id?: EqFilter | undefined, vendor_id?: EqFilter | undefined, updated_at?: LtLteGtGteFilter | undefined}) | undefined, sort?: ({created_at?: SortAscDesc | undefined, ended_at?: SortAscDesc | undefined, started_at?: SortAscDesc | undefined, updated_at?: SortAscDesc | undefined, id?: SortAscDescDefaultDesc | undefined}) | undefined}; export type GetApiChargingEntriesOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, accountToken?: string | undefined, fetch?: typeof fetch | undefined}; 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 includeEqFilter = z.union([z.object({include: z.string()}), z.object({eq: z.string()})]); export const sortAscDesc = z.enum(["asc", "desc"]); export const geolocation = z.object({gps_device: z.string().nullable().optional(), original_vendor: z.string().nullable().optional(), exception_distance_in_mi: z.number().nullable().optional(), exception_distance_in_km: z.number().nullable().optional()}).nullable(); export const chargingEntrySummary = z.object({additional_fees_cents: z.number().int().nullable(), approved_at: z.string().nullable(), approved_by_id: z.number().int().nullable(), cost_per_hr: z.string().nullable(), cost_per_km: z.string().nullable(), cost_per_mi: z.string().nullable(), discount_cents: z.number().int().nullable(), duration_seconds: z.number().int().gte(0), ended_at: z.string().nullable(), geolocation: geolocation, km_per_kwh: z.string(), mi_per_kwh: z.string(), personal: z.boolean(), price_per_kwh_cents: z.string().nullable(), reference: z.string().nullable(), started_at: z.string(), status: z.enum(["in_progress", "target_reached", "ready_for_review", "manually_completed", "approved", "auto_approved", "unknown"]), total_amount_cents: z.number().int().nullable(), total_kwh: z.string(), usage_in_hr: z.string().nullable(), usage_in_km: z.string().nullable(), usage_in_mi: z.string().nullable(), vehicle_id: z.number().int().gte(1), vendor_id: z.number().int().gte(1).nullable(), comments_count: z.number().int(), documents_count: z.number().int(), images_count: z.number().int()}); export const getApiChargingEntriesResponse = 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({created_at: ltLteGtGteFilter.optional()}), z.object({ended_at: ltLteGtGteFilter.optional()}), z.object({started_at: ltLteGtGteFilter.optional()}), z.object({updated_at: ltLteGtGteFilter.optional()}), z.object({vehicle_id: includeEqFilter.optional()}), z.object({vendor_id: includeEqFilter.optional()})])).optional(), sorted_by: z.array(z.union([z.object({created_at: sortAscDesc.optional()}), z.object({ended_at: sortAscDesc.optional()}), z.object({id: sortAscDesc.optional()}), z.object({started_at: sortAscDesc.optional()}), z.object({updated_at: sortAscDesc.optional()})])).optional(), records: z.array(chargingEntrySummary).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 Charging Entries * * GET /charging_entries */ export const getApiChargingEntries = async (args: GetApiChargingEntriesArgs, options?: GetApiChargingEntriesOptions) => { 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(/\/+$/, '')}/charging_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(getApiChargingEntriesResponse, await res.json()) };