@open-mercato/gateway-autopay 0.10.1-develop.8287.1.7313a0fe67 → 0.10.1-develop.8291.1.6ec3aee41c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
1
  import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
2
+ import { padDecimalPlaces, resolveExactDecimal, roundDecimal } from "@open-mercato/shared/lib/decimal";
2
3
  import { buildLaunchPath, createLaunchGrant, readHttpUrl, resolveLaunchUrl } from "../launch.js";
3
4
  import {
4
5
  buildSessionRequest,
@@ -58,6 +59,11 @@ async function resolveRefundRemoteId(credentials, input) {
58
59
  return interpretation.matchedRemoteId;
59
60
  }
60
61
  const AUTOPAY_CURRENCY = "PLN";
62
+ const AUTOPAY_AMOUNT_DECIMAL_PLACES = 2;
63
+ function formatAutopayAmount(amount, amountExact) {
64
+ const exact = resolveExactDecimal(amountExact, amount) ?? "0";
65
+ return padDecimalPlaces(roundDecimal(exact, AUTOPAY_AMOUNT_DECIMAL_PLACES), AUTOPAY_AMOUNT_DECIMAL_PLACES);
66
+ }
61
67
  const autopayAdapterV1 = {
62
68
  providerKey: "autopay",
63
69
  async createSession(input) {
@@ -75,7 +81,7 @@ const autopayAdapterV1 = {
75
81
  const session = buildSessionRequest({
76
82
  credentials,
77
83
  orderId,
78
- amount: input.amount.toFixed(2),
84
+ amount: formatAutopayAmount(input.amount, input.amountExact),
79
85
  currencyCode: input.currencyCode,
80
86
  description: input.description,
81
87
  gatewayId,
@@ -108,7 +114,7 @@ const autopayAdapterV1 = {
108
114
  const remoteId = await resolveRefundRemoteId(credentials, input);
109
115
  const result = await refundTransaction(credentials, {
110
116
  remoteId,
111
- amount: input.amount !== void 0 ? input.amount.toFixed(2) : void 0,
117
+ amount: input.amount !== void 0 ? formatAutopayAmount(input.amount, input.amountExact) : void 0,
112
118
  currencyCode: AUTOPAY_CURRENCY,
113
119
  idempotencyKey: input.idempotencyKey
114
120
  });
@@ -175,7 +181,9 @@ const autopayAdapterV1 = {
175
181
  return {
176
182
  status: interpretation.status,
177
183
  amount: interpretation.amount,
184
+ amountExact: interpretation.amountExact,
178
185
  amountReceived: interpretation.amountReceived,
186
+ amountReceivedExact: interpretation.amountReceivedExact,
179
187
  currencyCode: interpretation.currencyCode || AUTOPAY_CURRENCY,
180
188
  providerData: {
181
189
  remoteId: interpretation.matchedRemoteId,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/gateway_autopay/lib/adapters/v1.ts"],
4
- "sourcesContent": ["import type {\n GatewayAdapter,\n CreateSessionInput,\n CreateSessionResult,\n CaptureInput,\n CaptureResult,\n RefundInput,\n RefundResult,\n CancelInput,\n CancelResult,\n GetStatusInput,\n GatewayPaymentStatus,\n VerifyWebhookInput,\n WebhookEvent,\n UnifiedPaymentStatus,\n} from '@open-mercato/shared/modules/payment_gateways/types'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { buildLaunchPath, createLaunchGrant, readHttpUrl, resolveLaunchUrl } from '../launch'\nimport {\n buildSessionRequest,\n cancelTransaction,\n queryTransactionStatus,\n refundTransaction,\n sanitizeOrderId,\n type AutopayCredentials,\n} from '../autopay-client'\nimport { mapAutopayStatus, interpretAutopayTransactionStatus, type AutopayStatusInterpretation } from '../status-map'\n\nfunction resolveCredentials(raw: Record<string, unknown>): AutopayCredentials {\n const serviceId = raw.serviceId\n const sharedKey = raw.sharedKey\n const gatewayUrl = raw.gatewayUrl\n if (typeof serviceId !== 'string' || !serviceId) {\n throw new Error('[internal] Autopay credentials are missing serviceId')\n }\n if (typeof sharedKey !== 'string' || !sharedKey) {\n throw new Error('[internal] Autopay credentials are missing sharedKey')\n }\n if (typeof gatewayUrl !== 'string' || !gatewayUrl) {\n throw new Error('[internal] Autopay credentials are missing gatewayUrl')\n }\n return {\n serviceId,\n sharedKey,\n gatewayUrl,\n hashAlgorithm: raw.hashAlgorithm === 'sha512' ? 'sha512' : 'sha256',\n }\n}\n\n/**\n * `CreateSessionInput` has no dedicated customer-email field, but Autopay's\n * documented parameter table marks CustomerEmail as required (position 7).\n * This adapter reads it from `input.metadata.customerEmail` \u2014 callers of\n * `createSession` for the `autopay` provider MUST populate that key, as the\n * stock checkout submit route does.\n */\nfunction readCustomerEmail(metadata: Record<string, unknown> | undefined): string {\n const value = metadata?.customerEmail\n if (typeof value !== 'string' || !value) {\n throw new Error('[internal] Autopay requires metadata.customerEmail to be set on every session (CustomerEmail is a required field per the Autopay Online v1.1 documentation)')\n }\n return value\n}\n\nfunction readGatewayId(metadata: Record<string, unknown> | undefined): string | undefined {\n const value = metadata?.gatewayId\n return typeof value === 'string' && value ? value : undefined\n}\n\nasync function resolveStatusInterpretation(\n credentials: AutopayCredentials,\n orderId: string,\n): Promise<AutopayStatusInterpretation> {\n const { transactions } = await queryTransactionStatus(credentials, { orderId })\n return interpretAutopayTransactionStatus(transactions)\n}\n\n/**\n * `transactionRefund` needs Autopay's own `remoteID`, not the merchant\n * `OrderID` (`sessionId`) the canonical `paymentGatewayService.refundPayment`\n * call actually supplies \u2014 it does not thread caller metadata through to the\n * adapter. Rather than require a metadata field no real caller populates,\n * this resolves the settled transaction's `remoteID` itself via\n * `transactionStatus`, the same lookup `getStatus()` already performs. An\n * explicit `metadata.remoteId` is still honored first, as a fast path for a\n * caller that already has it cached (e.g. from a prior `getStatus` result)\n * and wants to skip the extra round trip.\n */\nasync function resolveRefundRemoteId(\n credentials: AutopayCredentials,\n input: RefundInput,\n): Promise<string> {\n const provided = input.metadata?.remoteId\n if (typeof provided === 'string' && provided) return provided\n\n const interpretation = await resolveStatusInterpretation(credentials, input.sessionId)\n if (interpretation.status !== 'captured' || !interpretation.matchedRemoteId) {\n const { t } = await resolveTranslations()\n throw new Error(t(\n 'gateway_autopay.errors.refundNotSettled',\n 'Autopay cannot refund session {sessionId}: no captured transaction was found (current status: {status}).',\n { sessionId: input.sessionId, status: interpretation.status },\n ))\n }\n return interpretation.matchedRemoteId\n}\n\n/** This package only ever creates PLN sessions (enforced in `createSession`),\n * so refunds always sign and send `Currency=PLN` explicitly rather than\n * omitting it \u2014 an omitted Currency still produces a validly-signed request,\n * but being explicit here removes any ambiguity about which currency the\n * refund applies to. */\nconst AUTOPAY_CURRENCY = 'PLN'\n\nexport const autopayAdapterV1: GatewayAdapter = {\n providerKey: 'autopay',\n\n async createSession(input: CreateSessionInput): Promise<CreateSessionResult> {\n if (input.currencyCode !== AUTOPAY_CURRENCY) {\n const { t } = await resolveTranslations()\n throw new Error(t(\n 'gateway_autopay.errors.plnOnly',\n 'Autopay only supports PLN payments in this integration.',\n ))\n }\n const credentials = resolveCredentials(input.credentials)\n const customerEmail = readCustomerEmail(input.metadata)\n const gatewayId = readGatewayId(input.metadata)\n const orderId = sanitizeOrderId(input.paymentId)\n\n const session = buildSessionRequest({\n credentials,\n orderId,\n amount: input.amount.toFixed(2),\n currencyCode: input.currencyCode,\n description: input.description,\n gatewayId,\n customerEmail,\n })\n\n const launch = createLaunchGrant()\n\n return {\n sessionId: orderId,\n status: 'pending',\n redirectUrl: resolveLaunchUrl(buildLaunchPath(orderId, launch.token), input.successUrl),\n providerData: {\n formPost: session.formPost,\n launch,\n returnTargets: {\n successUrl: readHttpUrl(input.successUrl),\n cancelUrl: readHttpUrl(input.cancelUrl),\n },\n },\n }\n },\n\n async capture(_input: CaptureInput): Promise<CaptureResult> {\n const { t } = await resolveTranslations()\n throw new Error(t(\n 'gateway_autopay.errors.captureUnsupported',\n 'Autopay does not support capturing a payment separately \u2014 it settles immediately when the payer completes the redirect.',\n ))\n },\n\n async refund(input: RefundInput): Promise<RefundResult> {\n const credentials = resolveCredentials(input.credentials)\n const remoteId = await resolveRefundRemoteId(credentials, input)\n const result = await refundTransaction(credentials, {\n remoteId,\n amount: input.amount !== undefined ? input.amount.toFixed(2) : undefined,\n currencyCode: AUTOPAY_CURRENCY,\n idempotencyKey: input.idempotencyKey,\n })\n\n return {\n refundId: result.messageId,\n // Autopay processes refunds asynchronously (docs: up to ~30 minutes,\n // failures reported the next business day), so the acknowledgment is not\n // a settled refund: nothing is refunded yet and the payment stays\n // `captured`. Reporting `pending` here would make the service reject a\n // replay of this operation, because it compares the stored result status\n // with the unchanged payment status.\n status: 'captured' as UnifiedPaymentStatus,\n refundedAmount: 0,\n providerData: {\n refundStatus: 'pending',\n requestedAmount: input.amount ?? null,\n acknowledged: result.acknowledged,\n note: 'Autopay processes refunds asynchronously and getStatus does not report refund outcomes, so this adapter cannot confirm the final result.',\n },\n }\n },\n\n async cancel(input: CancelInput): Promise<CancelResult> {\n const credentials = resolveCredentials(input.credentials)\n const result = await cancelTransaction(credentials, {\n orderId: input.sessionId,\n idempotencyKey: input.idempotencyKey,\n })\n\n if (result.confirmation === 'CONFIRMED' && result.reason === 'CANCELED_FULLY') {\n return {\n status: 'cancelled',\n providerData: { reason: result.reason, messageId: result.messageId },\n }\n }\n\n if (result.confirmation === 'CONFIRMED') {\n // Docs also document CONFIRMED / CANCELED_PARTIALLY: at least one\n // attempt was cancelled but another attempt for the same OrderID could\n // not be (for example because it already settled). Claiming a clean\n // `cancelled` here would be a fake state transition the core status\n // machine cannot walk back from (cancelled -> captured is rejected),\n // permanently hiding a payment that actually went through. Reconcile\n // against the real current state instead of trusting the label.\n const interpretation = await resolveStatusInterpretation(credentials, input.sessionId)\n if (interpretation.status === 'captured') {\n return {\n status: 'captured',\n providerData: {\n reason: result.reason,\n messageId: result.messageId,\n reconciledAfterPartialCancel: true,\n },\n }\n }\n const { t: translatePartial } = await resolveTranslations()\n throw new Error(translatePartial(\n 'gateway_autopay.errors.cancelPartial',\n 'Autopay only partially cancelled this payment ({reason}) and no settled payment was found \u2014 this needs to be resolved manually before treating it as cancelled.',\n { reason: result.reason ?? 'unknown reason' },\n ))\n }\n\n const { t } = await resolveTranslations()\n throw new Error(t(\n 'gateway_autopay.errors.cancelFailed',\n 'Autopay could not cancel this payment. It may already be settled \u2014 try a refund instead. ({reason})',\n { reason: result.reason ?? 'no reason provided by Autopay' },\n ))\n },\n\n async getStatus(input: GetStatusInput): Promise<GatewayPaymentStatus> {\n const credentials = resolveCredentials(input.credentials)\n const { transactions, reason } = await queryTransactionStatus(credentials, { orderId: input.sessionId })\n const interpretation = interpretAutopayTransactionStatus(transactions)\n\n return {\n status: interpretation.status,\n amount: interpretation.amount,\n amountReceived: interpretation.amountReceived,\n currencyCode: interpretation.currencyCode || AUTOPAY_CURRENCY,\n providerData: {\n remoteId: interpretation.matchedRemoteId,\n anomaly: interpretation.anomaly,\n transactionCount: transactions.length,\n reason,\n },\n }\n },\n\n async verifyWebhook(_input: VerifyWebhookInput): Promise<WebhookEvent> {\n throw new Error('[internal] Autopay ITN handling is deferred to a follow-up spec (see .ai/specs/2026-09-10-autopay-hosted-pln-payment-sessions.md, \"Why ITN Is Out of Scope\") \u2014 this integration reads status via getStatus() instead')\n },\n\n mapStatus(providerStatus: string, _eventType?: string): UnifiedPaymentStatus {\n return mapAutopayStatus(providerStatus)\n },\n}\n"],
5
- "mappings": "AAgBA,SAAS,2BAA2B;AACpC,SAAS,iBAAiB,mBAAmB,aAAa,wBAAwB;AAClF;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,kBAAkB,yCAA2E;AAEtG,SAAS,mBAAmB,KAAkD;AAC5E,QAAM,YAAY,IAAI;AACtB,QAAM,YAAY,IAAI;AACtB,QAAM,aAAa,IAAI;AACvB,MAAI,OAAO,cAAc,YAAY,CAAC,WAAW;AAC/C,UAAM,IAAI,MAAM,sDAAsD;AAAA,EACxE;AACA,MAAI,OAAO,cAAc,YAAY,CAAC,WAAW;AAC/C,UAAM,IAAI,MAAM,sDAAsD;AAAA,EACxE;AACA,MAAI,OAAO,eAAe,YAAY,CAAC,YAAY;AACjD,UAAM,IAAI,MAAM,uDAAuD;AAAA,EACzE;AACA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA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B,cAAc,eAAe,gBAAgB;AAAA,MAC7C,cAAc;AAAA,QACZ,UAAU,eAAe;AAAA,QACzB,SAAS,eAAe;AAAA,QACxB,kBAAkB,aAAa;AAAA,QAC/B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,cAAc,QAAmD;AACrE,UAAM,IAAI,MAAM,2NAAsN;AAAA,EACxO;AAAA,EAEA,UAAU,gBAAwB,YAA2C;AAC3E,WAAO,iBAAiB,cAAc;AAAA,EACxC;AACF;",
4
+ "sourcesContent": ["import type {\n GatewayAdapter,\n CreateSessionInput,\n CreateSessionResult,\n CaptureInput,\n CaptureResult,\n RefundInput,\n RefundResult,\n CancelInput,\n CancelResult,\n GetStatusInput,\n GatewayPaymentStatus,\n VerifyWebhookInput,\n WebhookEvent,\n UnifiedPaymentStatus,\n} from '@open-mercato/shared/modules/payment_gateways/types'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { padDecimalPlaces, resolveExactDecimal, roundDecimal } from '@open-mercato/shared/lib/decimal'\nimport { buildLaunchPath, createLaunchGrant, readHttpUrl, resolveLaunchUrl } from '../launch'\nimport {\n buildSessionRequest,\n cancelTransaction,\n queryTransactionStatus,\n refundTransaction,\n sanitizeOrderId,\n type AutopayCredentials,\n} from '../autopay-client'\nimport { mapAutopayStatus, interpretAutopayTransactionStatus, type AutopayExactStatusInterpretation } from '../status-map'\n\nfunction resolveCredentials(raw: Record<string, unknown>): AutopayCredentials {\n const serviceId = raw.serviceId\n const sharedKey = raw.sharedKey\n const gatewayUrl = raw.gatewayUrl\n if (typeof serviceId !== 'string' || !serviceId) {\n throw new Error('[internal] Autopay credentials are missing serviceId')\n }\n if (typeof sharedKey !== 'string' || !sharedKey) {\n throw new Error('[internal] Autopay credentials are missing sharedKey')\n }\n if (typeof gatewayUrl !== 'string' || !gatewayUrl) {\n throw new Error('[internal] Autopay credentials are missing gatewayUrl')\n }\n return {\n serviceId,\n sharedKey,\n gatewayUrl,\n hashAlgorithm: raw.hashAlgorithm === 'sha512' ? 'sha512' : 'sha256',\n }\n}\n\n/**\n * `CreateSessionInput` has no dedicated customer-email field, but Autopay's\n * documented parameter table marks CustomerEmail as required (position 7).\n * This adapter reads it from `input.metadata.customerEmail` \u2014 callers of\n * `createSession` for the `autopay` provider MUST populate that key, as the\n * stock checkout submit route does.\n */\nfunction readCustomerEmail(metadata: Record<string, unknown> | undefined): string {\n const value = metadata?.customerEmail\n if (typeof value !== 'string' || !value) {\n throw new Error('[internal] Autopay requires metadata.customerEmail to be set on every session (CustomerEmail is a required field per the Autopay Online v1.1 documentation)')\n }\n return value\n}\n\nfunction readGatewayId(metadata: Record<string, unknown> | undefined): string | undefined {\n const value = metadata?.gatewayId\n return typeof value === 'string' && value ? value : undefined\n}\n\nasync function resolveStatusInterpretation(\n credentials: AutopayCredentials,\n orderId: string,\n): Promise<AutopayExactStatusInterpretation> {\n const { transactions } = await queryTransactionStatus(credentials, { orderId })\n return interpretAutopayTransactionStatus(transactions)\n}\n\n/**\n * `transactionRefund` needs Autopay's own `remoteID`, not the merchant\n * `OrderID` (`sessionId`) the canonical `paymentGatewayService.refundPayment`\n * call actually supplies \u2014 it does not thread caller metadata through to the\n * adapter. Rather than require a metadata field no real caller populates,\n * this resolves the settled transaction's `remoteID` itself via\n * `transactionStatus`, the same lookup `getStatus()` already performs. An\n * explicit `metadata.remoteId` is still honored first, as a fast path for a\n * caller that already has it cached (e.g. from a prior `getStatus` result)\n * and wants to skip the extra round trip.\n */\nasync function resolveRefundRemoteId(\n credentials: AutopayCredentials,\n input: RefundInput,\n): Promise<string> {\n const provided = input.metadata?.remoteId\n if (typeof provided === 'string' && provided) return provided\n\n const interpretation = await resolveStatusInterpretation(credentials, input.sessionId)\n if (interpretation.status !== 'captured' || !interpretation.matchedRemoteId) {\n const { t } = await resolveTranslations()\n throw new Error(t(\n 'gateway_autopay.errors.refundNotSettled',\n 'Autopay cannot refund session {sessionId}: no captured transaction was found (current status: {status}).',\n { sessionId: input.sessionId, status: interpretation.status },\n ))\n }\n return interpretation.matchedRemoteId\n}\n\n/** This package only ever creates PLN sessions (enforced in `createSession`),\n * so refunds always sign and send `Currency=PLN` explicitly rather than\n * omitting it \u2014 an omitted Currency still produces a validly-signed request,\n * but being explicit here removes any ambiguity about which currency the\n * refund applies to. */\nconst AUTOPAY_CURRENCY = 'PLN'\nconst AUTOPAY_AMOUNT_DECIMAL_PLACES = 2\n\nfunction formatAutopayAmount(amount: number, amountExact: string | undefined): string {\n const exact = resolveExactDecimal(amountExact, amount) ?? '0'\n return padDecimalPlaces(roundDecimal(exact, AUTOPAY_AMOUNT_DECIMAL_PLACES), AUTOPAY_AMOUNT_DECIMAL_PLACES)\n}\n\nexport const autopayAdapterV1: GatewayAdapter = {\n providerKey: 'autopay',\n\n async createSession(input: CreateSessionInput): Promise<CreateSessionResult> {\n if (input.currencyCode !== AUTOPAY_CURRENCY) {\n const { t } = await resolveTranslations()\n throw new Error(t(\n 'gateway_autopay.errors.plnOnly',\n 'Autopay only supports PLN payments in this integration.',\n ))\n }\n const credentials = resolveCredentials(input.credentials)\n const customerEmail = readCustomerEmail(input.metadata)\n const gatewayId = readGatewayId(input.metadata)\n const orderId = sanitizeOrderId(input.paymentId)\n\n const session = buildSessionRequest({\n credentials,\n orderId,\n amount: formatAutopayAmount(input.amount, input.amountExact),\n currencyCode: input.currencyCode,\n description: input.description,\n gatewayId,\n customerEmail,\n })\n\n const launch = createLaunchGrant()\n\n return {\n sessionId: orderId,\n status: 'pending',\n redirectUrl: resolveLaunchUrl(buildLaunchPath(orderId, launch.token), input.successUrl),\n providerData: {\n formPost: session.formPost,\n launch,\n returnTargets: {\n successUrl: readHttpUrl(input.successUrl),\n cancelUrl: readHttpUrl(input.cancelUrl),\n },\n },\n }\n },\n\n async capture(_input: CaptureInput): Promise<CaptureResult> {\n const { t } = await resolveTranslations()\n throw new Error(t(\n 'gateway_autopay.errors.captureUnsupported',\n 'Autopay does not support capturing a payment separately \u2014 it settles immediately when the payer completes the redirect.',\n ))\n },\n\n async refund(input: RefundInput): Promise<RefundResult> {\n const credentials = resolveCredentials(input.credentials)\n const remoteId = await resolveRefundRemoteId(credentials, input)\n const result = await refundTransaction(credentials, {\n remoteId,\n amount: input.amount !== undefined ? formatAutopayAmount(input.amount, input.amountExact) : undefined,\n currencyCode: AUTOPAY_CURRENCY,\n idempotencyKey: input.idempotencyKey,\n })\n\n return {\n refundId: result.messageId,\n // Autopay processes refunds asynchronously (docs: up to ~30 minutes,\n // failures reported the next business day), so the acknowledgment is not\n // a settled refund: nothing is refunded yet and the payment stays\n // `captured`. Reporting `pending` here would make the service reject a\n // replay of this operation, because it compares the stored result status\n // with the unchanged payment status.\n status: 'captured' as UnifiedPaymentStatus,\n refundedAmount: 0,\n providerData: {\n refundStatus: 'pending',\n requestedAmount: input.amount ?? null,\n acknowledged: result.acknowledged,\n note: 'Autopay processes refunds asynchronously and getStatus does not report refund outcomes, so this adapter cannot confirm the final result.',\n },\n }\n },\n\n async cancel(input: CancelInput): Promise<CancelResult> {\n const credentials = resolveCredentials(input.credentials)\n const result = await cancelTransaction(credentials, {\n orderId: input.sessionId,\n idempotencyKey: input.idempotencyKey,\n })\n\n if (result.confirmation === 'CONFIRMED' && result.reason === 'CANCELED_FULLY') {\n return {\n status: 'cancelled',\n providerData: { reason: result.reason, messageId: result.messageId },\n }\n }\n\n if (result.confirmation === 'CONFIRMED') {\n // Docs also document CONFIRMED / CANCELED_PARTIALLY: at least one\n // attempt was cancelled but another attempt for the same OrderID could\n // not be (for example because it already settled). Claiming a clean\n // `cancelled` here would be a fake state transition the core status\n // machine cannot walk back from (cancelled -> captured is rejected),\n // permanently hiding a payment that actually went through. Reconcile\n // against the real current state instead of trusting the label.\n const interpretation = await resolveStatusInterpretation(credentials, input.sessionId)\n if (interpretation.status === 'captured') {\n return {\n status: 'captured',\n providerData: {\n reason: result.reason,\n messageId: result.messageId,\n reconciledAfterPartialCancel: true,\n },\n }\n }\n const { t: translatePartial } = await resolveTranslations()\n throw new Error(translatePartial(\n 'gateway_autopay.errors.cancelPartial',\n 'Autopay only partially cancelled this payment ({reason}) and no settled payment was found \u2014 this needs to be resolved manually before treating it as cancelled.',\n { reason: result.reason ?? 'unknown reason' },\n ))\n }\n\n const { t } = await resolveTranslations()\n throw new Error(t(\n 'gateway_autopay.errors.cancelFailed',\n 'Autopay could not cancel this payment. It may already be settled \u2014 try a refund instead. ({reason})',\n { reason: result.reason ?? 'no reason provided by Autopay' },\n ))\n },\n\n async getStatus(input: GetStatusInput): Promise<GatewayPaymentStatus> {\n const credentials = resolveCredentials(input.credentials)\n const { transactions, reason } = await queryTransactionStatus(credentials, { orderId: input.sessionId })\n const interpretation = interpretAutopayTransactionStatus(transactions)\n\n return {\n status: interpretation.status,\n amount: interpretation.amount,\n amountExact: interpretation.amountExact,\n amountReceived: interpretation.amountReceived,\n amountReceivedExact: interpretation.amountReceivedExact,\n currencyCode: interpretation.currencyCode || AUTOPAY_CURRENCY,\n providerData: {\n remoteId: interpretation.matchedRemoteId,\n anomaly: interpretation.anomaly,\n transactionCount: transactions.length,\n reason,\n },\n }\n },\n\n async verifyWebhook(_input: VerifyWebhookInput): Promise<WebhookEvent> {\n throw new Error('[internal] Autopay ITN handling is deferred to a follow-up spec (see .ai/specs/2026-09-10-autopay-hosted-pln-payment-sessions.md, \"Why ITN Is Out of Scope\") \u2014 this integration reads status via getStatus() instead')\n },\n\n mapStatus(providerStatus: string, _eventType?: string): UnifiedPaymentStatus {\n return mapAutopayStatus(providerStatus)\n },\n}\n"],
5
+ "mappings": "AAgBA,SAAS,2BAA2B;AACpC,SAAS,kBAAkB,qBAAqB,oBAAoB;AACpE,SAAS,iBAAiB,mBAAmB,aAAa,wBAAwB;AAClF;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,kBAAkB,yCAAgF;AAE3G,SAAS,mBAAmB,KAAkD;AAC5E,QAAM,YAAY,IAAI;AACtB,QA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AA,QACA;AAAA,QACA,EAAE,QAAQ,OAAO,UAAU,iBAAiB;AAAA,MAC9C,CAAC;AAAA,IACH;AAEA,UAAM,EAAE,EAAE,IAAI,MAAM,oBAAoB;AACxC,UAAM,IAAI,MAAM;AAAA,MACd;AAAA,MACA;AAAA,MACA,EAAE,QAAQ,OAAO,UAAU,gCAAgC;AAAA,IAC7D,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,UAAU,OAAsD;AACpE,UAAM,cAAc,mBAAmB,MAAM,WAAW;AACxD,UAAM,EAAE,cAAc,OAAO,IAAI,MAAM,uBAAuB,aAAa,EAAE,SAAS,MAAM,UAAU,CAAC;AACvG,UAAM,iBAAiB,kCAAkC,YAAY;AAErE,WAAO;AAAA,MACL,QAAQ,eAAe;AAAA,MACvB,QAAQ,eAAe;AAAA,MACvB,aAAa,eAAe;AAAA,MAC5B,gBAAgB,eAAe;AAAA,MAC/B,qBAAqB,eAAe;AAAA,MACpC,cAAc,eAAe,gBAAgB;AAAA,MAC7C,cAAc;AAAA,QACZ,UAAU,eAAe;AAAA,QACzB,SAAS,eAAe;AAAA,QACxB,kBAAkB,aAAa;AAAA,QAC/B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,cAAc,QAAmD;AACrE,UAAM,IAAI,MAAM,2NAAsN;AAAA,EACxO;AAAA,EAEA,UAAU,gBAAwB,YAA2C;AAC3E,WAAO,iBAAiB,cAAc;AAAA,EACxC;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,3 +1,4 @@
1
+ import { addDecimals, decimalToNumber, decimalToString, parseDecimal } from "@open-mercato/shared/lib/decimal";
1
2
  const AUTOPAY_STATUS_MAP = {
2
3
  PENDING: "pending",
3
4
  SUCCESS: "captured",
@@ -6,28 +7,41 @@ const AUTOPAY_STATUS_MAP = {
6
7
  function mapAutopayStatus(paymentStatus) {
7
8
  return AUTOPAY_STATUS_MAP[paymentStatus] ?? "unknown";
8
9
  }
10
+ function exactAmount(value) {
11
+ const parsed = parseDecimal(value);
12
+ return parsed ? decimalToString(parsed) : "0";
13
+ }
14
+ function amounts(amount, amountReceived) {
15
+ return {
16
+ amount: decimalToNumber(amount),
17
+ amountExact: amount,
18
+ amountReceived: decimalToNumber(amountReceived),
19
+ amountReceivedExact: amountReceived
20
+ };
21
+ }
9
22
  function interpretAutopayTransactionStatus(transactions) {
10
23
  const successes = transactions.filter((transaction) => transaction.paymentStatus === "SUCCESS");
11
24
  const pendings = transactions.filter((transaction) => transaction.paymentStatus === "PENDING");
12
25
  const failures = transactions.filter((transaction) => transaction.paymentStatus === "FAILURE");
13
26
  if (successes.length === 1) {
14
27
  const [success] = successes;
15
- const amount = Number(success.amount);
28
+ const amount = exactAmount(success.amount);
16
29
  return {
17
30
  status: "captured",
18
- amount,
19
- amountReceived: amount,
31
+ ...amounts(amount, amount),
20
32
  currencyCode: success.currency,
21
33
  matchedRemoteId: success.remoteID
22
34
  };
23
35
  }
24
36
  if (successes.length > 1) {
25
37
  const [first] = successes;
26
- const totalReceived = successes.reduce((sum, transaction) => sum + Number(transaction.amount), 0);
38
+ const totalReceived = successes.reduce(
39
+ (sum, transaction) => decimalToString(addDecimals(sum, exactAmount(transaction.amount))),
40
+ "0"
41
+ );
27
42
  return {
28
43
  status: "captured",
29
- amount: Number(first.amount),
30
- amountReceived: totalReceived,
44
+ ...amounts(exactAmount(first.amount), totalReceived),
31
45
  currencyCode: first.currency,
32
46
  matchedRemoteId: first.remoteID,
33
47
  anomaly: "overpaid"
@@ -37,8 +51,7 @@ function interpretAutopayTransactionStatus(transactions) {
37
51
  const [pending] = pendings;
38
52
  return {
39
53
  status: "pending",
40
- amount: Number(pending.amount),
41
- amountReceived: 0,
54
+ ...amounts(exactAmount(pending.amount), "0"),
42
55
  currencyCode: pending.currency,
43
56
  matchedRemoteId: pending.remoteID
44
57
  };
@@ -47,8 +60,7 @@ function interpretAutopayTransactionStatus(transactions) {
47
60
  const [first] = failures;
48
61
  return {
49
62
  status: "failed",
50
- amount: Number(first.amount),
51
- amountReceived: 0,
63
+ ...amounts(exactAmount(first.amount), "0"),
52
64
  currencyCode: first.currency,
53
65
  matchedRemoteId: first.remoteID
54
66
  };
@@ -57,16 +69,14 @@ function interpretAutopayTransactionStatus(transactions) {
57
69
  const [first] = transactions;
58
70
  return {
59
71
  status: "unknown",
60
- amount: Number(first.amount),
61
- amountReceived: 0,
72
+ ...amounts(exactAmount(first.amount), "0"),
62
73
  currencyCode: first.currency,
63
74
  matchedRemoteId: first.remoteID
64
75
  };
65
76
  }
66
77
  return {
67
78
  status: "unknown",
68
- amount: 0,
69
- amountReceived: 0,
79
+ ...amounts("0", "0"),
70
80
  currencyCode: ""
71
81
  };
72
82
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/gateway_autopay/lib/status-map.ts"],
4
- "sourcesContent": ["import type { UnifiedPaymentStatus } from '@open-mercato/shared/modules/payment_gateways/types'\n\n/**\n * Base hosted-redirect flow only sends PENDING/SUCCESS/FAILURE (docs \u00A7\n * \"Szczeg\u00F3\u0142owy opis zachowania i zmiany status\u00F3w p\u0142atno\u015Bci\"). ON_HOLD and\n * CONFIRMED belong to the out-of-scope card pre-authorization extension and\n * are intentionally absent here \u2014 an unrecognized value must map to\n * 'unknown', never be guessed into a success state.\n */\nconst AUTOPAY_STATUS_MAP: Record<string, UnifiedPaymentStatus> = {\n PENDING: 'pending',\n SUCCESS: 'captured',\n FAILURE: 'failed',\n}\n\nexport function mapAutopayStatus(paymentStatus: string): UnifiedPaymentStatus {\n return AUTOPAY_STATUS_MAP[paymentStatus] ?? 'unknown'\n}\n\nexport interface AutopayTransactionRecord {\n orderID: string\n remoteID: string\n amount: string\n currency: string\n gatewayID?: string\n paymentDate: string\n paymentStatus: string\n paymentStatusDetails?: string\n}\n\nexport interface AutopayStatusInterpretation {\n status: UnifiedPaymentStatus\n /** The transaction's own declared amount (docs: identical across every\n * record for one OrderID outside the out-of-scope commission-added\n * model), sourced from the same record as `amountReceived` so the two\n * never describe two different underlying transactions. */\n amount: number\n amountReceived: number\n currencyCode: string\n matchedRemoteId?: string\n anomaly?: 'overpaid'\n}\n\n/**\n * Applies the multi-transaction interpretation table from docs \u00A7\n * \"Odpytanie o status transakcji\" \u2014 a single OrderID can carry multiple\n * underlying Autopay transactions (e.g. the payer retried with a different\n * channel).\n */\nexport function interpretAutopayTransactionStatus(\n transactions: AutopayTransactionRecord[],\n): AutopayStatusInterpretation {\n const successes = transactions.filter((transaction) => transaction.paymentStatus === 'SUCCESS')\n const pendings = transactions.filter((transaction) => transaction.paymentStatus === 'PENDING')\n const failures = transactions.filter((transaction) => transaction.paymentStatus === 'FAILURE')\n\n if (successes.length === 1) {\n const [success] = successes\n const amount = Number(success.amount)\n return {\n status: 'captured',\n amount,\n amountReceived: amount,\n currencyCode: success.currency,\n matchedRemoteId: success.remoteID,\n }\n }\n\n if (successes.length > 1) {\n const [first] = successes\n const totalReceived = successes.reduce((sum, transaction) => sum + Number(transaction.amount), 0)\n return {\n status: 'captured',\n amount: Number(first.amount),\n amountReceived: totalReceived,\n currencyCode: first.currency,\n matchedRemoteId: first.remoteID,\n anomaly: 'overpaid',\n }\n }\n\n if (pendings.length > 0) {\n const [pending] = pendings\n return {\n status: 'pending',\n amount: Number(pending.amount),\n amountReceived: 0,\n currencyCode: pending.currency,\n matchedRemoteId: pending.remoteID,\n }\n }\n\n // Only a set of exclusively FAILURE records is a confirmed failed outcome.\n // Anything else non-empty here is either a mix of FAILURE and an\n // unrecognized status, or entirely unrecognized statuses (e.g. the\n // out-of-scope preauth extension's ON_HOLD/CONFIRMED) \u2014 never collapse\n // those into `failed`, which the core status machine treats as terminal\n // and would then reject a later `captured` transition.\n if (failures.length > 0 && failures.length === transactions.length) {\n const [first] = failures\n return {\n status: 'failed',\n amount: Number(first.amount),\n amountReceived: 0,\n currencyCode: first.currency,\n matchedRemoteId: first.remoteID,\n }\n }\n\n if (transactions.length > 0) {\n const [first] = transactions\n return {\n status: 'unknown',\n amount: Number(first.amount),\n amountReceived: 0,\n currencyCode: first.currency,\n matchedRemoteId: first.remoteID,\n }\n }\n\n return {\n status: 'unknown',\n amount: 0,\n amountReceived: 0,\n currencyCode: '',\n }\n}\n"],
5
- "mappings": "AASA,MAAM,qBAA2D;AAAA,EAC/D,SAAS;AAAA,EACT,SAAS;AAAA,EACT,SAAS;AACX;AAEO,SAAS,iBAAiB,eAA6C;AAC5E,SAAO,mBAAmB,aAAa,KAAK;AAC9C;AAgCO,SAAS,kCACd,cAC6B;AAC7B,QAAM,YAAY,aAAa,OAAO,CAAC,gBAAgB,YAAY,kBAAkB,SAAS;AAC9F,QAAM,WAAW,aAAa,OAAO,CAAC,gBAAgB,YAAY,kBAAkB,SAAS;AAC7F,QAAM,WAAW,aAAa,OAAO,CAAC,gBAAgB,YAAY,kBAAkB,SAAS;AAE7F,MAAI,UAAU,WAAW,GAAG;AAC1B,UAAM,CAAC,OAAO,IAAI;AAClB,UAAM,SAAS,OAAO,QAAQ,MAAM;AACpC,WAAO;AAAA,MACL,QAAQ;AAAA,MACR;AAAA,MACA,gBAAgB;AAAA,MAChB,cAAc,QAAQ;AAAA,MACtB,iBAAiB,QAAQ;AAAA,IAC3B;AAAA,EACF;AAEA,MAAI,UAAU,SAAS,GAAG;AACxB,UAAM,CAAC,KAAK,IAAI;AAChB,UAAM,gBAAgB,UAAU,OAAO,CAAC,KAAK,gBAAgB,MAAM,OAAO,YAAY,MAAM,GAAG,CAAC;AAChG,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,QAAQ,OAAO,MAAM,MAAM;AAAA,MAC3B,gBAAgB;AAAA,MAChB,cAAc,MAAM;AAAA,MACpB,iBAAiB,MAAM;AAAA,MACvB,SAAS;AAAA,IACX;AAAA,EACF;AAEA,MAAI,SAAS,SAAS,GAAG;AACvB,UAAM,CAAC,OAAO,IAAI;AAClB,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,QAAQ,OAAO,QAAQ,MAAM;AAAA,MAC7B,gBAAgB;AAAA,MAChB,cAAc,QAAQ;AAAA,MACtB,iBAAiB,QAAQ;AAAA,IAC3B;AAAA,EACF;AAQA,MAAI,SAAS,SAAS,KAAK,SAAS,WAAW,aAAa,QAAQ;AAClE,UAAM,CAAC,KAAK,IAAI;AAChB,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,QAAQ,OAAO,MAAM,MAAM;AAAA,MAC3B,gBAAgB;AAAA,MAChB,cAAc,MAAM;AAAA,MACpB,iBAAiB,MAAM;AAAA,IACzB;AAAA,EACF;AAEA,MAAI,aAAa,SAAS,GAAG;AAC3B,UAAM,CAAC,KAAK,IAAI;AAChB,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,QAAQ,OAAO,MAAM,MAAM;AAAA,MAC3B,gBAAgB;AAAA,MAChB,cAAc,MAAM;AAAA,MACpB,iBAAiB,MAAM;AAAA,IACzB;AAAA,EACF;AAEA,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,cAAc;AAAA,EAChB;AACF;",
4
+ "sourcesContent": ["import { addDecimals, decimalToNumber, decimalToString, parseDecimal } from '@open-mercato/shared/lib/decimal'\nimport type { UnifiedPaymentStatus } from '@open-mercato/shared/modules/payment_gateways/types'\n\n/**\n * Base hosted-redirect flow only sends PENDING/SUCCESS/FAILURE (docs \u00A7\n * \"Szczeg\u00F3\u0142owy opis zachowania i zmiany status\u00F3w p\u0142atno\u015Bci\"). ON_HOLD and\n * CONFIRMED belong to the out-of-scope card pre-authorization extension and\n * are intentionally absent here \u2014 an unrecognized value must map to\n * 'unknown', never be guessed into a success state.\n */\nconst AUTOPAY_STATUS_MAP: Record<string, UnifiedPaymentStatus> = {\n PENDING: 'pending',\n SUCCESS: 'captured',\n FAILURE: 'failed',\n}\n\nexport function mapAutopayStatus(paymentStatus: string): UnifiedPaymentStatus {\n return AUTOPAY_STATUS_MAP[paymentStatus] ?? 'unknown'\n}\n\nexport interface AutopayTransactionRecord {\n orderID: string\n remoteID: string\n amount: string\n currency: string\n gatewayID?: string\n paymentDate: string\n paymentStatus: string\n paymentStatusDetails?: string\n}\n\nexport interface AutopayStatusInterpretation {\n status: UnifiedPaymentStatus\n /** The transaction's own declared amount (docs: identical across every\n * record for one OrderID outside the out-of-scope commission-added\n * model), sourced from the same record as `amountReceived` so the two\n * never describe two different underlying transactions. */\n amount: number\n /** `amount` as an exact decimal string. */\n amountExact?: string\n amountReceived: number\n /** `amountReceived` as an exact decimal string. */\n amountReceivedExact?: string\n currencyCode: string\n matchedRemoteId?: string\n anomaly?: 'overpaid'\n}\n\nexport type AutopayExactStatusInterpretation = AutopayStatusInterpretation & {\n amountExact: string\n amountReceivedExact: string\n}\n\n/**\n * Applies the multi-transaction interpretation table from docs \u00A7\n * \"Odpytanie o status transakcji\" \u2014 a single OrderID can carry multiple\n * underlying Autopay transactions (e.g. the payer retried with a different\n * channel).\n */\nfunction exactAmount(value: string | null | undefined): string {\n const parsed = parseDecimal(value)\n return parsed ? decimalToString(parsed) : '0'\n}\n\nfunction amounts(amount: string, amountReceived: string) {\n return {\n amount: decimalToNumber(amount),\n amountExact: amount,\n amountReceived: decimalToNumber(amountReceived),\n amountReceivedExact: amountReceived,\n }\n}\n\nexport function interpretAutopayTransactionStatus(\n transactions: AutopayTransactionRecord[],\n): AutopayExactStatusInterpretation {\n const successes = transactions.filter((transaction) => transaction.paymentStatus === 'SUCCESS')\n const pendings = transactions.filter((transaction) => transaction.paymentStatus === 'PENDING')\n const failures = transactions.filter((transaction) => transaction.paymentStatus === 'FAILURE')\n\n if (successes.length === 1) {\n const [success] = successes\n const amount = exactAmount(success.amount)\n return {\n status: 'captured',\n ...amounts(amount, amount),\n currencyCode: success.currency,\n matchedRemoteId: success.remoteID,\n }\n }\n\n if (successes.length > 1) {\n const [first] = successes\n const totalReceived = successes.reduce(\n (sum, transaction) => decimalToString(addDecimals(sum, exactAmount(transaction.amount))),\n '0',\n )\n return {\n status: 'captured',\n ...amounts(exactAmount(first.amount), totalReceived),\n currencyCode: first.currency,\n matchedRemoteId: first.remoteID,\n anomaly: 'overpaid',\n }\n }\n\n if (pendings.length > 0) {\n const [pending] = pendings\n return {\n status: 'pending',\n ...amounts(exactAmount(pending.amount), '0'),\n currencyCode: pending.currency,\n matchedRemoteId: pending.remoteID,\n }\n }\n\n // Only a set of exclusively FAILURE records is a confirmed failed outcome.\n // Anything else non-empty here is either a mix of FAILURE and an\n // unrecognized status, or entirely unrecognized statuses (e.g. the\n // out-of-scope preauth extension's ON_HOLD/CONFIRMED) \u2014 never collapse\n // those into `failed`, which the core status machine treats as terminal\n // and would then reject a later `captured` transition.\n if (failures.length > 0 && failures.length === transactions.length) {\n const [first] = failures\n return {\n status: 'failed',\n ...amounts(exactAmount(first.amount), '0'),\n currencyCode: first.currency,\n matchedRemoteId: first.remoteID,\n }\n }\n\n if (transactions.length > 0) {\n const [first] = transactions\n return {\n status: 'unknown',\n ...amounts(exactAmount(first.amount), '0'),\n currencyCode: first.currency,\n matchedRemoteId: first.remoteID,\n }\n }\n\n return {\n status: 'unknown',\n ...amounts('0', '0'),\n currencyCode: '',\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,aAAa,iBAAiB,iBAAiB,oBAAoB;AAU5E,MAAM,qBAA2D;AAAA,EAC/D,SAAS;AAAA,EACT,SAAS;AAAA,EACT,SAAS;AACX;AAEO,SAAS,iBAAiB,eAA6C;AAC5E,SAAO,mBAAmB,aAAa,KAAK;AAC9C;AAyCA,SAAS,YAAY,OAA0C;AAC7D,QAAM,SAAS,aAAa,KAAK;AACjC,SAAO,SAAS,gBAAgB,MAAM,IAAI;AAC5C;AAEA,SAAS,QAAQ,QAAgB,gBAAwB;AACvD,SAAO;AAAA,IACL,QAAQ,gBAAgB,MAAM;AAAA,IAC9B,aAAa;AAAA,IACb,gBAAgB,gBAAgB,cAAc;AAAA,IAC9C,qBAAqB;AAAA,EACvB;AACF;AAEO,SAAS,kCACd,cACkC;AAClC,QAAM,YAAY,a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;AAAA,IACzB;AAAA,EACF;AAEA,MAAI,aAAa,SAAS,GAAG;AAC3B,UAAM,CAAC,KAAK,IAAI;AAChB,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,GAAG,QAAQ,YAAY,MAAM,MAAM,GAAG,GAAG;AAAA,MACzC,cAAc,MAAM;AAAA,MACpB,iBAAiB,MAAM;AAAA,IACzB;AAAA,EACF;AAEA,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,GAAG,QAAQ,KAAK,GAAG;AAAA,IACnB,cAAc;AAAA,EAChB;AACF;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/gateway-autopay",
3
- "version": "0.10.1-develop.8287.1.7313a0fe67",
3
+ "version": "0.10.1-develop.8291.1.6ec3aee41c",
4
4
  "license": "MIT",
5
5
  "description": "Autopay Online v1.1 hosted PLN payment gateway provider for Open Mercato",
6
6
  "type": "module",
@@ -63,19 +63,19 @@
63
63
  }
64
64
  },
65
65
  "dependencies": {
66
- "@open-mercato/core": "0.10.1-develop.8287.1.7313a0fe67"
66
+ "@open-mercato/core": "0.10.1-develop.8291.1.6ec3aee41c"
67
67
  },
68
68
  "peerDependencies": {
69
69
  "@mikro-orm/postgresql": "^7.0.14",
70
- "@open-mercato/ai-assistant": "0.10.1-develop.8287.1.7313a0fe67",
71
- "@open-mercato/shared": "0.10.1-develop.8287.1.7313a0fe67",
72
- "@open-mercato/ui": "0.10.1-develop.8287.1.7313a0fe67",
70
+ "@open-mercato/ai-assistant": "0.10.1-develop.8291.1.6ec3aee41c",
71
+ "@open-mercato/shared": "0.10.1-develop.8291.1.6ec3aee41c",
72
+ "@open-mercato/ui": "0.10.1-develop.8291.1.6ec3aee41c",
73
73
  "react": "^19.0.0",
74
74
  "react-dom": "^19.0.0"
75
75
  },
76
76
  "devDependencies": {
77
- "@open-mercato/ai-assistant": "0.10.1-develop.8287.1.7313a0fe67",
78
- "@open-mercato/shared": "0.10.1-develop.8287.1.7313a0fe67",
77
+ "@open-mercato/ai-assistant": "0.10.1-develop.8291.1.6ec3aee41c",
78
+ "@open-mercato/shared": "0.10.1-develop.8291.1.6ec3aee41c",
79
79
  "@types/jest": "^30.0.0",
80
80
  "esbuild": "^0.28.1",
81
81
  "glob": "^14.0.6",
@@ -0,0 +1,8 @@
1
+ import type { AutopayStatusInterpretation } from '../../lib/status-map'
2
+
3
+ export const legacyStatusInterpretation: AutopayStatusInterpretation = {
4
+ status: 'captured',
5
+ amount: 10,
6
+ amountReceived: 10,
7
+ currencyCode: 'PLN',
8
+ }
@@ -0,0 +1,49 @@
1
+ import { autopayAdapterV1 } from '../lib/adapters/v1'
2
+ import { interpretAutopayTransactionStatus, type AutopayTransactionRecord } from '../lib/status-map'
3
+
4
+ const credentials = {
5
+ serviceId: '2',
6
+ sharedKey: '2test2',
7
+ gatewayUrl: 'https://testpay.autopay.eu/sciezka',
8
+ }
9
+
10
+ function tx(overrides: Partial<AutopayTransactionRecord>): AutopayTransactionRecord {
11
+ return {
12
+ orderID: 'order-1',
13
+ remoteID: 'remote-1',
14
+ amount: '0.10',
15
+ currency: 'PLN',
16
+ paymentDate: '20010101111111',
17
+ paymentStatus: 'SUCCESS',
18
+ ...overrides,
19
+ }
20
+ }
21
+
22
+ describe('Autopay exact amounts', () => {
23
+ it('sums overpaid transactions exactly', () => {
24
+ const result = interpretAutopayTransactionStatus([
25
+ tx({ remoteID: 'r1', amount: '0.10' }),
26
+ tx({ remoteID: 'r2', amount: '0.20' }),
27
+ ])
28
+ expect(result.amountReceivedExact).toBe('0.3')
29
+ expect(result.amountReceived).toBe(0.3)
30
+ expect(result.amountExact).toBe('0.1')
31
+ })
32
+
33
+ it('sends the exact amount, padded to two decimals', async () => {
34
+ const result = await autopayAdapterV1.createSession({
35
+ paymentId: '3fa85f64-5717-4562-b3fc-2c963f66afa6',
36
+ tenantId: 't1',
37
+ organizationId: 'o1',
38
+ amount: 90071992547409.9,
39
+ amountExact: '90071992547409.91',
40
+ currencyCode: 'PLN',
41
+ credentials,
42
+ metadata: { customerEmail: 'buyer@example.com' },
43
+ successUrl: 'https://shop.example.com/pay/s/success/abc',
44
+ cancelUrl: 'https://shop.example.com/pay/s/cancel/abc',
45
+ })
46
+ const providerData = result.providerData as { formPost: { fields: Record<string, string> } }
47
+ expect(providerData.formPost.fields.Amount).toBe('90071992547409.91')
48
+ })
49
+ })
@@ -0,0 +1,29 @@
1
+ /** @jest-environment node */
2
+ import * as path from 'node:path'
3
+ import * as ts from 'typescript'
4
+ import { legacyStatusInterpretation } from './__fixtures__/legacyStatusInterpretation'
5
+
6
+ const FIXTURE = path.join(__dirname, '__fixtures__', 'legacyStatusInterpretation.ts')
7
+ const TSCONFIG = path.join(__dirname, '..', '..', '..', '..', 'tsconfig.json')
8
+
9
+ function fixtureDiagnostics(): string[] {
10
+ const config = ts.readConfigFile(TSCONFIG, ts.sys.readFile)
11
+ const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, path.dirname(TSCONFIG))
12
+ const program = ts.createProgram([FIXTURE], { ...parsed.options, noEmit: true })
13
+ const source = program.getSourceFile(FIXTURE)
14
+ if (!source) throw new Error('[internal] fixture not found')
15
+ return [...program.getSyntacticDiagnostics(source), ...program.getSemanticDiagnostics(source)].map((diagnostic) =>
16
+ ts.flattenDiagnosticMessageText(diagnostic.messageText, ' '),
17
+ )
18
+ }
19
+
20
+ describe('AutopayStatusInterpretation stays backward compatible (spec D7)', () => {
21
+ it('compiles the pre-exact construction shape without the exact siblings', () => {
22
+ expect(fixtureDiagnostics()).toEqual([])
23
+ }, 120000)
24
+
25
+ it('keeps the legacy numeric amounts', () => {
26
+ expect(legacyStatusInterpretation.amount).toBe(10)
27
+ expect(legacyStatusInterpretation).not.toHaveProperty('amountExact')
28
+ })
29
+ })
@@ -15,6 +15,7 @@ import type {
15
15
  UnifiedPaymentStatus,
16
16
  } from '@open-mercato/shared/modules/payment_gateways/types'
17
17
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
18
+ import { padDecimalPlaces, resolveExactDecimal, roundDecimal } from '@open-mercato/shared/lib/decimal'
18
19
  import { buildLaunchPath, createLaunchGrant, readHttpUrl, resolveLaunchUrl } from '../launch'
19
20
  import {
20
21
  buildSessionRequest,
@@ -24,7 +25,7 @@ import {
24
25
  sanitizeOrderId,
25
26
  type AutopayCredentials,
26
27
  } from '../autopay-client'
27
- import { mapAutopayStatus, interpretAutopayTransactionStatus, type AutopayStatusInterpretation } from '../status-map'
28
+ import { mapAutopayStatus, interpretAutopayTransactionStatus, type AutopayExactStatusInterpretation } from '../status-map'
28
29
 
29
30
  function resolveCredentials(raw: Record<string, unknown>): AutopayCredentials {
30
31
  const serviceId = raw.serviceId
@@ -70,7 +71,7 @@ function readGatewayId(metadata: Record<string, unknown> | undefined): string |
70
71
  async function resolveStatusInterpretation(
71
72
  credentials: AutopayCredentials,
72
73
  orderId: string,
73
- ): Promise<AutopayStatusInterpretation> {
74
+ ): Promise<AutopayExactStatusInterpretation> {
74
75
  const { transactions } = await queryTransactionStatus(credentials, { orderId })
75
76
  return interpretAutopayTransactionStatus(transactions)
76
77
  }
@@ -111,6 +112,12 @@ async function resolveRefundRemoteId(
111
112
  * but being explicit here removes any ambiguity about which currency the
112
113
  * refund applies to. */
113
114
  const AUTOPAY_CURRENCY = 'PLN'
115
+ const AUTOPAY_AMOUNT_DECIMAL_PLACES = 2
116
+
117
+ function formatAutopayAmount(amount: number, amountExact: string | undefined): string {
118
+ const exact = resolveExactDecimal(amountExact, amount) ?? '0'
119
+ return padDecimalPlaces(roundDecimal(exact, AUTOPAY_AMOUNT_DECIMAL_PLACES), AUTOPAY_AMOUNT_DECIMAL_PLACES)
120
+ }
114
121
 
115
122
  export const autopayAdapterV1: GatewayAdapter = {
116
123
  providerKey: 'autopay',
@@ -131,7 +138,7 @@ export const autopayAdapterV1: GatewayAdapter = {
131
138
  const session = buildSessionRequest({
132
139
  credentials,
133
140
  orderId,
134
- amount: input.amount.toFixed(2),
141
+ amount: formatAutopayAmount(input.amount, input.amountExact),
135
142
  currencyCode: input.currencyCode,
136
143
  description: input.description,
137
144
  gatewayId,
@@ -168,7 +175,7 @@ export const autopayAdapterV1: GatewayAdapter = {
168
175
  const remoteId = await resolveRefundRemoteId(credentials, input)
169
176
  const result = await refundTransaction(credentials, {
170
177
  remoteId,
171
- amount: input.amount !== undefined ? input.amount.toFixed(2) : undefined,
178
+ amount: input.amount !== undefined ? formatAutopayAmount(input.amount, input.amountExact) : undefined,
172
179
  currencyCode: AUTOPAY_CURRENCY,
173
180
  idempotencyKey: input.idempotencyKey,
174
181
  })
@@ -249,7 +256,9 @@ export const autopayAdapterV1: GatewayAdapter = {
249
256
  return {
250
257
  status: interpretation.status,
251
258
  amount: interpretation.amount,
259
+ amountExact: interpretation.amountExact,
252
260
  amountReceived: interpretation.amountReceived,
261
+ amountReceivedExact: interpretation.amountReceivedExact,
253
262
  currencyCode: interpretation.currencyCode || AUTOPAY_CURRENCY,
254
263
  providerData: {
255
264
  remoteId: interpretation.matchedRemoteId,
@@ -1,3 +1,4 @@
1
+ import { addDecimals, decimalToNumber, decimalToString, parseDecimal } from '@open-mercato/shared/lib/decimal'
1
2
  import type { UnifiedPaymentStatus } from '@open-mercato/shared/modules/payment_gateways/types'
2
3
 
3
4
  /**
@@ -35,32 +36,54 @@ export interface AutopayStatusInterpretation {
35
36
  * model), sourced from the same record as `amountReceived` so the two
36
37
  * never describe two different underlying transactions. */
37
38
  amount: number
39
+ /** `amount` as an exact decimal string. */
40
+ amountExact?: string
38
41
  amountReceived: number
42
+ /** `amountReceived` as an exact decimal string. */
43
+ amountReceivedExact?: string
39
44
  currencyCode: string
40
45
  matchedRemoteId?: string
41
46
  anomaly?: 'overpaid'
42
47
  }
43
48
 
49
+ export type AutopayExactStatusInterpretation = AutopayStatusInterpretation & {
50
+ amountExact: string
51
+ amountReceivedExact: string
52
+ }
53
+
44
54
  /**
45
55
  * Applies the multi-transaction interpretation table from docs §
46
56
  * "Odpytanie o status transakcji" — a single OrderID can carry multiple
47
57
  * underlying Autopay transactions (e.g. the payer retried with a different
48
58
  * channel).
49
59
  */
60
+ function exactAmount(value: string | null | undefined): string {
61
+ const parsed = parseDecimal(value)
62
+ return parsed ? decimalToString(parsed) : '0'
63
+ }
64
+
65
+ function amounts(amount: string, amountReceived: string) {
66
+ return {
67
+ amount: decimalToNumber(amount),
68
+ amountExact: amount,
69
+ amountReceived: decimalToNumber(amountReceived),
70
+ amountReceivedExact: amountReceived,
71
+ }
72
+ }
73
+
50
74
  export function interpretAutopayTransactionStatus(
51
75
  transactions: AutopayTransactionRecord[],
52
- ): AutopayStatusInterpretation {
76
+ ): AutopayExactStatusInterpretation {
53
77
  const successes = transactions.filter((transaction) => transaction.paymentStatus === 'SUCCESS')
54
78
  const pendings = transactions.filter((transaction) => transaction.paymentStatus === 'PENDING')
55
79
  const failures = transactions.filter((transaction) => transaction.paymentStatus === 'FAILURE')
56
80
 
57
81
  if (successes.length === 1) {
58
82
  const [success] = successes
59
- const amount = Number(success.amount)
83
+ const amount = exactAmount(success.amount)
60
84
  return {
61
85
  status: 'captured',
62
- amount,
63
- amountReceived: amount,
86
+ ...amounts(amount, amount),
64
87
  currencyCode: success.currency,
65
88
  matchedRemoteId: success.remoteID,
66
89
  }
@@ -68,11 +91,13 @@ export function interpretAutopayTransactionStatus(
68
91
 
69
92
  if (successes.length > 1) {
70
93
  const [first] = successes
71
- const totalReceived = successes.reduce((sum, transaction) => sum + Number(transaction.amount), 0)
94
+ const totalReceived = successes.reduce(
95
+ (sum, transaction) => decimalToString(addDecimals(sum, exactAmount(transaction.amount))),
96
+ '0',
97
+ )
72
98
  return {
73
99
  status: 'captured',
74
- amount: Number(first.amount),
75
- amountReceived: totalReceived,
100
+ ...amounts(exactAmount(first.amount), totalReceived),
76
101
  currencyCode: first.currency,
77
102
  matchedRemoteId: first.remoteID,
78
103
  anomaly: 'overpaid',
@@ -83,8 +108,7 @@ export function interpretAutopayTransactionStatus(
83
108
  const [pending] = pendings
84
109
  return {
85
110
  status: 'pending',
86
- amount: Number(pending.amount),
87
- amountReceived: 0,
111
+ ...amounts(exactAmount(pending.amount), '0'),
88
112
  currencyCode: pending.currency,
89
113
  matchedRemoteId: pending.remoteID,
90
114
  }
@@ -100,8 +124,7 @@ export function interpretAutopayTransactionStatus(
100
124
  const [first] = failures
101
125
  return {
102
126
  status: 'failed',
103
- amount: Number(first.amount),
104
- amountReceived: 0,
127
+ ...amounts(exactAmount(first.amount), '0'),
105
128
  currencyCode: first.currency,
106
129
  matchedRemoteId: first.remoteID,
107
130
  }
@@ -111,8 +134,7 @@ export function interpretAutopayTransactionStatus(
111
134
  const [first] = transactions
112
135
  return {
113
136
  status: 'unknown',
114
- amount: Number(first.amount),
115
- amountReceived: 0,
137
+ ...amounts(exactAmount(first.amount), '0'),
116
138
  currencyCode: first.currency,
117
139
  matchedRemoteId: first.remoteID,
118
140
  }
@@ -120,8 +142,7 @@ export function interpretAutopayTransactionStatus(
120
142
 
121
143
  return {
122
144
  status: 'unknown',
123
- amount: 0,
124
- amountReceived: 0,
145
+ ...amounts('0', '0'),
125
146
  currencyCode: '',
126
147
  }
127
148
  }