import {z} from 'zod' export type CreateEstimateV2Dto = {clientId: string, jobId?: string | undefined, name?: string | undefined, description?: string | undefined, createdDate?: string | undefined}; export type CreateApiV2EstimatesArgs = {Authorization: string, body: CreateEstimateV2Dto}; export type CreateApiV2EstimatesOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const responseEstimateLineItemV2Dto = z.object({id: z.string().optional(), productId: z.number().optional(), name: z.string().optional(), description: z.string().optional(), price: z.number().optional(), quantity: z.number().optional(), total: z.number().optional(), cost: z.number().optional(), taxable: z.boolean().optional(), discountable: z.boolean().optional(), inventoryManaged: z.boolean().optional(), inventorySync: z.boolean().optional(), optionalConverted: z.boolean().optional()}); export const responsePaymentV2Dto = z.object({id: z.string().optional(), date: z.string().optional(), amount: z.number().optional(), tipAmount: z.number().optional(), type: z.enum(["charge", "cash", "credit", "check", "refund", "refund_offline", "bank_transfer", "bank_transfer_offline", "cash_app", "consumer_financing", "venmo", "zelle", "debit_offline", "installments", "interac", "check_deposit"]).optional(), status: z.enum(["pending", "failed", "succeeded"]).optional(), estimateId: z.string().nullable().optional(), confirmationCode: z.string().optional(), collectedById: z.string().nullable().optional()}); export const responseGenericAttachmentV2Dto = z.object({id: z.string().optional(), name: z.string().optional(), fileUrl: z.string().optional()}); export const responseGenericSignatureV2Dto = z.object({id: z.string().optional(), signedByName: z.string().optional(), imageUrl: z.string().optional()}); export const responseOneEstimateV2Dto = z.object({id: z.string().optional(), status: z.string().optional(), serialId: z.string().optional(), name: z.string().optional(), description: z.string().optional(), notes: z.string().optional(), imageUrl: z.string().optional(), clientId: z.string().optional(), jobId: z.string().optional(), discountAmount: z.number().optional(), taxPercent: z.number().optional(), taxableAmount: z.number().optional(), taxAmount: z.number().optional(), isDepositPercentage: z.boolean().optional(), deposit: z.number().optional(), subTotal: z.number().optional(), total: z.number().optional(), declineReason: z.string().optional(), lineItems: z.array(responseEstimateLineItemV2Dto).optional(), payments: z.array(responsePaymentV2Dto).optional(), attachments: z.array(responseGenericAttachmentV2Dto).optional(), signatureImage: responseGenericSignatureV2Dto.optional(), sentDate: z.string().optional(), estimateDate: z.string().optional(), lastViewedDate: z.string().optional(), statusUpdatedAt: z.string().optional(), updated: z.string().optional(), created: z.string().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 }; /** * Create a new Estimate * * POST /v2/estimates */ export const createApiV2Estimates = async (args: CreateApiV2EstimatesArgs, options?: CreateApiV2EstimatesOptions) => { const {baseUrl = "https://api.workiz.com/crm/api", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.Authorization != null) headers.set("Authorization", String(args.Authorization)) const url = `${baseUrl.replace(/\/+$/, '')}/v2/estimates${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(responseOneEstimateV2Dto, await res.json()) };