import {z} from 'zod' export type CreateApiJobsArgs = {body: {isDraft?: boolean | undefined, jobType: 'Quote' | 'Estimate' | 'Charge Up', title?: string | undefined, description?: string | undefined, customerId?: number | undefined, customerReference?: string | undefined, siteId?: number | undefined, parentJobId?: number | undefined}}; export type CreateApiJobsOptions = {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 jobResponse = z.object({result: z.string(), data: job}); 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 }; /** * Creates a new job. Supports two modes depending on whether `isDraft` is set: * * POST /jobs * * Also accepts auth: PersonalAccessToken */ export const createApiJobs = async (args: CreateApiJobsArgs, options?: CreateApiJobsOptions) => { const {baseUrl = "https://api.fergus.com", fetch: fetchFn = fetch, oauth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (oauth2 !== undefined) headers.set('authorization', `Bearer ${oauth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/jobs${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(jobResponse, await res.json()) };