import {z} from 'zod' export type GetApiCustomersExternalCustomerIdPastUsageArgs = {external_customer_id: string, page?: number | undefined, per_page?: number | undefined, subscription_id: string}; export type GetApiCustomersExternalCustomerIdPastUsageOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const date = z.string(); export const currency = z.string().min(3).max(3); export const amount = z.object({value: z.number().gte(0), currency_code: currency}); export const chargeModel = z.enum(["STANDARD", "GRADUATED", "PACKAGE", "PERCENTAGE", "VOLUME"]); export const taxCode = z.string(); export const taxResponse = z.object({name: z.string(), rate: z.string().optional(), description: z.string().optional(), code: taxCode.optional(), id: z.string().optional(), created_at: z.string().optional()}); export const usageBasedCharge = z.object({id: z.string(), metric_id: z.string(), charge_model: chargeModel.optional(), properties: z.object({}).optional(), taxes: z.array(taxResponse).optional(), min_amount: amount.optional()}); export const metricAggregationType = z.enum(["COUNT", "SUM", "MAX", "COUNT_DISTINCT", "LATEST"]).nullable(); export const customerUsageMetric = z.object({name: z.string(), code: z.string(), aggregation_type: metricAggregationType}); export const customerChargeUsage = z.object({units: z.string(), events_count: z.number().int(), amount: amount, charge: usageBasedCharge, metric: customerUsageMetric}); export const customerUsage = z.object({from_datetime: z.string(), to_datetime: z.string(), issuing_date: date, invoice_id: z.string().optional(), total_amount: amount, taxes_amount: amount, charges_usage: z.array(customerChargeUsage)}); export const paginationMetadata = z.object({total_count: z.number().int().optional(), total_pages: z.number().int().optional(), current_page: z.number().int().optional()}); export const customerPastUsage = z.object({usage_periods: z.array(customerUsage), meta: paginationMetadata}); 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 past usage for a customer * * GET /customers/{external_customer_id}/past_usage */ export const getApiCustomersExternalCustomerIdPastUsage = async (args: GetApiCustomersExternalCustomerIdPastUsageArgs, options?: GetApiCustomersExternalCustomerIdPastUsageOptions) => { const {baseUrl = "https://api-m.sandbox.paypal.com", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.page != null) query.append("page", String(args.page)) if (args.per_page != null) query.append("per_page", String(args.per_page)) if (args.subscription_id != null) query.append("subscription_id", String(args.subscription_id)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/customers/${encodeURIComponent(String(args.external_customer_id))}/past_usage${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(customerPastUsage, await res.json()) };