import {z} from 'zod' export type Currency = string; export type Money = {amount?: number | undefined, currency?: Currency | undefined}; export type CountryCode = unknown; export type CardholderVerificationType = 'WALLET' | 'PIN' | 'BIO' | 'THREE_DS'; export type CardEntryMode = 'MANUAL_ENTRY' | 'MAGNETIC_STRIPE_READ' | 'CHIP_READ' | 'CONTACTLESS' | 'ELECTRONIC_COMMERCE'; export type TransactionType = 'RETAIL' | 'CASH' | 'ATM' | 'CREDIT' | 'UNIQUE' | 'P2P_CREDIT' | 'P2P_DEBIT' | 'BALANCE_INQUIRY' | 'CASH_DISBURSEMENT'; export type CardScheme = 'VISA' | 'MC'; export type MessageCategory = 'REQUEST' | 'ADJUSTMENT' | 'SCHEME_ADVICE' | 'REVERSAL_ADVICE'; export type TestEvaluationV1Request = {cardId: unknown, merchantCategoryCode: string, settlementAmount: Money, merchantCountryCode?: CountryCode | undefined, merchantId?: string | undefined, acquirerId?: string | undefined, subMerchantId?: string | undefined, cardholderVerifications?: Array | undefined, cardEntryMode?: CardEntryMode | undefined, cardholderPresent?: boolean | undefined, transactionType: TransactionType, cardScheme?: CardScheme | undefined, messageCategory?: MessageCategory | undefined, transactionTimestamp?: string | undefined, transactionId?: unknown | undefined, terminalCategoryCode?: string | undefined}; export type CreateApiV1EvaluateTestArgs = {auditUser: string, body: TestEvaluationV1Request}; export type CreateApiV1EvaluateTestOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const spendControlDecision = z.enum(["DECLINE", "APPROVE_PARTIAL", "APPROVE"]); export const currency = z.string(); export const money = z.object({amount: z.number().optional(), currency: currency.optional()}); export const id = z.string(); export const ruleSetOperatorType = z.enum(["ANY", "ALL"]); export const entityType = z.enum(["CARD", "CARD_HIERARCHY_GROUP"]); export const externalEntityReference = z.object({id: z.string(), type: entityType}); export const ruleType = z.enum(["DECLINE", "ALLOWED_MCC", "BLOCKED_MCC", "ALLOWED_MERCHANT_ID", "BLOCKED_MERCHANT_ID", "AMOUNT", "ALLOWED_MERCHANT_COUNTRY", "BLOCKED_MERCHANT_COUNTRY", "ALLOWED_CARD_ENTRY_MODES", "BLOCKED_CARD_ENTRY_MODES", "ALLOWED_CVM", "BLOCKED_CVM", "CARDHOLDER_PRESENT", "EXTERNAL_BALANCE_CHECK", "CUMULATIVE_AMOUNT_INDIVIDUAL_LIMITS", "CUMULATIVE_COUNT_INDIVIDUAL_LIMITS", "ENFUCE_INTERNAL_PSD2_PIN_COUNT_RULE", "ENFUCE_INTERNAL_PSD2_PIN_AMOUNT_RULE"]); export const filterOperatorType = z.enum(["ANY", "ALL"]); export const filterType = z.enum(["MCC", "AMOUNT", "MERCHANT_COUNTRY", "CARDHOLDER_VERIFICATION", "CARD_ENTRY_MODE", "CARDHOLDER_PRESENT", "ACQUIRER_ID", "TRANSACTION_TYPE"]); export const filterResponseBody = z.object({id: id.optional(), type: filterType.optional(), reversed: z.boolean().optional()}); export const ruleResponseBody = z.object({id: id.optional(), ruleType: ruleType.optional(), name: z.string(), filterOperatorType: filterOperatorType, filters: z.array(filterResponseBody).optional()}); export const spendControlRuleEvaluation = z.object({ruleId: id.optional(), decision: spendControlDecision.optional(), partialApprovalAmount: money.optional(), settings: ruleResponseBody.optional()}); export const spendControlRuleSetEvaluationDetails = z.object({ruleSetId: id.optional(), operator: ruleSetOperatorType.optional(), decision: spendControlDecision.optional(), entityReferences: z.array(externalEntityReference).optional(), partialApprovalAmount: money.optional(), ruleEvaluations: z.array(spendControlRuleEvaluation).optional()}); export const testEvaluationV1Response = z.object({decision: spendControlDecision.optional(), partialApprovalAmount: money.optional(), responseCode: z.string().optional(), details: z.array(spendControlRuleSetEvaluationDetails).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 }; /** * Test Spend Control Rules Evaluation * * POST /v1/evaluate/test */ export const createApiV1EvaluateTest = async (args: CreateApiV1EvaluateTestArgs, options: CreateApiV1EvaluateTestOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.auditUser != null) query.append("auditUser", String(args.auditUser)) const url = `${baseUrl.replace(/\/+$/, '')}/v1/evaluate/test${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(testEvaluationV1Response, await res.json()) };