import {z} from 'zod' export type ChargeKey = string; export type ComponentsSchemasOffsetToken = string; export type GetApiChargesChargeKeyActionsArgs = {chargeKey: ChargeKey, offsetToken?: ComponentsSchemasOffsetToken | undefined, limit?: number | undefined}; export type GetApiChargesChargeKeyActionsOptions = {baseUrl?: string | undefined, ApiKey?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const componentsSchemasOffsetToken = z.string().min(1).max(2048); export const actionKey = z.string().min(5).max(120); export const chargeKey = z.string().min(5).max(120); export const actionReference = z.string().min(1).max(120); export const componentsSchemasAmountValue = z.number().int().gte(0).lte(999999999999); export const commonCurrencyCode = z.enum(["AED", "AFN", "ALL", "AMD", "AOA", "ARS", "AUD", "AWG", "AZN", "BAM", "BBD", "BDT", "BHD", "BIF", "BMD", "BND", "BOB", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD", "CAD", "CDF", "CHF", "CLP", "CNY", "COP", "CRC", "CUC", "CUP", "CVE", "CZK", "DJF", "DKK", "DOP", "DZD", "EGP", "ERN", "ETB", "EUR", "FJD", "FKP", "GBP", "GEL", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", "HKD", "HNL", "HTG", "HUF", "IDR", "ILS", "INR", "IQD", "IRR", "ISK", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LYD", "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRU", "MUR", "MVR", "MWK", "MXN", "MYR", "MZN", "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", "OMR", "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", "QAR", "RON", "RSD", "RUB", "RWF", "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SOS", "SRD", "SSP", "STN", "SYP", "SZL", "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS", "UAH", "UGX", "USD", "UYU", "UZS", "VES", "VND", "VUV", "WST", "XAF", "XCD", "XCG", "XOF", "XPF", "YER", "ZAR", "ZMW", "ZWL"]); export const isoFieldResponseCode = z.string(); export const isoFieldResponseCodeDescription = z.string(); export const authorizationResponseForAuthorizationAndRefundActions = z.discriminatedUnion("network", [z.object({network: z.literal("american-express"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription, acquirerReferenceData: z.string()}), z.object({network: z.literal("bancontact"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription}), z.object({network: z.literal("diners"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription, networkReferenceId: z.string()}), z.object({network: z.literal("discover"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription, networkReferenceId: z.string()}), z.object({network: z.literal("mastercard"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription, traceId: z.string()}), z.object({network: z.literal("unionpay"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription}), z.object({network: z.literal("visa"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription, transactionIdentifier: z.string()}), z.object({network: z.literal("unknown"), responseCode: z.literal("unknown"), responseCodeDescription: z.literal("unknown")})]); export const schemasCountryCodeAlpha3 = z.string().min(3).max(3); export const schemasCountryCodeAlpha2 = z.string().min(2).max(2); export const schemasCountryCodeNumeric = z.string().min(3).max(3); export const enhancedDataDestinationAddress = z.object({countryCode: z.object({alpha3: schemasCountryCodeAlpha3, alpha2: schemasCountryCodeAlpha2, numeric: schemasCountryCodeNumeric}).optional(), postalCode: z.string().min(1).max(10).optional()}); export const enhancedDataShippingAddress = z.object({postalCode: z.string().min(1).max(10).optional()}); export const enhancedDataLineItem = z.object({commodityCode: z.string().min(1).max(12), description: z.string().min(2).max(26), discountAmount: z.number().int().gte(0).lte(999999999999), productCode: z.string().min(1).max(12), quantity: z.number().int().gte(0).lte(999999999999), unitOfMeasure: z.string().min(1).max(12), unitPrice: z.number().int().gte(0).lte(999999999999), taxAmount: z.number().int().gte(0).lte(999999999999), taxRate: z.number().int().gte(0).lte(10000), totalAmount: z.number().int().gte(0).lte(999999999999)}); export const enhancedData = z.object({taxAmount: z.number().int().gte(0).lte(999999999999), customerCode: z.string().min(1).max(25).optional(), customerTaxId: z.string().min(1).max(13).optional(), destinationAddress: enhancedDataDestinationAddress.optional(), discountAmount: z.number().int().gte(0).lte(999999999999).optional(), invoiceNumber: z.string().min(1).max(25).optional(), orderDate: z.string().optional(), purchaseOrderNumber: z.string().min(1).max(13).optional(), shippingAddress: enhancedDataShippingAddress.optional(), timeOfPurchase: z.string().min(4).max(4).optional(), lineItems: z.array(enhancedDataLineItem).optional()}); export const openapiComponentsSchemasCreated = z.string(); export const componentsSchemasLastModified = z.string(); export const schemasVersion = z.number().int(); export const commonAmount = z.object({value: componentsSchemasAmountValue, currency: commonCurrencyCode}); export const authorizationResponseForReversalAction = z.discriminatedUnion("network", [z.object({network: z.literal("american-express"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription}), z.object({network: z.literal("bancontact"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription}), z.object({network: z.literal("diners"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription}), z.object({network: z.literal("discover"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription}), z.object({network: z.literal("mastercard"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription}), z.object({network: z.literal("unionpay"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription}), z.object({network: z.literal("visa"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription}), z.object({network: z.literal("unknown"), responseCode: z.literal("unknown"), responseCodeDescription: z.literal("unknown")})]); export const refundChargeKey = z.string().min(5).max(120); export const clearAfter = z.string(); export const offlineRefundInitialTransactionReferences = z.object({initialTraceId: z.string().min(1).max(15)}); export const authorizationResponseForIncrementAction = z.discriminatedUnion("network", [z.object({network: z.literal("bancontact"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription}), z.object({network: z.literal("diners"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription}), z.object({network: z.literal("discover"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription}), z.object({network: z.literal("mastercard"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription}), z.object({network: z.literal("unionpay"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription}), z.object({network: z.literal("visa"), responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription}), z.object({network: z.literal("unknown"), responseCode: z.literal("unknown"), responseCodeDescription: z.literal("unknown")})]); export const action = z.discriminatedUnion("type", [z.object({type: z.literal("authorization"), key: actionKey, chargeKey: chargeKey, reference: actionReference.optional(), amount: z.object({value: componentsSchemasAmountValue, currency: commonCurrencyCode}), status: z.object({authorization: z.enum(["approved", "approved-partial", "approved-purchase-amount-only", "declined"])}), authorizationResponse: authorizationResponseForAuthorizationAndRefundActions, enhancedData: enhancedData.optional(), created: openapiComponentsSchemasCreated, lastModified: componentsSchemasLastModified.optional(), version: schemasVersion}), z.object({type: z.literal("reversal"), key: actionKey, chargeKey: chargeKey, reference: actionReference.optional(), replacementAmount: commonAmount, status: z.object({authorization: z.enum(["approved", "declined"])}), authorizationResponse: authorizationResponseForReversalAction, created: openapiComponentsSchemasCreated, lastModified: componentsSchemasLastModified.optional(), version: schemasVersion}), z.object({type: z.literal("refund"), key: actionKey, chargeKey: chargeKey, refundChargeKey: refundChargeKey.optional(), reference: z.string().min(1).max(120).optional(), amount: commonAmount, status: z.object({authorization: z.enum(["approved", "declined"])}), clearAfter: clearAfter.optional(), authorizationResponse: authorizationResponseForAuthorizationAndRefundActions, created: openapiComponentsSchemasCreated, lastModified: componentsSchemasLastModified.optional(), version: schemasVersion}), z.object({type: z.literal("offline-refund"), key: actionKey, chargeKey: chargeKey, reference: actionReference.optional(), amount: z.object({value: componentsSchemasAmountValue, currency: commonCurrencyCode}), clearAfter: clearAfter.optional(), initialRefundReferences: offlineRefundInitialTransactionReferences.optional(), created: openapiComponentsSchemasCreated, lastModified: componentsSchemasLastModified.optional(), version: schemasVersion}), z.object({type: z.literal("clearing"), key: actionKey, chargeKey: chargeKey, reference: actionReference.optional(), amount: z.object({value: componentsSchemasAmountValue, currency: commonCurrencyCode}), enhancedData: enhancedData.optional(), created: openapiComponentsSchemasCreated, lastModified: componentsSchemasLastModified.optional(), version: schemasVersion}), z.object({type: z.literal("increment"), key: actionKey, chargeKey: chargeKey, reference: actionReference.optional(), replacementAmount: commonAmount, status: z.object({authorization: z.enum(["approved", "declined"])}), authorizationResponse: authorizationResponseForIncrementAction, created: openapiComponentsSchemasCreated, lastModified: componentsSchemasLastModified.optional(), version: schemasVersion})]); export const actionsPage = z.object({moreItems: z.boolean().optional(), offsetToken: componentsSchemasOffsetToken.optional(), actions: z.array(action)}); 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 }; /** * List Charge Actions * * GET /charges/{chargeKey}/actions * * Also accepts auth: BearerToken */ export const getApiChargesChargeKeyActions = async (args: GetApiChargesChargeKeyActionsArgs, options?: GetApiChargesChargeKeyActionsOptions) => { const {baseUrl = "https://eu-west-1.api.silverflow.com/v1", fetch: fetchFn = fetch, ApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.offsetToken != null) query.append("offsetToken", String(args.offsetToken)) if (args.limit != null) query.append("limit", String(args.limit)) if (ApiKey !== undefined) headers.set('authorization', `Basic ${btoa(`${ApiKey.username}:${ApiKey.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/charges/${encodeURIComponent(String(args.chargeKey))}/actions${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(actionsPage, await res.json()) };