import {z} from 'zod' export type GetApiPlansPlanIdMonthsMonthMoneyMovementsArgs = {plan_id: string, month: string}; export type GetApiPlansPlanIdMonthsMonthMoneyMovementsOptions = {baseUrl?: string | undefined, bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const moneyMovement = z.object({id: z.string(), month: z.string().nullable().optional(), moved_at: z.string().nullable().optional(), note: z.string().nullable().optional(), money_movement_group_id: z.string().nullable().optional(), performed_by_user_id: z.string().nullable().optional(), from_category_id: z.string().nullable().optional(), to_category_id: z.string().nullable().optional(), amount: z.number().int(), amount_formatted: z.string().optional(), amount_currency: z.number().optional()}); export const moneyMovementsResponse = z.object({data: z.object({money_movements: z.array(moneyMovement), server_knowledge: z.number().int()})}); 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 }; /** * Get money movements for a plan month * * GET /plans/{plan_id}/months/{month}/money_movements */ export const getApiPlansPlanIdMonthsMonthMoneyMovements = async (args: GetApiPlansPlanIdMonthsMonthMoneyMovementsArgs, options?: GetApiPlansPlanIdMonthsMonthMoneyMovementsOptions) => { const {baseUrl = "https://api.ynab.com/v1", fetch: fetchFn = fetch, bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (bearer !== undefined) headers.set('authorization', `Bearer ${bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/plans/${encodeURIComponent(String(args.plan_id))}/months/${encodeURIComponent(String(args.month))}/money_movements${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(moneyMovementsResponse, await res.json()) };