import {z} from 'zod' export type GetApiV1InsightIncomeRevenueArgs = {'X-Trace-Id'?: string | undefined, start: string, end: string, 'accounts[]'?: Array | undefined}; export type GetApiV1InsightIncomeRevenueOptions = {baseUrl?: string | undefined, fireflyIiiAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const insightGroupEntry = z.object({id: z.string().optional(), name: z.string().optional(), difference: z.string().optional(), difference_float: z.number().optional(), currency_id: z.string().optional(), currency_code: z.string().optional()}); export const insightGroup = z.array(insightGroupEntry); 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 }; /** * Insight into income, grouped by revenue account. * * GET /v1/insight/income/revenue * * Also accepts auth: local_bearer_auth */ export const getApiV1InsightIncomeRevenue = async (args: GetApiV1InsightIncomeRevenueArgs, options?: GetApiV1InsightIncomeRevenueOptions) => { const {baseUrl = "https://demo.firefly-iii.org/api", fetch: fetchFn = fetch, fireflyIiiAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args['X-Trace-Id'] != null) headers.set("X-Trace-Id", String(args['X-Trace-Id'])) if (args.start != null) query.append("start", String(args.start)) if (args.end != null) query.append("end", String(args.end)) for (const item of args['accounts[]'] ?? []) query.append("accounts[]", String(item)) if (fireflyIiiAuth !== undefined) headers.set('authorization', `Bearer ${fireflyIiiAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/insight/income/revenue${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(insightGroup, await res.json()) };