import {z} from 'zod' export type GetApiJobsArgs = {pageSize?: number | undefined, sortOrder?: ('asc' | 'desc') | undefined, pageCursor?: string | undefined, filterJobNo?: string | undefined, filterJobStatus?: ('Active' | 'Completed' | 'Estimate Rejected' | 'Estimate Sent' | 'Inactive' | 'Quote Sent' | 'Quote Rejected' | 'To Price') | undefined, filterJobType?: ('Quote' | 'Estimate' | 'Charge Up') | undefined, filterCustomerId?: number | undefined, filterSiteId?: number | undefined, sortField?: ('jobNo' | 'createdAt' | 'lastModified') | undefined, filterShowOnHold?: boolean | undefined, filterShowArchived?: boolean | undefined, filterSearchText?: string | undefined}; export type GetApiJobsOptions = {baseUrl?: string | undefined, oauth2?: string | undefined, fetch?: typeof fetch | undefined}; export const jobCustomer = z.object({id: z.number(), customerFullName: z.string().nullable()}); export const jobSiteAddress = z.object({id: z.number(), name: z.string().nullable(), firstName: z.string().nullable(), lastName: z.string().nullable(), address1: z.string().nullable(), address2: z.string().nullable(), addressSuburb: z.string().nullable(), addressCity: z.string().nullable(), addressRegion: z.string().nullable(), addressCountry: z.string().nullable(), addressPostcode: z.string().nullable()}); export const contactItem = z.object({id: z.number(), contactType: z.enum(["email", "phone", "mobile", "other", "fax", "website"]), contactValue: z.string()}); export const links = z.object({href: z.string(), rel: z.string(), type: z.enum(["GET", "POST", "PUT", "PATCH"])}); export const job = z.object({id: z.number(), jobNo: z.string().nullable(), jobNumber: z.string().nullable(), description: z.string().nullable(), longDescription: z.string().nullable(), createdAt: z.string(), lastModified: z.string().nullable(), jobType: z.string(), status: z.string(), assignedGroups: z.array(z.string()), customer: jobCustomer.nullable(), siteAddress: jobSiteAddress.nullable(), mainContact: z.object({id: z.number(), firstName: z.string().nullable(), lastName: z.string().nullable(), contactItems: z.array(contactItem).nullable()}).nullable(), activeQuote: z.object({id: z.number(), versionNumber: z.number(), guid: z.string().nullable(), title: z.string().nullable(), description: z.string().nullable(), quoteDate: z.string().nullable(), isSent: z.boolean(), isAccepted: z.boolean(), isSuperseded: z.boolean(), isLocked: z.boolean(), voidedAt: z.string().nullable(), declinedAt: z.string().nullable(), createdAt: z.string(), lastModified: z.string(), publishedAt: z.string().nullable(), dueDate: z.string().nullable(), dueDays: z.string().nullable(), isDraft: z.boolean(), total: z.number().nullable().optional()}).nullable(), onHold: z.boolean(), archived: z.boolean(), customerReference: z.string().nullable(), parentJobId: z.number().nullable(), jobVariants: z.array(z.number()).nullable(), links: z.array(links)}); export const pagination = z.object({perPage: z.number(), pageCount: z.number(), links: z.object({self: z.string(), previous: z.string().nullable(), next: z.string().nullable()})}); export const jobsResponse = z.object({result: z.string(), data: z.array(job), paging: pagination.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 }; /** * Returns a list of jobs. The list can be filtered by job type. * * GET /jobs * * Also accepts auth: PersonalAccessToken */ export const getApiJobs = async (args: GetApiJobsArgs, options?: GetApiJobsOptions) => { const {baseUrl = "https://api.fergus.com", fetch: fetchFn = fetch, oauth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.pageSize != null) query.append("pageSize", String(args.pageSize)) if (args.sortOrder != null) query.append("sortOrder", String(args.sortOrder)) if (args.pageCursor != null) query.append("pageCursor", String(args.pageCursor)) if (args.filterJobNo != null) query.append("filterJobNo", String(args.filterJobNo)) if (args.filterJobStatus != null) query.append("filterJobStatus", String(args.filterJobStatus)) if (args.filterJobType != null) query.append("filterJobType", String(args.filterJobType)) if (args.filterCustomerId != null) query.append("filterCustomerId", String(args.filterCustomerId)) if (args.filterSiteId != null) query.append("filterSiteId", String(args.filterSiteId)) if (args.sortField != null) query.append("sortField", String(args.sortField)) if (args.filterShowOnHold != null) query.append("filterShowOnHold", String(args.filterShowOnHold)) if (args.filterShowArchived != null) query.append("filterShowArchived", String(args.filterShowArchived)) if (args.filterSearchText != null) query.append("filterSearchText", String(args.filterSearchText)) if (oauth2 !== undefined) headers.set('authorization', `Bearer ${oauth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/jobs${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(jobsResponse, await res.json()) };