@fire-spark/payments 0.24.0 → 0.26.0

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.
package/dist/index.d.ts CHANGED
@@ -211,6 +211,7 @@ declare const PAYMENT_ERROR_DEFAULTS: {
211
211
  readonly BATCH_CLOSE_REQUIRED: ErrorDefaults;
212
212
  readonly INVALID_CREDENTIALS: ErrorDefaults;
213
213
  readonly INVALID_REQUEST: ErrorDefaults;
214
+ readonly INVALID_AMOUNT: ErrorDefaults;
214
215
  readonly PROVIDER_UNAVAILABLE: ErrorDefaults;
215
216
  readonly NETWORK_ERROR: {
216
217
  readonly reason: "network";
@@ -474,8 +475,16 @@ type PaymentTransient = {
474
475
  /** What an adapter returns from every operation. */
475
476
  type PaymentResult = {
476
477
  status: PaymentIntentStatus;
477
- /** Amount this result covers, in the order currency. */
478
+ /**
479
+ * Amount this result covers, in the order currency. Kept for
480
+ * compatibility: read `amount_decimal` for money math.
481
+ */
478
482
  amount: number;
483
+ /**
484
+ * Exact decimal text of `amount` (Big.js, never rounded, no exponent),
485
+ * e.g. `"1500"` or `"12.5"`. Build both with `paymentResultAmount`.
486
+ */
487
+ amount_decimal: string;
479
488
  metadata: PaymentMetadata;
480
489
  error?: StandardPaymentError;
481
490
  /** Non-sensitive tender data recorded with the attempt (§3.1). */
@@ -522,6 +531,32 @@ declare const CURRENCY_DECIMALS: Readonly<Record<string, number>>;
522
531
  declare const currencyDecimals: (currency: string) => number;
523
532
  /** Full precision. `decimals` is ignored so amounts are never truncated. */
524
533
  declare const roundTo: (value: number, _decimals: number) => number;
534
+ /** Exact decimal text: plain notation, no exponent, never rounded. */
535
+ declare const amountDecimal: (value: number | string | Money) => string;
536
+ /** `amount` and `amount_decimal` of a `PaymentResult`, from one Big. */
537
+ declare const paymentResultAmount: (value: number | string | Money) => {
538
+ amount: number;
539
+ amount_decimal: string;
540
+ };
541
+ /**
542
+ * Decimal amount of a result. A result saved before `amount_decimal`
543
+ * existed falls back to its `amount`.
544
+ */
545
+ declare const paymentResultDecimal: (result: {
546
+ amount: number;
547
+ amount_decimal?: string | null;
548
+ }) => string;
549
+ /** True when `value` has no fractional part (exact, Big.js). */
550
+ declare const isWholeAmount: (value: number | string | Money) => boolean;
551
+ /** Digits after the decimal point that `value` really has. */
552
+ declare const decimalPlaces: (value: number | string | Money) => number;
553
+ /**
554
+ * `value` with exactly `decimals` digits, for wire formats that need them.
555
+ * Only pads with zeros: more digits than that throws `INVALID_AMOUNT`.
556
+ */
557
+ declare const exactFixed: (value: number | string | Money, decimals: number) => string;
558
+ /** Display text with at least `decimals` digits; never drops one. */
559
+ declare const paddedDecimal: (value: number | string | Money, decimals: number) => string;
525
560
  declare const toPaymentAmount: (value: number, currency: string) => PaymentAmount;
526
561
  type ChargeConversion = {
527
562
  amount: PaymentAmount;
@@ -813,4 +848,4 @@ declare const scopedPaymentStorage: (storage: PaymentStorage, paymentId: string)
813
848
  /** For tests and web previews; apps provide AsyncStorage or localStorage. */
814
849
  declare const memoryPaymentStorage: () => PaymentStorage;
815
850
  //#endregion
816
- export { ACTIVE_INTENT_STATUSES, AllocateTenderInput, AllocateTendersInput, AllocateTendersResult, AllocatedTender, AllocationError, CURRENCY_DECIMALS, ChargeConversion, DEFAULT_PAYMENT_POLICY, DELIVERY_FEE_BASED_ON, DIGITAL_COLLECT_AT, type DeviceField, MANUAL_PAYMENT_METHODS, MergePaymentTenderOutcome, MergePaymentTenderResult, Money, NEXT_STATUSES, PARTIAL_APPROVAL_ERROR, PAYMENT_CHALLENGE_MESSAGE, PAYMENT_ERROR_CODES, PAYMENT_ERROR_DEFAULTS, type PaymentAction, type PaymentAdapter, type PaymentAdapterCapabilities, type PaymentAmount, type PaymentCardType, PaymentChallenge, PaymentChallengeInput, PaymentChallengeMessage, PaymentChallengeResult, type PaymentCollectAt, type PaymentContext, type PaymentCustomer, type PaymentEntryMode, type PaymentEnvironment, PaymentError, PaymentErrorCode, PaymentErrorDictionary, PaymentErrorEntry, PaymentErrorReason, type PaymentIntentStatus, type PaymentMetadata, type PaymentMetadataPayment, type PaymentOperation, type PaymentPolicy, type PaymentResult, type PaymentReversal, type PaymentServer, type PaymentStorage, PaymentTenderUpdate, type PaymentTransient, type PaymentUI, REDEMPTION_METHOD, RawPaymentError, RedeemLike, RedeemSource, RedemptionDetails, RedemptionGroup, RedemptionReward, RulesTender, StandardPaymentError, TERMINAL_TENDER_STATUSES, TIP_FEE_BASED_ON, type TaxBreakdown, TaxLine, type TerminalContext, type TerminalOperation, type TerminalOperations, type TerminalResult, ValidateTendersResult, activeIntent, allocateTenders, batchCloseDay, countTenderItems, createAttemptReference, createPaymentError, currencyDecimals, currentIntent, defaultReversalFor, definePaymentErrors, derivePaymentStatus, formatPaymentError, groupRedeems, hasRedeemPayment, isBatchCloseDue, isDeliveryFee, isIntentCovered, isManualPayment, isMixedTenders, isPaymentError, isProductReward, isRealPaymentMethod, isRedemptionReserved, isScopePaid, isTenderSettled, isTerminalLocked, isTipFee, liveRealTenders, liveTenders, memoryPaymentStorage, mergePaymentTender, missingDeviceFields, money, moneyMax, moneyMin, moneyNumber, moneyNumbers, moneySum, moneyZero, nextIntentStatus, orderRedeems, parsePaymentChallengeMessage, paymentChallengeDocument, primaryTender, primaryTenderOf, prorateMinor, realTenders, redeemsCoverTotal, redemptionDetailsOf, redemptionRewardsOf, resolvePaymentPolicy, resolveProviderEnvironment, roundTo, scopedPaymentStorage, splitMoney, taxBreakdown, tendersCoverage, tendersInScope, toChargeAmount, toPaymentAmount, toPaymentError, validateTendersAgainstRules, withTerminalLock };
851
+ export { ACTIVE_INTENT_STATUSES, AllocateTenderInput, AllocateTendersInput, AllocateTendersResult, AllocatedTender, AllocationError, CURRENCY_DECIMALS, ChargeConversion, DEFAULT_PAYMENT_POLICY, DELIVERY_FEE_BASED_ON, DIGITAL_COLLECT_AT, type DeviceField, MANUAL_PAYMENT_METHODS, MergePaymentTenderOutcome, MergePaymentTenderResult, Money, NEXT_STATUSES, PARTIAL_APPROVAL_ERROR, PAYMENT_CHALLENGE_MESSAGE, PAYMENT_ERROR_CODES, PAYMENT_ERROR_DEFAULTS, type PaymentAction, type PaymentAdapter, type PaymentAdapterCapabilities, type PaymentAmount, type PaymentCardType, PaymentChallenge, PaymentChallengeInput, PaymentChallengeMessage, PaymentChallengeResult, type PaymentCollectAt, type PaymentContext, type PaymentCustomer, type PaymentEntryMode, type PaymentEnvironment, PaymentError, PaymentErrorCode, PaymentErrorDictionary, PaymentErrorEntry, PaymentErrorReason, type PaymentIntentStatus, type PaymentMetadata, type PaymentMetadataPayment, type PaymentOperation, type PaymentPolicy, type PaymentResult, type PaymentReversal, type PaymentServer, type PaymentStorage, PaymentTenderUpdate, type PaymentTransient, type PaymentUI, REDEMPTION_METHOD, RawPaymentError, RedeemLike, RedeemSource, RedemptionDetails, RedemptionGroup, RedemptionReward, RulesTender, StandardPaymentError, TERMINAL_TENDER_STATUSES, TIP_FEE_BASED_ON, type TaxBreakdown, TaxLine, type TerminalContext, type TerminalOperation, type TerminalOperations, type TerminalResult, ValidateTendersResult, activeIntent, allocateTenders, amountDecimal, batchCloseDay, countTenderItems, createAttemptReference, createPaymentError, currencyDecimals, currentIntent, decimalPlaces, defaultReversalFor, definePaymentErrors, derivePaymentStatus, exactFixed, formatPaymentError, groupRedeems, hasRedeemPayment, isBatchCloseDue, isDeliveryFee, isIntentCovered, isManualPayment, isMixedTenders, isPaymentError, isProductReward, isRealPaymentMethod, isRedemptionReserved, isScopePaid, isTenderSettled, isTerminalLocked, isTipFee, isWholeAmount, liveRealTenders, liveTenders, memoryPaymentStorage, mergePaymentTender, missingDeviceFields, money, moneyMax, moneyMin, moneyNumber, moneyNumbers, moneySum, moneyZero, nextIntentStatus, orderRedeems, paddedDecimal, parsePaymentChallengeMessage, paymentChallengeDocument, paymentResultAmount, paymentResultDecimal, primaryTender, primaryTenderOf, prorateMinor, realTenders, redeemsCoverTotal, redemptionDetailsOf, redemptionRewardsOf, resolvePaymentPolicy, resolveProviderEnvironment, roundTo, scopedPaymentStorage, splitMoney, taxBreakdown, tendersCoverage, tendersInScope, toChargeAmount, toPaymentAmount, toPaymentError, validateTendersAgainstRules, withTerminalLock };
package/dist/index.js CHANGED
@@ -979,85 +979,6 @@ const paymentChallengeDocument = (challenge) => {
979
979
  }).join("")}</form>`}<script>document.getElementById("fs-challenge").submit();<\/script></body></html>`;
980
980
  };
981
981
  //#endregion
982
- //#region src/amount.ts
983
- /** ISO 4217 minor units; anything not listed uses 2. */
984
- const CURRENCY_DECIMALS = {
985
- CLP: 0,
986
- PYG: 0,
987
- JPY: 0,
988
- COP: 2,
989
- USD: 2,
990
- BRL: 2,
991
- PEN: 2,
992
- ARS: 2,
993
- VES: 2,
994
- MXN: 2,
995
- EUR: 2
996
- };
997
- const currencyDecimals = (currency) => {
998
- return CURRENCY_DECIMALS[currency.toUpperCase()] ?? 2;
999
- };
1000
- /** Full precision. `decimals` is ignored so amounts are never truncated. */
1001
- const roundTo = (value, _decimals) => {
1002
- return moneyNumber(money(value));
1003
- };
1004
- const toPaymentAmount = (value, currency) => {
1005
- const code = currency.toUpperCase();
1006
- const decimals = currencyDecimals(code);
1007
- const exact = money(value);
1008
- const scale = money(10).pow(decimals);
1009
- const minor = moneyNumber(exact.times(scale));
1010
- return {
1011
- value: moneyNumber(exact),
1012
- minor,
1013
- currency: code,
1014
- decimals
1015
- };
1016
- };
1017
- /** Converts an order-currency value to the charge currency at a fixed rate. */
1018
- const toChargeAmount = (input) => {
1019
- const orderCurrency = input.orderCurrency.toUpperCase();
1020
- const chargeCurrency = (input.chargeCurrency ?? orderCurrency).toUpperCase();
1021
- const same = chargeCurrency === orderCurrency;
1022
- if (!same && !(input.rate && input.rate > 0)) {
1023
- const message = `Missing exchange rate ${orderCurrency}->${chargeCurrency}`;
1024
- throw new Error(message);
1025
- }
1026
- const rate = same ? 1 : input.rate;
1027
- const charged = money(input.value).times(rate);
1028
- const amount = toPaymentAmount(moneyNumber(charged), chargeCurrency);
1029
- return {
1030
- amount,
1031
- charged_amount: amount.value,
1032
- charged_currency: chargeCurrency,
1033
- exchange_rate: rate
1034
- };
1035
- };
1036
- //#endregion
1037
- //#region src/device.ts
1038
- const isEmpty = (value) => {
1039
- return value == null || typeof value === "string" && value.trim() === "";
1040
- };
1041
- const isVisible = (field, settings) => {
1042
- if (!field.visible_if) return true;
1043
- return Object.entries(field.visible_if).every(([key, expected]) => {
1044
- return settings[key] === expected;
1045
- });
1046
- };
1047
- /** Required, visible device fields that are still empty on this device. */
1048
- const missingDeviceFields = (fields, settings) => {
1049
- const values = settings ?? {};
1050
- return (fields ?? []).filter((field) => {
1051
- if (!field.required) return false;
1052
- if (!isVisible(field, values)) return false;
1053
- return isEmpty(values[field.key]);
1054
- });
1055
- };
1056
- /** Default when the adapter has no `reversalFor`. */
1057
- const defaultReversalFor = (result) => {
1058
- return result.status === "PAID" ? "refund" : "cancel";
1059
- };
1060
- //#endregion
1061
982
  //#region src/errors.ts
1062
983
  const declined = (message) => {
1063
984
  return {
@@ -1107,6 +1028,7 @@ const PAYMENT_ERROR_DEFAULTS = {
1107
1028
  BATCH_CLOSE_REQUIRED: provider("Batch close required"),
1108
1029
  INVALID_CREDENTIALS: provider("Invalid payment credentials"),
1109
1030
  INVALID_REQUEST: provider("Invalid payment request"),
1031
+ INVALID_AMOUNT: provider("Invalid payment amount"),
1110
1032
  PROVIDER_UNAVAILABLE: provider("Payment provider unavailable", true),
1111
1033
  NETWORK_ERROR: {
1112
1034
  reason: "network",
@@ -1197,6 +1119,127 @@ const formatPaymentError = (error, providerName) => {
1197
1119
  return `${error.message} (${prefix}${error.provider_code})`;
1198
1120
  };
1199
1121
  //#endregion
1122
+ //#region src/amount.ts
1123
+ /** ISO 4217 minor units; anything not listed uses 2. */
1124
+ const CURRENCY_DECIMALS = {
1125
+ CLP: 0,
1126
+ PYG: 0,
1127
+ JPY: 0,
1128
+ COP: 2,
1129
+ USD: 2,
1130
+ BRL: 2,
1131
+ PEN: 2,
1132
+ ARS: 2,
1133
+ VES: 2,
1134
+ MXN: 2,
1135
+ EUR: 2
1136
+ };
1137
+ const currencyDecimals = (currency) => {
1138
+ return CURRENCY_DECIMALS[currency.toUpperCase()] ?? 2;
1139
+ };
1140
+ /** Full precision. `decimals` is ignored so amounts are never truncated. */
1141
+ const roundTo = (value, _decimals) => {
1142
+ return moneyNumber(money(value));
1143
+ };
1144
+ /** Exact decimal text: plain notation, no exponent, never rounded. */
1145
+ const amountDecimal = (value) => {
1146
+ return money(value).toFixed();
1147
+ };
1148
+ /** `amount` and `amount_decimal` of a `PaymentResult`, from one Big. */
1149
+ const paymentResultAmount = (value) => {
1150
+ const exact = money(value);
1151
+ return {
1152
+ amount: moneyNumber(exact),
1153
+ amount_decimal: exact.toFixed()
1154
+ };
1155
+ };
1156
+ /**
1157
+ * Decimal amount of a result. A result saved before `amount_decimal`
1158
+ * existed falls back to its `amount`.
1159
+ */
1160
+ const paymentResultDecimal = (result) => {
1161
+ return result.amount_decimal ?? amountDecimal(result.amount);
1162
+ };
1163
+ /** True when `value` has no fractional part (exact, Big.js). */
1164
+ const isWholeAmount = (value) => {
1165
+ return money(value).mod(1).eq(0);
1166
+ };
1167
+ /** Digits after the decimal point that `value` really has. */
1168
+ const decimalPlaces = (value) => {
1169
+ const exact = money(value);
1170
+ return Math.max(0, exact.c.length - exact.e - 1);
1171
+ };
1172
+ /**
1173
+ * `value` with exactly `decimals` digits, for wire formats that need them.
1174
+ * Only pads with zeros: more digits than that throws `INVALID_AMOUNT`.
1175
+ */
1176
+ const exactFixed = (value, decimals) => {
1177
+ const exact = money(value);
1178
+ if (decimalPlaces(exact) <= decimals) return exact.toFixed(decimals);
1179
+ throw new PaymentError(createPaymentError("INVALID_AMOUNT", { message: `Amount ${exact.toFixed()} has more than ${decimals} decimals` }));
1180
+ };
1181
+ /** Display text with at least `decimals` digits; never drops one. */
1182
+ const paddedDecimal = (value, decimals) => {
1183
+ const exact = money(value);
1184
+ return exact.toFixed(Math.max(decimals, decimalPlaces(exact)));
1185
+ };
1186
+ const toPaymentAmount = (value, currency) => {
1187
+ const code = currency.toUpperCase();
1188
+ const decimals = currencyDecimals(code);
1189
+ const exact = money(value);
1190
+ const scale = money(10).pow(decimals);
1191
+ const minor = moneyNumber(exact.times(scale));
1192
+ return {
1193
+ value: moneyNumber(exact),
1194
+ minor,
1195
+ currency: code,
1196
+ decimals
1197
+ };
1198
+ };
1199
+ /** Converts an order-currency value to the charge currency at a fixed rate. */
1200
+ const toChargeAmount = (input) => {
1201
+ const orderCurrency = input.orderCurrency.toUpperCase();
1202
+ const chargeCurrency = (input.chargeCurrency ?? orderCurrency).toUpperCase();
1203
+ const same = chargeCurrency === orderCurrency;
1204
+ if (!same && !(input.rate && input.rate > 0)) {
1205
+ const message = `Missing exchange rate ${orderCurrency}->${chargeCurrency}`;
1206
+ throw new Error(message);
1207
+ }
1208
+ const rate = same ? 1 : input.rate;
1209
+ const charged = money(input.value).times(rate);
1210
+ const amount = toPaymentAmount(moneyNumber(charged), chargeCurrency);
1211
+ return {
1212
+ amount,
1213
+ charged_amount: amount.value,
1214
+ charged_currency: chargeCurrency,
1215
+ exchange_rate: rate
1216
+ };
1217
+ };
1218
+ //#endregion
1219
+ //#region src/device.ts
1220
+ const isEmpty = (value) => {
1221
+ return value == null || typeof value === "string" && value.trim() === "";
1222
+ };
1223
+ const isVisible = (field, settings) => {
1224
+ if (!field.visible_if) return true;
1225
+ return Object.entries(field.visible_if).every(([key, expected]) => {
1226
+ return settings[key] === expected;
1227
+ });
1228
+ };
1229
+ /** Required, visible device fields that are still empty on this device. */
1230
+ const missingDeviceFields = (fields, settings) => {
1231
+ const values = settings ?? {};
1232
+ return (fields ?? []).filter((field) => {
1233
+ if (!field.required) return false;
1234
+ if (!isVisible(field, values)) return false;
1235
+ return isEmpty(values[field.key]);
1236
+ });
1237
+ };
1238
+ /** Default when the adapter has no `reversalFor`. */
1239
+ const defaultReversalFor = (result) => {
1240
+ return result.status === "PAID" ? "refund" : "cancel";
1241
+ };
1242
+ //#endregion
1200
1243
  //#region src/policy.ts
1201
1244
  const DEFAULT_PAYMENT_POLICY = {
1202
1245
  timeout_ms: 3e4,
@@ -1486,4 +1529,4 @@ const memoryPaymentStorage = () => {
1486
1529
  };
1487
1530
  };
1488
1531
  //#endregion
1489
- export { ACTIVE_INTENT_STATUSES, CURRENCY_DECIMALS, DEFAULT_PAYMENT_POLICY, DELIVERY_FEE_BASED_ON, DIGITAL_COLLECT_AT, MANUAL_PAYMENT_METHODS, NEXT_STATUSES, PARTIAL_APPROVAL_ERROR, PAYMENT_CHALLENGE_MESSAGE, PAYMENT_ERROR_CODES, PAYMENT_ERROR_DEFAULTS, PaymentError, REDEMPTION_METHOD, TERMINAL_TENDER_STATUSES, TIP_FEE_BASED_ON, activeIntent, allocateTenders, batchCloseDay, countTenderItems, createAttemptReference, createPaymentError, currencyDecimals, currentIntent, defaultReversalFor, definePaymentErrors, derivePaymentStatus, formatPaymentError, groupRedeems, hasRedeemPayment, isBatchCloseDue, isDeliveryFee, isIntentCovered, isManualPayment, isMixedTenders, isPaymentError, isProductReward, isRealPaymentMethod, isRedemptionReserved, isScopePaid, isTenderSettled, isTerminalLocked, isTipFee, liveRealTenders, liveTenders, memoryPaymentStorage, mergePaymentTender, missingDeviceFields, money, moneyMax, moneyMin, moneyNumber, moneyNumbers, moneySum, moneyZero, nextIntentStatus, orderRedeems, parsePaymentChallengeMessage, paymentChallengeDocument, primaryTender, primaryTenderOf, prorateMinor, realTenders, redeemsCoverTotal, redemptionDetailsOf, redemptionRewardsOf, resolvePaymentPolicy, resolveProviderEnvironment, roundTo, scopedPaymentStorage, splitMoney, taxBreakdown, tendersCoverage, tendersInScope, toChargeAmount, toPaymentAmount, toPaymentError, validateTendersAgainstRules, withTerminalLock };
1532
+ export { ACTIVE_INTENT_STATUSES, CURRENCY_DECIMALS, DEFAULT_PAYMENT_POLICY, DELIVERY_FEE_BASED_ON, DIGITAL_COLLECT_AT, MANUAL_PAYMENT_METHODS, NEXT_STATUSES, PARTIAL_APPROVAL_ERROR, PAYMENT_CHALLENGE_MESSAGE, PAYMENT_ERROR_CODES, PAYMENT_ERROR_DEFAULTS, PaymentError, REDEMPTION_METHOD, TERMINAL_TENDER_STATUSES, TIP_FEE_BASED_ON, activeIntent, allocateTenders, amountDecimal, batchCloseDay, countTenderItems, createAttemptReference, createPaymentError, currencyDecimals, currentIntent, decimalPlaces, defaultReversalFor, definePaymentErrors, derivePaymentStatus, exactFixed, formatPaymentError, groupRedeems, hasRedeemPayment, isBatchCloseDue, isDeliveryFee, isIntentCovered, isManualPayment, isMixedTenders, isPaymentError, isProductReward, isRealPaymentMethod, isRedemptionReserved, isScopePaid, isTenderSettled, isTerminalLocked, isTipFee, isWholeAmount, liveRealTenders, liveTenders, memoryPaymentStorage, mergePaymentTender, missingDeviceFields, money, moneyMax, moneyMin, moneyNumber, moneyNumbers, moneySum, moneyZero, nextIntentStatus, orderRedeems, paddedDecimal, parsePaymentChallengeMessage, paymentChallengeDocument, paymentResultAmount, paymentResultDecimal, primaryTender, primaryTenderOf, prorateMinor, realTenders, redeemsCoverTotal, redemptionDetailsOf, redemptionRewardsOf, resolvePaymentPolicy, resolveProviderEnvironment, roundTo, scopedPaymentStorage, splitMoney, taxBreakdown, tendersCoverage, tendersInScope, toChargeAmount, toPaymentAmount, toPaymentError, validateTendersAgainstRules, withTerminalLock };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fire-spark/payments",
3
- "version": "0.24.0",
3
+ "version": "0.26.0",
4
4
  "description": "Fire Spark payments contract: adapters, errors, amounts and policy",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -18,7 +18,7 @@
18
18
  },
19
19
  "dependencies": {
20
20
  "big.js": "6.2.1",
21
- "@fire-spark/types": "^0.24.0"
21
+ "@fire-spark/types": "^0.26.0"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@types/big.js": "6.2.2",