import {z} from 'zod' export type CreateApiV2TimeOffArgs = {body: {user_id: number, company_id: number, from_date: string, to_date: string, partial: boolean, partial_from?: (string | null) | undefined, partial_to?: (string | null) | undefined, comments?: string | undefined, status: number, category: string, hours?: Array<{date: string, num_hours: number}> | undefined, status_action_user_id?: (number | null) | undefined, status_action_message?: string | undefined}}; export type CreateApiV2TimeOffOptions = {baseUrl?: string | undefined, OAuth2?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiV2TimeOffResponse = z.object({id: z.number().int(), user_id: z.number().int(), company_id: z.number().int(), from_date: z.string(), to_date: z.string(), partial: z.boolean(), partial_from: z.string().nullable(), partial_to: z.string().nullable(), comments: z.string(), status: z.number().int(), status_action_user_id: z.number().int().nullable(), status_action_message: z.string(), category: z.string(), created: z.string(), amount_of_hours: z.number(), hours: z.array(z.object({date: z.string(), hours: z.number()}))}); 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 Time Off * * POST /v2/time_off * * Also accepts auth: cookieAuth */ export const createApiV2TimeOff = async (args: CreateApiV2TimeOffArgs, options?: CreateApiV2TimeOffOptions) => { const {baseUrl = "https://api.7shifts.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(/\/+$/, '')}/v2/time_off${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(createApiV2TimeOffResponse, await res.json()) };