import {z} from 'zod' export type CreditNoteReason = 'DUPLICATED_CHARGE' | 'PRODUCT_UNSATISFACTORY' | 'ORDER_CHANGE' | 'ORDER_CANCELLATION' | 'FRAUDULENT_CHARGE' | 'OTHER'; export type AmountNoCurrency = {value: number}; export type CreditNoteCreateRequest = {invoice_id: string, reason?: CreditNoteReason | undefined, description?: string | undefined, credit_amount?: (AmountNoCurrency | null) | undefined, refund_amount?: (AmountNoCurrency | null) | undefined, items: Array<{fee_id: string, amount: AmountNoCurrency}>}; export type CreateApiCreditNotesArgs = {body: CreditNoteCreateRequest}; export type CreateApiCreditNotesOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const billingEntityCode = z.string(); export const date = z.string(); export const creditNoteStatus = z.enum(["AVAILABLE", "CONSUMED", "VOIDED"]); export const refundStatus = z.enum(["PENDING", "SUCCEEDED", "FAILED"]); export const creditNoteReason = z.enum(["DUPLICATED_CHARGE", "PRODUCT_UNSATISFACTORY", "ORDER_CHANGE", "ORDER_CANCELLATION", "FRAUDULENT_CHARGE", "OTHER"]); export const currency = z.string().min(3).max(3); export const amount = z.object({value: z.number().gte(0), currency_code: currency}); export const dateTimeWithZone = z.string(); export const feeObject = z.object({id: z.string().nullable().optional(), total_amount: amount.optional(), name: z.string().nullable().optional()}); export const creditNoteItemObject = z.object({id: z.string(), amount: amount, fee: feeObject}); export const creditNoteAppliedTaxObject = z.object({id: z.string().optional(), tax_id: z.string().optional(), tax_name: z.string().optional(), tax_code: z.string().optional(), tax_rate: z.number().optional(), tax_description: z.string().optional(), amount: amount.optional(), created_at: dateTimeWithZone.optional()}); export const creditNoteWithId = z.object({billing_entity_code: billingEntityCode, sequential_id: z.number().int(), number: z.string(), invoice_id: z.string(), invoice_number: z.string(), issuing_date: date, credit_status: creditNoteStatus.optional(), refund_status: refundStatus.optional(), reason: creditNoteReason, description: z.string().nullable().optional(), total_amount: amount, taxes_amount: amount, taxes_rate: z.number(), sub_total_excluding_taxes_amount: amount, balance_amount: amount, credit_amount: amount, refund_amount: amount, created_at: dateTimeWithZone, updated_at: dateTimeWithZone, items: z.array(creditNoteItemObject).optional(), applied_taxes: z.array(creditNoteAppliedTaxObject).optional(), id: z.string().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 a new credit note * * POST /credit-notes */ export const createApiCreditNotes = async (args: CreateApiCreditNotesArgs, options?: CreateApiCreditNotesOptions) => { const {baseUrl = "https://api-m.sandbox.paypal.com", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/credit-notes${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(creditNoteWithId, await res.json()) };