import {z} from 'zod' export type CreateApiOpportunitiesArgs = {body: {owner?: number | undefined, account: number, stage?: number | undefined, lost_reason?: number | undefined, files?: Array> | undefined, lead_source?: number | undefined, start_date?: string | undefined, probability?: number | undefined, assignee?: number | undefined, creator?: number | undefined, status?: string | undefined, name?: string | undefined, value?: number | undefined, currency?: number | undefined, status_date?: string | undefined, close_date?: string | undefined, closed?: boolean | undefined, tags?: Array | undefined, recurring_price_per_unit?: number | undefined, frequency?: ('annually' | 'weekly' | 'monthly' | 'daily') | undefined, units?: number | undefined, contract_start_date?: string | undefined, contract_end_date?: string | undefined, main_contact?: number | undefined, custom?: Record | undefined}}; export type CreateApiOpportunitiesOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiOpportunitiesResponse = z.object({id: z.number().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 an opportunity * * POST /opportunities */ export const createApiOpportunities = async (args: CreateApiOpportunitiesArgs, options?: CreateApiOpportunitiesOptions) => { const {baseUrl = "https://api.salesflare.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/opportunities${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(createApiOpportunitiesResponse, await res.json()) };