@tallyui/core 5.1.0 → 5.3.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/{chunk-RPBSJ3FB.js → chunk-PQ3DB6CJ.js} +9 -2
- package/dist/index.d.ts +5 -3
- package/dist/index.js +5 -1
- package/dist/{refund-share-Cv_TgE1p.d.ts → refund-share-BnDEtU7J.d.ts} +43 -3
- package/dist/server/index.cjs +25 -8
- package/dist/server/index.d.cts +14 -2
- package/dist/server/index.d.ts +4 -2
- package/dist/server/index.js +17 -7
- package/package.json +1 -1
- package/src/context/connector-context.tsx +5 -0
- package/src/index.ts +2 -1
- package/src/server/batch.ts +6 -1
- package/src/server/fiscal-figures.ts +12 -5
- package/src/server/order-payload-shape.ts +2 -1
- package/src/server/refund-share.ts +12 -3
- package/src/types/commands.ts +3 -1
- package/src/types/connector.ts +24 -0
- package/src/types/orders.ts +6 -0
|
@@ -489,6 +489,13 @@ function roundRatio(n, d, mode = "half_away_from_zero") {
|
|
|
489
489
|
}
|
|
490
490
|
|
|
491
491
|
// src/server/refund-share.ts
|
|
492
|
+
function pricingBase({ totalMinor, taxMinor, soldTotalMinor, soldTaxMinor }) {
|
|
493
|
+
if (soldTotalMinor === void 0 && soldTaxMinor === void 0) return [totalMinor, taxMinor];
|
|
494
|
+
if (soldTotalMinor === void 0 || soldTaxMinor === void 0 || !Number.isSafeInteger(soldTotalMinor) || !Number.isSafeInteger(soldTaxMinor)) {
|
|
495
|
+
throw new RangeError("A line carries both sold figures or neither, as safe integers");
|
|
496
|
+
}
|
|
497
|
+
return [soldTotalMinor, soldTaxMinor];
|
|
498
|
+
}
|
|
492
499
|
function refundableLines(lines, refunds) {
|
|
493
500
|
const earlier = refunds.flatMap((refund) => refund.lines);
|
|
494
501
|
for (const refund of earlier) {
|
|
@@ -499,7 +506,7 @@ function refundableLines(lines, refunds) {
|
|
|
499
506
|
throw new RangeError("Order line values must be safe integers and quantity non-negative");
|
|
500
507
|
}
|
|
501
508
|
const refundedQuantity = earlier.reduce((sum, refund) => refund.orderLineId === line.id ? Math.min(line.quantity, sum + Math.abs(refund.quantity)) : sum, 0);
|
|
502
|
-
const [netMinor, taxMinor] =
|
|
509
|
+
const [netMinor, taxMinor] = pricingBase(line).map((total) => line.quantity === 0 ? 0 : total - Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), "half_up")));
|
|
503
510
|
return {
|
|
504
511
|
orderLineId: line.id,
|
|
505
512
|
refundedQuantity,
|
|
@@ -524,7 +531,7 @@ function priceRefund(lines, refunds, request) {
|
|
|
524
531
|
if (quantity < 1) continue;
|
|
525
532
|
const line = lines[index];
|
|
526
533
|
const refundedQuantity = available[index].refundedQuantity;
|
|
527
|
-
const [netMinor, taxMinor] =
|
|
534
|
+
const [netMinor, taxMinor] = pricingBase(line).map((total) => Number(roundRatio(BigInt(refundedQuantity + quantity) * BigInt(total), BigInt(line.quantity), "half_up")) - Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), "half_up")));
|
|
528
535
|
const totalMinor = netMinor + taxMinor;
|
|
529
536
|
result.lines.push({ orderLineId, quantity, restock });
|
|
530
537
|
result.priced.push({ orderLineId, quantity, netMinor, taxMinor, totalMinor });
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { I as IceServer, D as DisplayAdvertisement, O as OrderFilterField, L as ListOrdersQuery, V as VariantSummary, C as CommandWarning, P as ProductTraits, S as StockReconcileAdapter, a as StockLevel, R as ReplicationAdapter, b as SyncContext, T as TallyConnector, c as TraitContext, d as CustomerTraits, M as MoneyFormat, e as Money, f as CalculateTaxesInput, g as CalculateTaxesResult, W as WooTaxRate, h as ItemizedTax, i as ResolvedTaxLocation, j as TAX_BASED_ON_META_KEY, k as TaxAddress, l as TaxBasedOn, m as TaxLocationOrder, n as normalizeTaxBasedOn, o as orderTaxLocation } from './refund-share-
|
|
2
|
-
export { A as AnyCommandEnvelope, p as ApproverCredentials, q as AuthField, B as BatchTooLargeBody, r as CASHIER_PERMISSIONS, s as COMMANDS_PATH, t as CaptureMode, u as CaptureModeEntry, v as Cashier, w as CashierPermission, x as CatalogueReconcileAdapter, y as CatalogueReconcileEntry, z as ClosureReads, E as CollectionSync, F as CommandBatchRequest, G as CommandBatchResponse, H as CommandEnvelope, J as CommandError, K as CommandResult, N as CommandResultError, Q as CommandServerRefs, U as CommandStatus, X as CommandType, Y as ConnectivityState, Z as ConnectorAuth, _ as ConnectorSchemas, $ as ConnectorTraits, a0 as Correction, a1 as Customer, a2 as CustomerAddress, a3 as CustomerInput, a4 as CustomerPage, a5 as CustomerPatch, a6 as CustomerServiceError, a7 as CustomerTaxId, a8 as DISPLAY_PAIR_CAPABILITY, a9 as DisplayRecord, aa as DisplaySignalling, ab as DisplaySignallingContext, ac as DisplaySignallingError, ad as DisplaySignallingErrorCode, ae as EarlierRefund, af as FailureClass, ag as FingerprintReconcileAdapter, ah as IdReconcileAdapter, ai as ListRefundsQuery, aj as MAX_COMMANDS_PER_BATCH, ak as NEEDS_ADMIN_MESSAGE_MAX, al as ORDER_LINE_SKU_MAX, am as ORDER_META_KEY_MAX, an as ORDER_META_MAX, ao as ORDER_NOTE_MAX, ap as ORDER_TAX_IDS_MAX, aq as ORDER_TAX_ID_TYPE_MAX, ar as ORDER_TAX_ID_VALUE_MAX, as as OrderAddress, at as OrderCreateCoupon, au as OrderCreateCouponInvalidData, av as OrderCreateCouponLine, aw as OrderCreateDisplay, ax as OrderCreateEnvelope, ay as OrderCreateLine, az as OrderCreateMeta, aA as OrderCreatePayload, aB as OrderCreatePayment, aC as OrderCreateTaxId, aD as OrderCreateTaxRate, aE as OrderCreateTotalMismatchData, aF as OrderRefundAmountMismatchData, aG as OrderRefundEnvelope, aH as OrderRefundLine, aI as OrderRefundNoOpenSessionData, aJ as OrderRefundOrderStateData, aK as OrderRefundPayload, aL as OrderRefundQuantityExceedsData, aM as OrderRefundRejectionCode, aN as OrderRefundResult, aO as OrderReopenEnvelope, aP as OrderReopenOrderStateData, aQ as OrderReopenPayload, aR as OrderReopenPaymentInMotionData, aS as OrderReopenRejectionCode, aT as OrderReopenResult, aU as OrderUpdateEnvelope, aV as OrderUpdateFee, aW as OrderUpdateLine, aX as OrderUpdatePayload, aY as OrderUpdatePayment, aZ as OrderUpdateRejectionCode, a_ as OrderUpdateReopenRequiredData, a$ as OrderUpdateShipping, b0 as PROTOCOL_HEADER, b1 as PROTOCOL_VERSION, b2 as PaymentHardware, b3 as PaymentKind, b4 as PaymentMethodDescriptor, b5 as PaymentMethodKind, b6 as PaymentOfflineMode, b7 as PaymentRounding, b8 as PaymentTipsMode, b9 as PaymentTransport, ba as PendingPairing, bb as PricedRefund, bc as PricedRefundLine, bd as ProductCategory, be as ProductPrice, bf as ProductTerm, bg as ReceiptTemplate, bh as ReceiptTemplateKind, bi as RefundableLine, bj as RefundableOrderLine, bk as RefusedOrderSettlement, bl as RegisterApprovalInvalidData, bm as RegisterApprovalRequiredData, bn as RegisterClosureSubmitPayload, bo as RegisterCommandEnvelope, bp as RegisterCommandResult, bq as RegisterCommandType, br as RegisterInfo, bs as RegisterMovementRecordPayload, bt as RegisterMovementVoidPayload, bu as RegisterSessionAlreadyOpenData, bv as RegisterSessionOpenPayload, bw as RegisterSessionSupersededData, bx as RegisterSessionTransitionPayload, by as RemoteIdEntry, bz as ResolvedPrice, bA as RoundingMode, bB as ServerCapabilities, bC as SettleCancelRequest, bD as SettleOutcome, bE as SettlePayRequest, bF as SettlePayResult, bG as SettlePayment, bH as
|
|
1
|
+
import { I as IceServer, D as DisplayAdvertisement, O as OrderFilterField, L as ListOrdersQuery, V as VariantSummary, C as CommandWarning, P as ProductTraits, S as StockReconcileAdapter, a as StockLevel, R as ReplicationAdapter, b as SyncContext, T as TallyConnector, c as TraitContext, d as CustomerTraits, M as MoneyFormat, e as Money, f as CalculateTaxesInput, g as CalculateTaxesResult, W as WooTaxRate, h as ItemizedTax, i as ResolvedTaxLocation, j as TAX_BASED_ON_META_KEY, k as TaxAddress, l as TaxBasedOn, m as TaxLocationOrder, n as normalizeTaxBasedOn, o as orderTaxLocation } from './refund-share-BnDEtU7J.js';
|
|
2
|
+
export { A as AnyCommandEnvelope, p as ApproverCredentials, q as AuthField, B as BatchTooLargeBody, r as CASHIER_PERMISSIONS, s as COMMANDS_PATH, t as CaptureMode, u as CaptureModeEntry, v as Cashier, w as CashierPermission, x as CatalogueReconcileAdapter, y as CatalogueReconcileEntry, z as ClosureReads, E as CollectionSync, F as CommandBatchRequest, G as CommandBatchResponse, H as CommandEnvelope, J as CommandError, K as CommandResult, N as CommandResultError, Q as CommandServerRefs, U as CommandStatus, X as CommandType, Y as ConnectivityState, Z as ConnectorAuth, _ as ConnectorSchemas, $ as ConnectorTraits, a0 as Correction, a1 as Customer, a2 as CustomerAddress, a3 as CustomerInput, a4 as CustomerPage, a5 as CustomerPatch, a6 as CustomerServiceError, a7 as CustomerTaxId, a8 as DISPLAY_PAIR_CAPABILITY, a9 as DisplayRecord, aa as DisplaySignalling, ab as DisplaySignallingContext, ac as DisplaySignallingError, ad as DisplaySignallingErrorCode, ae as EarlierRefund, af as FailureClass, ag as FingerprintReconcileAdapter, ah as IdReconcileAdapter, ai as ListRefundsQuery, aj as MAX_COMMANDS_PER_BATCH, ak as NEEDS_ADMIN_MESSAGE_MAX, al as ORDER_LINE_SKU_MAX, am as ORDER_META_KEY_MAX, an as ORDER_META_MAX, ao as ORDER_NOTE_MAX, ap as ORDER_TAX_IDS_MAX, aq as ORDER_TAX_ID_TYPE_MAX, ar as ORDER_TAX_ID_VALUE_MAX, as as OrderAddress, at as OrderCreateCoupon, au as OrderCreateCouponInvalidData, av as OrderCreateCouponLine, aw as OrderCreateDisplay, ax as OrderCreateEnvelope, ay as OrderCreateLine, az as OrderCreateMeta, aA as OrderCreatePayload, aB as OrderCreatePayment, aC as OrderCreateTaxId, aD as OrderCreateTaxRate, aE as OrderCreateTotalMismatchData, aF as OrderRefundAmountMismatchData, aG as OrderRefundEnvelope, aH as OrderRefundLine, aI as OrderRefundNoOpenSessionData, aJ as OrderRefundOrderStateData, aK as OrderRefundPayload, aL as OrderRefundQuantityExceedsData, aM as OrderRefundRejectionCode, aN as OrderRefundResult, aO as OrderReopenEnvelope, aP as OrderReopenOrderStateData, aQ as OrderReopenPayload, aR as OrderReopenPaymentInMotionData, aS as OrderReopenRejectionCode, aT as OrderReopenResult, aU as OrderUpdateEnvelope, aV as OrderUpdateFee, aW as OrderUpdateLine, aX as OrderUpdatePayload, aY as OrderUpdatePayment, aZ as OrderUpdateRejectionCode, a_ as OrderUpdateReopenRequiredData, a$ as OrderUpdateShipping, b0 as PROTOCOL_HEADER, b1 as PROTOCOL_VERSION, b2 as PaymentHardware, b3 as PaymentKind, b4 as PaymentMethodDescriptor, b5 as PaymentMethodKind, b6 as PaymentOfflineMode, b7 as PaymentRounding, b8 as PaymentTipsMode, b9 as PaymentTransport, ba as PendingPairing, bb as PricedRefund, bc as PricedRefundLine, bd as ProductCategory, be as ProductPrice, bf as ProductTerm, bg as ReceiptTemplate, bh as ReceiptTemplateKind, bi as RefundableLine, bj as RefundableOrderLine, bk as RefusedOrderSettlement, bl as RegisterApprovalInvalidData, bm as RegisterApprovalRequiredData, bn as RegisterClosureSubmitPayload, bo as RegisterCommandEnvelope, bp as RegisterCommandResult, bq as RegisterCommandType, br as RegisterInfo, bs as RegisterMovementRecordPayload, bt as RegisterMovementVoidPayload, bu as RegisterSessionAlreadyOpenData, bv as RegisterSessionOpenPayload, bw as RegisterSessionSupersededData, bx as RegisterSessionTransitionPayload, by as RemoteIdEntry, bz as ResolvedPrice, bA as RoundingMode, bB as ServerCapabilities, bC as SettleCancelRequest, bD as SettleOutcome, bE as SettlePayRequest, bF as SettlePayResult, bG as SettlePayment, bH as SettleReverseLeg, bI as SettleReverseRequest, bJ as SettleReverseResult, bK as SignInResult, bL as SignalMessage, bM as StockStatus, bN as StoreClosure, bO as StoreOrder, bP as StoreOrderCharge, bQ as StoreOrderLine, bR as StoreOrderPage, bS as StoreOrderPayment, bT as StoreOrderRefund, bU as StoreOrderRefundLine, bV as StoreRefund, bW as StoreRefundOrphan, bX as StoreRefundPage, bY as StoreSettings, bZ as StoreSettingsChoice, b_ as StoreTaxClass, b$ as StoreTaxRate, c0 as StoreTaxRateLocation, c1 as TaxRounding, c2 as TillDevice, c3 as UpdateRequired, c4 as VariantOptionGroup, c5 as cashierPermissions, c6 as classifyFailure, c7 as currencySymbol, c8 as customerTraits, c9 as defaultPaymentMethods, ca as deriveSessionFigures, cb as deriveVariance, cc as formatMoney, cd as isCashierPermission, ce as isCommandBatchResponse, cf as legMethodId, cg as minorToMajor, ch as minorUnitDigits, ci as moneyFromDecimalString, cj as moneyFromMajor, ck as moneyToMajor, cl as neutralFailureClass, cm as noResponse, cn as normalizeMoneyText, co as parseCommandResult, cp as parseInfoCapabilities, cq as parseLineTax, cr as parseTaxRounding, cs as paymentMethodOf, ct as priceRefund, cu as ratePpmFromPercent, cv as refundableLines, cw as resolveCapabilities, cx as resolvePrice, cy as resolvePriceRange, cz as roundRatio, cA as wireMethodOf } from './refund-share-BnDEtU7J.js';
|
|
3
3
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
4
4
|
import { ReactNode } from 'react';
|
|
5
5
|
import 'rxdb';
|
|
@@ -301,6 +301,8 @@ declare function ConnectorProvider({ connector, traitContext, stockOverlay, stoc
|
|
|
301
301
|
* Access the active connector. Throws if used outside a ConnectorProvider.
|
|
302
302
|
*/
|
|
303
303
|
declare function useConnector(): TallyConnector;
|
|
304
|
+
/** Returns the active connector, or null without a provider. */
|
|
305
|
+
declare function useOptionalConnector(): TallyConnector | null;
|
|
304
306
|
/**
|
|
305
307
|
* Convenience hook: grab just the product traits from the active connector.
|
|
306
308
|
*/
|
|
@@ -875,4 +877,4 @@ declare namespace index {
|
|
|
875
877
|
export { type index_CouponContext as CouponContext, type index_CouponDiscountConfig as CouponDiscountConfig, type index_CouponInput as CouponInput, type index_CouponLineInput as CouponLineInput, type index_CouponRejection as CouponRejection, type index_CouponRejectionCode as CouponRejectionCode, type index_CouponValidationContext as CouponValidationContext, type index_EngineWarning as EngineWarning, type index_LineItemInput as LineItemInput, type index_OrderTotals as OrderTotals, type index_RecalculateInput as RecalculateInput, type index_RecalculateResult as RecalculateResult, type index_TaxRateInput as TaxRateInput, type index_ValidationResult as ValidationResult, index_calculateOrderTotals as calculateOrderTotals, index_enrichCategoriesWithAncestors as enrichCategoriesWithAncestors, index_recalculateCoupons as recalculateCoupons, index_toCouponConfigs as toCouponConfigs, index_validateCoupon as validateCoupon };
|
|
876
878
|
}
|
|
877
879
|
|
|
878
|
-
export { CommandWarning, ConnectorProvider, type ConnectorProviderProps, ConnectorUnauthorizedError, CustomerTraits, DEFAULT_ICE_SERVERS, DisplayAdvertisement, type ErrorKind, IceServer, type KeyedReconcileFeedOptions, ListOrdersQuery, Money, MoneyFormat, MoneyFormatProvider, type MoneyFormatProviderProps, ORDER_FILTER_FIELDS, OrderFilterField, ProductTraits, type ReconcileFeed, type ReconcileFeedEntry, type ReconcileFetchEntry, ReplicationAdapter, STOCK_LEVELS_LAST_PASS, SignInError, type SignInErrorCode, StockLevel, StockReconcileAdapter, StoreRefundsUnsupportedError, type StoreSettingsChoices, StoreSettingsError, type StoreSettingsErrorCode, SyncContext, type SyncNotice, TallyConnector, TraitContext, UnsupportedOrderFilterError, VariantSummary, assertOrderDateRange, assertOrderFiltersSupported, combinePullAdapters, compareIds, createReconcileFeed, errorKind, findVariantByCode, fnv1a32, getProductStock, isRxdbRemoteVersionMismatch, knownWarnings, orderFilterFields, parseDisplayAdvertisement, rateLimitSource, useConnector, useCurrencySymbol, useCustomerTraits, useFormatMoney, useMoneyFormat, useProductStock, useProductTraits, useStockOverlaid, useStockOverlayAsOf, useTraitContext, withStockOverlay, index as woocommerceCoupons, index$1 as woocommerceTax };
|
|
880
|
+
export { CommandWarning, ConnectorProvider, type ConnectorProviderProps, ConnectorUnauthorizedError, CustomerTraits, DEFAULT_ICE_SERVERS, DisplayAdvertisement, type ErrorKind, IceServer, type KeyedReconcileFeedOptions, ListOrdersQuery, Money, MoneyFormat, MoneyFormatProvider, type MoneyFormatProviderProps, ORDER_FILTER_FIELDS, OrderFilterField, ProductTraits, type ReconcileFeed, type ReconcileFeedEntry, type ReconcileFetchEntry, ReplicationAdapter, STOCK_LEVELS_LAST_PASS, SignInError, type SignInErrorCode, StockLevel, StockReconcileAdapter, StoreRefundsUnsupportedError, type StoreSettingsChoices, StoreSettingsError, type StoreSettingsErrorCode, SyncContext, type SyncNotice, TallyConnector, TraitContext, UnsupportedOrderFilterError, VariantSummary, assertOrderDateRange, assertOrderFiltersSupported, combinePullAdapters, compareIds, createReconcileFeed, errorKind, findVariantByCode, fnv1a32, getProductStock, isRxdbRemoteVersionMismatch, knownWarnings, orderFilterFields, parseDisplayAdvertisement, rateLimitSource, useConnector, useCurrencySymbol, useCustomerTraits, useFormatMoney, useMoneyFormat, useOptionalConnector, useProductStock, useProductTraits, useStockOverlaid, useStockOverlayAsOf, useTraitContext, withStockOverlay, index as woocommerceCoupons, index$1 as woocommerceTax };
|
package/dist/index.js
CHANGED
|
@@ -33,7 +33,7 @@ import {
|
|
|
33
33
|
resolvePrice,
|
|
34
34
|
resolvePriceRange,
|
|
35
35
|
roundRatio
|
|
36
|
-
} from "./chunk-
|
|
36
|
+
} from "./chunk-PQ3DB6CJ.js";
|
|
37
37
|
import {
|
|
38
38
|
__export
|
|
39
39
|
} from "./chunk-MLKGABMK.js";
|
|
@@ -605,6 +605,9 @@ function useConnector() {
|
|
|
605
605
|
}
|
|
606
606
|
return connector;
|
|
607
607
|
}
|
|
608
|
+
function useOptionalConnector() {
|
|
609
|
+
return useContext(ConnectorContext);
|
|
610
|
+
}
|
|
608
611
|
function useProductTraits() {
|
|
609
612
|
const connector = useConnector();
|
|
610
613
|
return connector.traits.product;
|
|
@@ -2038,6 +2041,7 @@ export {
|
|
|
2038
2041
|
useCustomerTraits,
|
|
2039
2042
|
useFormatMoney,
|
|
2040
2043
|
useMoneyFormat,
|
|
2044
|
+
useOptionalConnector,
|
|
2041
2045
|
useProductStock,
|
|
2042
2046
|
useProductTraits,
|
|
2043
2047
|
useStockOverlaid,
|
|
@@ -1177,8 +1177,10 @@ interface OrderCreateFee {
|
|
|
1177
1177
|
clientFeeId: string;
|
|
1178
1178
|
/** Recorded fee title, 1–255 characters. */
|
|
1179
1179
|
name: string;
|
|
1180
|
-
/** Instruction: integer >= 0, gross when pricesIncludeTax, net otherwise; never discounted. */
|
|
1180
|
+
/** Instruction: integer >= 0, gross when its own mode (`amountIncludesTax`, else `pricesIncludeTax`) includes tax, net otherwise; never discounted. */
|
|
1181
1181
|
amountMinor: number;
|
|
1182
|
+
/** Instruction (vendurepos 2.10b): `amountMinor`'s own mode, gross when true and net when false. Absent means `pricesIncludeTax`'s. Sent only to a store whose connector declares `chargeTaxMode`, and only when it differs from `pricesIncludeTax`. */
|
|
1183
|
+
amountIncludesTax?: boolean;
|
|
1182
1184
|
/** Instruction: `none` means no tax on this fee. */
|
|
1183
1185
|
taxStatus: 'taxable' | 'none';
|
|
1184
1186
|
/** Instruction, at most 64 characters; absent means the standard class. */
|
|
@@ -1372,6 +1374,12 @@ interface StoreOrderLine {
|
|
|
1372
1374
|
/** After discounts, excluding tax. */
|
|
1373
1375
|
totalMinor: number;
|
|
1374
1376
|
taxMinor: number;
|
|
1377
|
+
/** The line's total after discounts, excluding tax, as sold, before any return; set by a connector whose live totals shrink on return (connector-medusa at plugin contract 7), absent otherwise. */
|
|
1378
|
+
soldTotalMinor?: number;
|
|
1379
|
+
/** The tax beside `soldTotalMinor`, as sold. Present exactly when it is. */
|
|
1380
|
+
soldTaxMinor?: number;
|
|
1381
|
+
/** The store's returned quantity for the line (requested, received or dismissed returns); absent when the store does not say. Refund pricing does not read it. */
|
|
1382
|
+
returnedQuantity?: number;
|
|
1375
1383
|
}
|
|
1376
1384
|
/** A fee or shipping line: excluding tax, the tax beside it. A fee may be negative.
|
|
1377
1385
|
* `taxMinor` is such that `totalMinor + taxMinor` is the gross rounded once. */
|
|
@@ -2103,6 +2111,8 @@ interface ServerCapabilities {
|
|
|
2103
2111
|
pluginContract?: number;
|
|
2104
2112
|
/** True only when the store's connector carries order.create's `cashRoundings` (ADR-094). Absent: the till never rounds a cash leg, and finalize refuses an order with entries. */
|
|
2105
2113
|
cashRounding?: boolean;
|
|
2114
|
+
/** True only when the store takes a fee's or shipping charge's own tax mode as order.create's `amountIncludesTax` (vendurepos 2.10b). Absent: finalize converts every charge to the order's mode and sends no `amountIncludesTax`. */
|
|
2115
|
+
chargeTaxMode?: boolean;
|
|
2106
2116
|
}
|
|
2107
2117
|
/** #287, ADR-071. `custom`: the till computes as when absent; that server never emits `figures_mismatch` for subtotal or tax. */
|
|
2108
2118
|
type TaxRounding = {
|
|
@@ -2270,6 +2280,22 @@ interface SettlePayResult {
|
|
|
2270
2280
|
outcome: SettleOutcome;
|
|
2271
2281
|
recorded: readonly string[];
|
|
2272
2282
|
}
|
|
2283
|
+
/** One till leg to take off the store order (#1101 slice 4): its store payment id and the void's command id, kept across repeats of an attempt.
|
|
2284
|
+
* `amountMinor` is the till leg's amount in minor units, which the connector checks against the store row. */
|
|
2285
|
+
interface SettleReverseLeg {
|
|
2286
|
+
paymentId: string;
|
|
2287
|
+
commandId: string;
|
|
2288
|
+
amountMinor: number;
|
|
2289
|
+
}
|
|
2290
|
+
/** Void the till's recorded legs on the store order a refused sale left part paid, then cancel it. */
|
|
2291
|
+
interface SettleReverseRequest extends SettleCancelRequest {
|
|
2292
|
+
legs: readonly SettleReverseLeg[];
|
|
2293
|
+
}
|
|
2294
|
+
/** `voided`: the request's payment ids the store holds as voided when the call ends, in request order. */
|
|
2295
|
+
interface SettleReverseResult {
|
|
2296
|
+
outcome: SettleOutcome;
|
|
2297
|
+
voided: readonly string[];
|
|
2298
|
+
}
|
|
2273
2299
|
/** Settlement of an order the store created before it refused the sale. */
|
|
2274
2300
|
interface RefusedOrderSettlement {
|
|
2275
2301
|
cancel?: (context: SyncContext, request: SettleCancelRequest) => Promise<SettleOutcome>;
|
|
@@ -2280,12 +2306,26 @@ interface RefusedOrderSettlement {
|
|
|
2280
2306
|
* means no definite answer: send again with the same `attemptId` and payment ids.
|
|
2281
2307
|
*/
|
|
2282
2308
|
pay?: (context: SyncContext, request: SettlePayRequest) => Promise<SettlePayResult>;
|
|
2309
|
+
/**
|
|
2310
|
+
* No money moves: the cashier hands it back. `voided` lists the legs the store holds as voided when the call ends.
|
|
2311
|
+
* `done`: every leg is voided and the order reads `cancelled`.
|
|
2312
|
+
* `changed`: the store shows money or a status the till does not hold, so nothing more was sent.
|
|
2313
|
+
* `refused`: the store refused this step, or answered in a way that is not a usable ledger answer (as for `cancel` and `pay`).
|
|
2314
|
+
* The order is not cancelled. A refused void always stops the run before any cancel is sent.
|
|
2315
|
+
* `gone`: only from the uuid resolver's 404.
|
|
2316
|
+
* `retry`: no definite answer. Send again with the same `attemptId` and command ids.
|
|
2317
|
+
*/
|
|
2318
|
+
reverse?: (context: SyncContext, request: SettleReverseRequest) => Promise<SettleReverseResult>;
|
|
2283
2319
|
}
|
|
2284
2320
|
/**
|
|
2285
2321
|
* The main connector interface.
|
|
2286
2322
|
* Each backend (WooCommerce, Medusa, Vendure, etc.) implements this.
|
|
2287
2323
|
*/
|
|
2288
2324
|
interface TallyConnector {
|
|
2325
|
+
/** True when the store's live order-line totals shrink as units are returned while `quantity` stays the sold quantity (Medusa). The refund form then refuses a partial refund of a line without `soldTotalMinor`/`soldTaxMinor`. Absent: line totals are as sold. */
|
|
2326
|
+
lineTotalsShrinkOnReturn?: boolean;
|
|
2327
|
+
/** True when the store turns each discounted order line into its own taxed row and rounds each taxed row once (Vendure, ADR-048). The till's rounding tolerance then also counts the order's discounted lines. Absent: discounts are not separate taxed rows. */
|
|
2328
|
+
discountsAreTaxedRows?: boolean;
|
|
2289
2329
|
/** Unique identifier for this connector */
|
|
2290
2330
|
id: string;
|
|
2291
2331
|
/** Human-readable name */
|
|
@@ -2549,7 +2589,7 @@ declare function roundRatio(n: bigint, d: bigint, mode?: RoundingMode): bigint;
|
|
|
2549
2589
|
*/
|
|
2550
2590
|
|
|
2551
2591
|
/** The fields of an order line this needs; a StoreOrderLine fits. */
|
|
2552
|
-
type RefundableOrderLine = Pick<StoreOrderLine, 'id' | 'quantity' | 'totalMinor' | 'taxMinor'>;
|
|
2592
|
+
type RefundableOrderLine = Pick<StoreOrderLine, 'id' | 'quantity' | 'totalMinor' | 'taxMinor' | 'soldTotalMinor' | 'soldTaxMinor'>;
|
|
2553
2593
|
/** Earlier refund lines; negative quantities count by magnitude. */
|
|
2554
2594
|
interface EarlierRefund {
|
|
2555
2595
|
lines: ReadonlyArray<Pick<OrderRefundLine, 'orderLineId' | 'quantity'>>;
|
|
@@ -2591,4 +2631,4 @@ declare function refundableLines(lines: readonly RefundableOrderLine[], refunds:
|
|
|
2591
2631
|
/** Prices requested quantities with cumulative shares, clamping them to what remains refundable. */
|
|
2592
2632
|
declare function priceRefund(lines: readonly RefundableOrderLine[], refunds: readonly EarlierRefund[], request: readonly OrderRefundLine[]): PricedRefund;
|
|
2593
2633
|
|
|
2594
|
-
export { type ConnectorTraits as $, type AnyCommandEnvelope as A, type BatchTooLargeBody as B, type CommandWarning as C, type DisplayAdvertisement as D, type CollectionSync as E, type CommandBatchRequest as F, type CommandBatchResponse as G, type CommandEnvelope as H, type IceServer as I, type CommandError as J, type CommandResult as K, type ListOrdersQuery as L, type MoneyFormat as M, CommandResultError as N, type OrderFilterField as O, type ProductTraits as P, type CommandServerRefs as Q, type ReplicationAdapter as R, type StockReconcileAdapter as S, type TallyConnector as T, type CommandStatus as U, type VariantSummary as V, type WooTaxRate as W, type CommandType as X, type ConnectivityState as Y, type ConnectorAuth as Z, type ConnectorSchemas as _, type StockLevel as a, type OrderUpdateShipping as a$, type Correction as a0, type Customer as a1, type CustomerAddress as a2, type CustomerInput as a3, type CustomerPage as a4, type CustomerPatch as a5, CustomerServiceError as a6, type CustomerTaxId as a7, DISPLAY_PAIR_CAPABILITY as a8, type DisplayRecord as a9, type OrderCreatePayload as aA, type OrderCreatePayment as aB, type OrderCreateTaxId as aC, type OrderCreateTaxRate as aD, type OrderCreateTotalMismatchData as aE, type OrderRefundAmountMismatchData as aF, type OrderRefundEnvelope as aG, type OrderRefundLine as aH, type OrderRefundNoOpenSessionData as aI, type OrderRefundOrderStateData as aJ, type OrderRefundPayload as aK, type OrderRefundQuantityExceedsData as aL, type OrderRefundRejectionCode as aM, type OrderRefundResult as aN, type OrderReopenEnvelope as aO, type OrderReopenOrderStateData as aP, type OrderReopenPayload as aQ, type OrderReopenPaymentInMotionData as aR, type OrderReopenRejectionCode as aS, type OrderReopenResult as aT, type OrderUpdateEnvelope as aU, type OrderUpdateFee as aV, type OrderUpdateLine as aW, type OrderUpdatePayload as aX, type OrderUpdatePayment as aY, type OrderUpdateRejectionCode as aZ, type OrderUpdateReopenRequiredData as a_, type DisplaySignalling as aa, type DisplaySignallingContext as ab, DisplaySignallingError as ac, type DisplaySignallingErrorCode as ad, type EarlierRefund as ae, type FailureClass as af, type FingerprintReconcileAdapter as ag, type IdReconcileAdapter as ah, type ListRefundsQuery as ai, MAX_COMMANDS_PER_BATCH as aj, NEEDS_ADMIN_MESSAGE_MAX as ak, ORDER_LINE_SKU_MAX as al, ORDER_META_KEY_MAX as am, ORDER_META_MAX as an, ORDER_NOTE_MAX as ao, ORDER_TAX_IDS_MAX as ap, ORDER_TAX_ID_TYPE_MAX as aq, ORDER_TAX_ID_VALUE_MAX as ar, type OrderAddress as as, type OrderCreateCoupon as at, type OrderCreateCouponInvalidData as au, type OrderCreateCouponLine as av, type OrderCreateDisplay as aw, type OrderCreateEnvelope as ax, type OrderCreateLine as ay, type OrderCreateMeta as az, type SyncContext as b, type
|
|
2634
|
+
export { type ConnectorTraits as $, type AnyCommandEnvelope as A, type BatchTooLargeBody as B, type CommandWarning as C, type DisplayAdvertisement as D, type CollectionSync as E, type CommandBatchRequest as F, type CommandBatchResponse as G, type CommandEnvelope as H, type IceServer as I, type CommandError as J, type CommandResult as K, type ListOrdersQuery as L, type MoneyFormat as M, CommandResultError as N, type OrderFilterField as O, type ProductTraits as P, type CommandServerRefs as Q, type ReplicationAdapter as R, type StockReconcileAdapter as S, type TallyConnector as T, type CommandStatus as U, type VariantSummary as V, type WooTaxRate as W, type CommandType as X, type ConnectivityState as Y, type ConnectorAuth as Z, type ConnectorSchemas as _, type StockLevel as a, type OrderUpdateShipping as a$, type Correction as a0, type Customer as a1, type CustomerAddress as a2, type CustomerInput as a3, type CustomerPage as a4, type CustomerPatch as a5, CustomerServiceError as a6, type CustomerTaxId as a7, DISPLAY_PAIR_CAPABILITY as a8, type DisplayRecord as a9, type OrderCreatePayload as aA, type OrderCreatePayment as aB, type OrderCreateTaxId as aC, type OrderCreateTaxRate as aD, type OrderCreateTotalMismatchData as aE, type OrderRefundAmountMismatchData as aF, type OrderRefundEnvelope as aG, type OrderRefundLine as aH, type OrderRefundNoOpenSessionData as aI, type OrderRefundOrderStateData as aJ, type OrderRefundPayload as aK, type OrderRefundQuantityExceedsData as aL, type OrderRefundRejectionCode as aM, type OrderRefundResult as aN, type OrderReopenEnvelope as aO, type OrderReopenOrderStateData as aP, type OrderReopenPayload as aQ, type OrderReopenPaymentInMotionData as aR, type OrderReopenRejectionCode as aS, type OrderReopenResult as aT, type OrderUpdateEnvelope as aU, type OrderUpdateFee as aV, type OrderUpdateLine as aW, type OrderUpdatePayload as aX, type OrderUpdatePayment as aY, type OrderUpdateRejectionCode as aZ, type OrderUpdateReopenRequiredData as a_, type DisplaySignalling as aa, type DisplaySignallingContext as ab, DisplaySignallingError as ac, type DisplaySignallingErrorCode as ad, type EarlierRefund as ae, type FailureClass as af, type FingerprintReconcileAdapter as ag, type IdReconcileAdapter as ah, type ListRefundsQuery as ai, MAX_COMMANDS_PER_BATCH as aj, NEEDS_ADMIN_MESSAGE_MAX as ak, ORDER_LINE_SKU_MAX as al, ORDER_META_KEY_MAX as am, ORDER_META_MAX as an, ORDER_NOTE_MAX as ao, ORDER_TAX_IDS_MAX as ap, ORDER_TAX_ID_TYPE_MAX as aq, ORDER_TAX_ID_VALUE_MAX as ar, type OrderAddress as as, type OrderCreateCoupon as at, type OrderCreateCouponInvalidData as au, type OrderCreateCouponLine as av, type OrderCreateDisplay as aw, type OrderCreateEnvelope as ax, type OrderCreateLine as ay, type OrderCreateMeta as az, type SyncContext as b, type StoreTaxRate as b$, PROTOCOL_HEADER as b0, PROTOCOL_VERSION as b1, type PaymentHardware as b2, type PaymentKind as b3, type PaymentMethodDescriptor as b4, type PaymentMethodKind as b5, type PaymentOfflineMode as b6, type PaymentRounding as b7, type PaymentTipsMode as b8, type PaymentTransport as b9, type RoundingMode as bA, type ServerCapabilities as bB, type SettleCancelRequest as bC, type SettleOutcome as bD, type SettlePayRequest as bE, type SettlePayResult as bF, type SettlePayment as bG, type SettleReverseLeg as bH, type SettleReverseRequest as bI, type SettleReverseResult as bJ, type SignInResult as bK, type SignalMessage as bL, type StockStatus as bM, type StoreClosure as bN, type StoreOrder as bO, type StoreOrderCharge as bP, type StoreOrderLine as bQ, type StoreOrderPage as bR, type StoreOrderPayment as bS, type StoreOrderRefund as bT, type StoreOrderRefundLine as bU, type StoreRefund as bV, type StoreRefundOrphan as bW, type StoreRefundPage as bX, type StoreSettings as bY, type StoreSettingsChoice as bZ, type StoreTaxClass as b_, type PendingPairing as ba, type PricedRefund as bb, type PricedRefundLine as bc, type ProductCategory as bd, type ProductPrice as be, type ProductTerm as bf, type ReceiptTemplate as bg, type ReceiptTemplateKind as bh, type RefundableLine as bi, type RefundableOrderLine as bj, type RefusedOrderSettlement as bk, type RegisterApprovalInvalidData as bl, type RegisterApprovalRequiredData as bm, type RegisterClosureSubmitPayload as bn, type RegisterCommandEnvelope as bo, type RegisterCommandResult as bp, type RegisterCommandType as bq, type RegisterInfo as br, type RegisterMovementRecordPayload as bs, type RegisterMovementVoidPayload as bt, type RegisterSessionAlreadyOpenData as bu, type RegisterSessionOpenPayload as bv, type RegisterSessionSupersededData as bw, type RegisterSessionTransitionPayload as bx, type RemoteIdEntry as by, type ResolvedPrice as bz, type TraitContext as c, type StoreTaxRateLocation as c0, type TaxRounding as c1, type TillDevice as c2, type UpdateRequired as c3, type VariantOptionGroup as c4, cashierPermissions as c5, classifyFailure as c6, currencySymbol as c7, customerTraits as c8, defaultPaymentMethods as c9, wireMethodOf as cA, currencyDecimals as cB, majorToMinor as cC, deriveSessionFigures as ca, deriveVariance as cb, formatMoney as cc, isCashierPermission as cd, isCommandBatchResponse as ce, legMethodId as cf, minorToMajor as cg, minorUnitDigits as ch, moneyFromDecimalString as ci, moneyFromMajor as cj, moneyToMajor as ck, neutralFailureClass as cl, noResponse as cm, normalizeMoneyText as cn, parseCommandResult as co, parseInfoCapabilities as cp, parseLineTax as cq, parseTaxRounding as cr, paymentMethodOf as cs, priceRefund as ct, ratePpmFromPercent as cu, refundableLines as cv, resolveCapabilities as cw, resolvePrice as cx, resolvePriceRange as cy, roundRatio as cz, type CustomerTraits as d, type Money as e, type CalculateTaxesInput as f, type CalculateTaxesResult as g, type ItemizedTax as h, type ResolvedTaxLocation as i, TAX_BASED_ON_META_KEY as j, type TaxAddress as k, type TaxBasedOn as l, type TaxLocationOrder as m, normalizeTaxBasedOn as n, orderTaxLocation as o, type ApproverCredentials as p, type AuthField as q, CASHIER_PERMISSIONS as r, COMMANDS_PATH as s, type CaptureMode as t, type CaptureModeEntry as u, type Cashier as v, type CashierPermission as w, type CatalogueReconcileAdapter as x, type CatalogueReconcileEntry as y, type ClosureReads as z };
|
package/dist/server/index.cjs
CHANGED
|
@@ -262,7 +262,7 @@ function payloadShapeErrors(payload) {
|
|
|
262
262
|
if (custom && (!object(entry) || item === void 0)) return;
|
|
263
263
|
check2(object(item), path, "an object");
|
|
264
264
|
if (!object(item)) return;
|
|
265
|
-
const keys = custom ? ["name", "sku", "taxClass", "taxStatus"] : [id, "name", "amountMinor", "taxMinor", "taxStatus", "taxClass", ...field === "shipping" ? ["methodId"] : []];
|
|
265
|
+
const keys = custom ? ["name", "sku", "taxClass", "taxStatus"] : [id, "name", "amountMinor", "amountIncludesTax", "taxMinor", "taxStatus", "taxClass", ...field === "shipping" ? ["methodId"] : []];
|
|
266
266
|
for (const key of Object.keys(item)) check2(keys.includes(key), `${path}.${key}`, "no unknown key");
|
|
267
267
|
check2(typeof item.name === "string" && item.name.length > 0, `${path}.name`, "a non-empty string");
|
|
268
268
|
check2(item.taxStatus === "taxable" || item.taxStatus === "none", `${path}.taxStatus`, "taxable or none");
|
|
@@ -270,6 +270,7 @@ function payloadShapeErrors(payload) {
|
|
|
270
270
|
if (item[key] !== void 0) check2(typeof item[key] === "string", `${path}.${key}`, "a string");
|
|
271
271
|
}
|
|
272
272
|
if (!custom) {
|
|
273
|
+
if (item.amountIncludesTax !== void 0) check2(typeof item.amountIncludesTax === "boolean", `${path}.amountIncludesTax`, "a boolean");
|
|
273
274
|
check2(typeof item[id] === "string" && item[id].length > 0, `${path}.${id}`, "a non-empty string");
|
|
274
275
|
check2(!seen.has(item[id]), `${path}.${id}`, `no duplicate ${id}`);
|
|
275
276
|
seen.add(item[id]);
|
|
@@ -510,9 +511,9 @@ function fiscalFiguresErrors(payload) {
|
|
|
510
511
|
if (payload.fees?.length || payload.shipping?.length) check2(display.taxInclusive === payload.pricesIncludeTax, "display.taxInclusive", "payload.pricesIncludeTax");
|
|
511
512
|
for (const field of ["fees", "shipping"]) {
|
|
512
513
|
const id = field === "fees" ? "clientFeeId" : "clientShippingId";
|
|
513
|
-
const
|
|
514
|
+
const charges = new Map((payload[field] ?? []).map((entry) => [
|
|
514
515
|
"clientFeeId" in entry ? entry.clientFeeId : entry.clientShippingId,
|
|
515
|
-
entry
|
|
516
|
+
entry
|
|
516
517
|
]));
|
|
517
518
|
const rows = display[field];
|
|
518
519
|
if (rows !== void 0) check2(Array.isArray(rows), `display.${field}`, "an array");
|
|
@@ -522,12 +523,18 @@ function fiscalFiguresErrors(payload) {
|
|
|
522
523
|
if (!object(row, path, [id, "amountMinor"])) return;
|
|
523
524
|
check2(typeof row[id] === "string" && row[id].length > 0, `${path}.${id}`, "a non-empty string");
|
|
524
525
|
money(row, path, ["amountMinor"]);
|
|
525
|
-
|
|
526
|
+
const entry = charges.get(row[id]);
|
|
527
|
+
check2(entry !== void 0, `${path}.${id}`, `a payload.${field}[].${id}`);
|
|
526
528
|
check2(!seen3.has(row[id]), `${path}.${id}`, `no duplicate ${id}`);
|
|
527
529
|
seen3.add(row[id]);
|
|
528
|
-
if (
|
|
530
|
+
if (entry) {
|
|
531
|
+
const converted = entry.amountIncludesTax !== void 0 && entry.amountIncludesTax !== payload.pricesIncludeTax;
|
|
532
|
+
const expected = !converted ? entry.amountMinor : entry.amountMinor + (entry.amountIncludesTax ? -entry.taxMinor : entry.taxMinor);
|
|
533
|
+
const matches = converted ? typeof row.amountMinor === "number" && Math.abs(row.amountMinor - expected) <= 1 : row.amountMinor === expected;
|
|
534
|
+
check2(matches, `${path}.amountMinor`, `the payload.${field} amountMinor${converted ? " converted to the display tax mode" : ""}`);
|
|
535
|
+
}
|
|
529
536
|
});
|
|
530
|
-
for (const key of
|
|
537
|
+
for (const key of charges.keys()) check2(seen3.has(key), `display.${field}`, `a row for ${id} ${key}`);
|
|
531
538
|
}
|
|
532
539
|
const codes = new Set((payload.coupons ?? []).map((coupon) => coupon.code));
|
|
533
540
|
const seen2 = /* @__PURE__ */ new Set();
|
|
@@ -966,6 +973,9 @@ function precheckCommand(envelope, supported) {
|
|
|
966
973
|
if (command.payload.cashRoundings !== void 0 && supported.cashRounding !== true) {
|
|
967
974
|
return rejected(command.id, "invalid_payload", "cashRoundings requires the cashRounding capability, which this server does not declare");
|
|
968
975
|
}
|
|
976
|
+
if (supported.chargeTaxMode !== true && [command.payload.fees, command.payload.shipping].some((items) => Array.isArray(items) && items.some((entry) => entry?.amountIncludesTax !== void 0))) {
|
|
977
|
+
return rejected(command.id, "invalid_payload", "amountIncludesTax requires the chargeTaxMode capability, which this server does not declare");
|
|
978
|
+
}
|
|
969
979
|
const { lines, discountMinor } = command.payload;
|
|
970
980
|
const discounted = discountMinor !== void 0 || Array.isArray(lines) && lines.some((line) => line?.discountMinor !== void 0);
|
|
971
981
|
const payload = command.payload;
|
|
@@ -1933,6 +1943,13 @@ function roundRatio(n, d, mode = "half_away_from_zero") {
|
|
|
1933
1943
|
}
|
|
1934
1944
|
|
|
1935
1945
|
// src/server/refund-share.ts
|
|
1946
|
+
function pricingBase({ totalMinor, taxMinor, soldTotalMinor, soldTaxMinor }) {
|
|
1947
|
+
if (soldTotalMinor === void 0 && soldTaxMinor === void 0) return [totalMinor, taxMinor];
|
|
1948
|
+
if (soldTotalMinor === void 0 || soldTaxMinor === void 0 || !Number.isSafeInteger(soldTotalMinor) || !Number.isSafeInteger(soldTaxMinor)) {
|
|
1949
|
+
throw new RangeError("A line carries both sold figures or neither, as safe integers");
|
|
1950
|
+
}
|
|
1951
|
+
return [soldTotalMinor, soldTaxMinor];
|
|
1952
|
+
}
|
|
1936
1953
|
function refundableLines(lines, refunds) {
|
|
1937
1954
|
const earlier = refunds.flatMap((refund) => refund.lines);
|
|
1938
1955
|
for (const refund of earlier) {
|
|
@@ -1943,7 +1960,7 @@ function refundableLines(lines, refunds) {
|
|
|
1943
1960
|
throw new RangeError("Order line values must be safe integers and quantity non-negative");
|
|
1944
1961
|
}
|
|
1945
1962
|
const refundedQuantity = earlier.reduce((sum, refund) => refund.orderLineId === line.id ? Math.min(line.quantity, sum + Math.abs(refund.quantity)) : sum, 0);
|
|
1946
|
-
const [netMinor, taxMinor] =
|
|
1963
|
+
const [netMinor, taxMinor] = pricingBase(line).map((total) => line.quantity === 0 ? 0 : total - Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), "half_up")));
|
|
1947
1964
|
return {
|
|
1948
1965
|
orderLineId: line.id,
|
|
1949
1966
|
refundedQuantity,
|
|
@@ -1968,7 +1985,7 @@ function priceRefund(lines, refunds, request) {
|
|
|
1968
1985
|
if (quantity < 1) continue;
|
|
1969
1986
|
const line = lines[index];
|
|
1970
1987
|
const refundedQuantity = available[index].refundedQuantity;
|
|
1971
|
-
const [netMinor, taxMinor] =
|
|
1988
|
+
const [netMinor, taxMinor] = pricingBase(line).map((total) => Number(roundRatio(BigInt(refundedQuantity + quantity) * BigInt(total), BigInt(line.quantity), "half_up")) - Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), "half_up")));
|
|
1972
1989
|
const totalMinor = netMinor + taxMinor;
|
|
1973
1990
|
result.lines.push({ orderLineId, quantity, restock });
|
|
1974
1991
|
result.priced.push({ orderLineId, quantity, netMinor, taxMinor, totalMinor });
|
package/dist/server/index.d.cts
CHANGED
|
@@ -390,8 +390,10 @@ interface OrderCreateFee {
|
|
|
390
390
|
clientFeeId: string;
|
|
391
391
|
/** Recorded fee title, 1–255 characters. */
|
|
392
392
|
name: string;
|
|
393
|
-
/** Instruction: integer >= 0, gross when pricesIncludeTax, net otherwise; never discounted. */
|
|
393
|
+
/** Instruction: integer >= 0, gross when its own mode (`amountIncludesTax`, else `pricesIncludeTax`) includes tax, net otherwise; never discounted. */
|
|
394
394
|
amountMinor: number;
|
|
395
|
+
/** Instruction (vendurepos 2.10b): `amountMinor`'s own mode, gross when true and net when false. Absent means `pricesIncludeTax`'s. Sent only to a store whose connector declares `chargeTaxMode`, and only when it differs from `pricesIncludeTax`. */
|
|
396
|
+
amountIncludesTax?: boolean;
|
|
395
397
|
/** Instruction: `none` means no tax on this fee. */
|
|
396
398
|
taxStatus: 'taxable' | 'none';
|
|
397
399
|
/** Instruction, at most 64 characters; absent means the standard class. */
|
|
@@ -581,6 +583,12 @@ interface StoreOrderLine {
|
|
|
581
583
|
/** After discounts, excluding tax. */
|
|
582
584
|
totalMinor: number;
|
|
583
585
|
taxMinor: number;
|
|
586
|
+
/** The line's total after discounts, excluding tax, as sold, before any return; set by a connector whose live totals shrink on return (connector-medusa at plugin contract 7), absent otherwise. */
|
|
587
|
+
soldTotalMinor?: number;
|
|
588
|
+
/** The tax beside `soldTotalMinor`, as sold. Present exactly when it is. */
|
|
589
|
+
soldTaxMinor?: number;
|
|
590
|
+
/** The store's returned quantity for the line (requested, received or dismissed returns); absent when the store does not say. Refund pricing does not read it. */
|
|
591
|
+
returnedQuantity?: number;
|
|
584
592
|
}
|
|
585
593
|
|
|
586
594
|
/** One ICE server, in the shape `RTCPeerConnection` takes (ADR-085 d7). */
|
|
@@ -764,6 +772,8 @@ interface ServerCapabilities {
|
|
|
764
772
|
pluginContract?: number;
|
|
765
773
|
/** True only when the store's connector carries order.create's `cashRoundings` (ADR-094). Absent: the till never rounds a cash leg, and finalize refuses an order with entries. */
|
|
766
774
|
cashRounding?: boolean;
|
|
775
|
+
/** True only when the store takes a fee's or shipping charge's own tax mode as order.create's `amountIncludesTax` (vendurepos 2.10b). Absent: finalize converts every charge to the order's mode and sends no `amountIncludesTax`. */
|
|
776
|
+
chargeTaxMode?: boolean;
|
|
767
777
|
}
|
|
768
778
|
/** #287, ADR-071. `custom`: the till computes as when absent; that server never emits `figures_mismatch` for subtotal or tax. */
|
|
769
779
|
type TaxRounding = {
|
|
@@ -884,6 +894,7 @@ declare function validateBatch(body: unknown): {
|
|
|
884
894
|
* `precheckCommand(envelope, { orderCreate: [1, 2, 3], register: [1], orderRefund: [1], orderReopen: [1], orderUpdate: [1] })` (`orderRefund`, `orderReopen` and `orderUpdate` are optional).
|
|
885
895
|
* `cashRounding` is the server's own word too (ADR-094): without `true`, an order.create (or an order.update's create part)
|
|
886
896
|
* carrying `cashRoundings` is refused as `invalid_payload`, never sent on with the field dropped, which would be a wrong total.
|
|
897
|
+
* Likewise, a fee or shipping charge carrying `amountIncludesTax` is refused unless the server declares `chargeTaxMode: true`.
|
|
887
898
|
*/
|
|
888
899
|
declare function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCommandEnvelope, 'id' | 'type' | 'version' | 'payload'>, supported: {
|
|
889
900
|
orderCreate: readonly number[];
|
|
@@ -892,6 +903,7 @@ declare function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCo
|
|
|
892
903
|
orderReopen?: readonly number[];
|
|
893
904
|
orderUpdate?: readonly number[];
|
|
894
905
|
cashRounding?: boolean;
|
|
906
|
+
chargeTaxMode?: boolean;
|
|
895
907
|
}): CommandResult | undefined;
|
|
896
908
|
|
|
897
909
|
/**
|
|
@@ -1098,7 +1110,7 @@ declare function roundRatio(n: bigint, d: bigint, mode?: RoundingMode): bigint;
|
|
|
1098
1110
|
*/
|
|
1099
1111
|
|
|
1100
1112
|
/** The fields of an order line this needs; a StoreOrderLine fits. */
|
|
1101
|
-
type RefundableOrderLine = Pick<StoreOrderLine, 'id' | 'quantity' | 'totalMinor' | 'taxMinor'>;
|
|
1113
|
+
type RefundableOrderLine = Pick<StoreOrderLine, 'id' | 'quantity' | 'totalMinor' | 'taxMinor' | 'soldTotalMinor' | 'soldTaxMinor'>;
|
|
1102
1114
|
/** Earlier refund lines; negative quantities count by magnitude. */
|
|
1103
1115
|
interface EarlierRefund {
|
|
1104
1116
|
lines: ReadonlyArray<Pick<OrderRefundLine, 'orderLineId' | 'quantity'>>;
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { J as CommandError, aA as OrderCreatePayload, H as CommandEnvelope, bo as RegisterCommandEnvelope, A as AnyCommandEnvelope, K as CommandResult, B as BatchTooLargeBody, G as CommandBatchResponse, C as CommandWarning, bp as RegisterCommandResult, aM as OrderRefundRejectionCode, aS as OrderReopenRejectionCode, aZ as OrderUpdateRejectionCode, aa as DisplaySignalling, b as SyncContext, ab as DisplaySignallingContext } from '../refund-share-
|
|
2
|
-
export { N as CommandResultError, ae as EarlierRefund, aj as MAX_COMMANDS_PER_BATCH, ak as NEEDS_ADMIN_MESSAGE_MAX, ao as ORDER_NOTE_MAX, aw as OrderCreateDisplay, aD as OrderCreateTaxRate, bb as PricedRefund, bc as PricedRefundLine, bi as RefundableLine, bj as RefundableOrderLine, bA as RoundingMode,
|
|
1
|
+
import { J as CommandError, aA as OrderCreatePayload, H as CommandEnvelope, bo as RegisterCommandEnvelope, A as AnyCommandEnvelope, K as CommandResult, B as BatchTooLargeBody, G as CommandBatchResponse, C as CommandWarning, bp as RegisterCommandResult, aM as OrderRefundRejectionCode, aS as OrderReopenRejectionCode, aZ as OrderUpdateRejectionCode, aa as DisplaySignalling, b as SyncContext, ab as DisplaySignallingContext } from '../refund-share-BnDEtU7J.js';
|
|
2
|
+
export { N as CommandResultError, ae as EarlierRefund, aj as MAX_COMMANDS_PER_BATCH, ak as NEEDS_ADMIN_MESSAGE_MAX, ao as ORDER_NOTE_MAX, aw as OrderCreateDisplay, aD as OrderCreateTaxRate, bb as PricedRefund, bc as PricedRefundLine, bi as RefundableLine, bj as RefundableOrderLine, bA as RoundingMode, cB as currencyDecimals, ca as deriveSessionFigures, cb as deriveVariance, cC as majorToMinor, cg as minorToMajor, ch as minorUnitDigits, co as parseCommandResult, ct as priceRefund, cu as ratePpmFromPercent, cv as refundableLines, cz as roundRatio } from '../refund-share-BnDEtU7J.js';
|
|
3
3
|
import 'rxdb';
|
|
4
4
|
import 'rxjs';
|
|
5
5
|
|
|
@@ -112,6 +112,7 @@ declare function validateBatch(body: unknown): {
|
|
|
112
112
|
* `precheckCommand(envelope, { orderCreate: [1, 2, 3], register: [1], orderRefund: [1], orderReopen: [1], orderUpdate: [1] })` (`orderRefund`, `orderReopen` and `orderUpdate` are optional).
|
|
113
113
|
* `cashRounding` is the server's own word too (ADR-094): without `true`, an order.create (or an order.update's create part)
|
|
114
114
|
* carrying `cashRoundings` is refused as `invalid_payload`, never sent on with the field dropped, which would be a wrong total.
|
|
115
|
+
* Likewise, a fee or shipping charge carrying `amountIncludesTax` is refused unless the server declares `chargeTaxMode: true`.
|
|
115
116
|
*/
|
|
116
117
|
declare function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCommandEnvelope, 'id' | 'type' | 'version' | 'payload'>, supported: {
|
|
117
118
|
orderCreate: readonly number[];
|
|
@@ -120,6 +121,7 @@ declare function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCo
|
|
|
120
121
|
orderReopen?: readonly number[];
|
|
121
122
|
orderUpdate?: readonly number[];
|
|
122
123
|
cashRounding?: boolean;
|
|
124
|
+
chargeTaxMode?: boolean;
|
|
123
125
|
}): CommandResult | undefined;
|
|
124
126
|
|
|
125
127
|
/**
|
package/dist/server/index.js
CHANGED
|
@@ -23,7 +23,7 @@ import {
|
|
|
23
23
|
ratePpmFromPercent,
|
|
24
24
|
refundableLines,
|
|
25
25
|
roundRatio
|
|
26
|
-
} from "../chunk-
|
|
26
|
+
} from "../chunk-PQ3DB6CJ.js";
|
|
27
27
|
import "../chunk-MLKGABMK.js";
|
|
28
28
|
|
|
29
29
|
// src/server/fingerprint.ts
|
|
@@ -156,7 +156,7 @@ function payloadShapeErrors(payload) {
|
|
|
156
156
|
if (custom && (!object(entry) || item === void 0)) return;
|
|
157
157
|
check2(object(item), path, "an object");
|
|
158
158
|
if (!object(item)) return;
|
|
159
|
-
const keys = custom ? ["name", "sku", "taxClass", "taxStatus"] : [id, "name", "amountMinor", "taxMinor", "taxStatus", "taxClass", ...field === "shipping" ? ["methodId"] : []];
|
|
159
|
+
const keys = custom ? ["name", "sku", "taxClass", "taxStatus"] : [id, "name", "amountMinor", "amountIncludesTax", "taxMinor", "taxStatus", "taxClass", ...field === "shipping" ? ["methodId"] : []];
|
|
160
160
|
for (const key of Object.keys(item)) check2(keys.includes(key), `${path}.${key}`, "no unknown key");
|
|
161
161
|
check2(typeof item.name === "string" && item.name.length > 0, `${path}.name`, "a non-empty string");
|
|
162
162
|
check2(item.taxStatus === "taxable" || item.taxStatus === "none", `${path}.taxStatus`, "taxable or none");
|
|
@@ -164,6 +164,7 @@ function payloadShapeErrors(payload) {
|
|
|
164
164
|
if (item[key] !== void 0) check2(typeof item[key] === "string", `${path}.${key}`, "a string");
|
|
165
165
|
}
|
|
166
166
|
if (!custom) {
|
|
167
|
+
if (item.amountIncludesTax !== void 0) check2(typeof item.amountIncludesTax === "boolean", `${path}.amountIncludesTax`, "a boolean");
|
|
167
168
|
check2(typeof item[id] === "string" && item[id].length > 0, `${path}.${id}`, "a non-empty string");
|
|
168
169
|
check2(!seen.has(item[id]), `${path}.${id}`, `no duplicate ${id}`);
|
|
169
170
|
seen.add(item[id]);
|
|
@@ -404,9 +405,9 @@ function fiscalFiguresErrors(payload) {
|
|
|
404
405
|
if (payload.fees?.length || payload.shipping?.length) check2(display.taxInclusive === payload.pricesIncludeTax, "display.taxInclusive", "payload.pricesIncludeTax");
|
|
405
406
|
for (const field of ["fees", "shipping"]) {
|
|
406
407
|
const id = field === "fees" ? "clientFeeId" : "clientShippingId";
|
|
407
|
-
const
|
|
408
|
+
const charges = new Map((payload[field] ?? []).map((entry) => [
|
|
408
409
|
"clientFeeId" in entry ? entry.clientFeeId : entry.clientShippingId,
|
|
409
|
-
entry
|
|
410
|
+
entry
|
|
410
411
|
]));
|
|
411
412
|
const rows = display[field];
|
|
412
413
|
if (rows !== void 0) check2(Array.isArray(rows), `display.${field}`, "an array");
|
|
@@ -416,12 +417,18 @@ function fiscalFiguresErrors(payload) {
|
|
|
416
417
|
if (!object(row, path, [id, "amountMinor"])) return;
|
|
417
418
|
check2(typeof row[id] === "string" && row[id].length > 0, `${path}.${id}`, "a non-empty string");
|
|
418
419
|
money(row, path, ["amountMinor"]);
|
|
419
|
-
|
|
420
|
+
const entry = charges.get(row[id]);
|
|
421
|
+
check2(entry !== void 0, `${path}.${id}`, `a payload.${field}[].${id}`);
|
|
420
422
|
check2(!seen3.has(row[id]), `${path}.${id}`, `no duplicate ${id}`);
|
|
421
423
|
seen3.add(row[id]);
|
|
422
|
-
if (
|
|
424
|
+
if (entry) {
|
|
425
|
+
const converted = entry.amountIncludesTax !== void 0 && entry.amountIncludesTax !== payload.pricesIncludeTax;
|
|
426
|
+
const expected = !converted ? entry.amountMinor : entry.amountMinor + (entry.amountIncludesTax ? -entry.taxMinor : entry.taxMinor);
|
|
427
|
+
const matches = converted ? typeof row.amountMinor === "number" && Math.abs(row.amountMinor - expected) <= 1 : row.amountMinor === expected;
|
|
428
|
+
check2(matches, `${path}.amountMinor`, `the payload.${field} amountMinor${converted ? " converted to the display tax mode" : ""}`);
|
|
429
|
+
}
|
|
423
430
|
});
|
|
424
|
-
for (const key of
|
|
431
|
+
for (const key of charges.keys()) check2(seen3.has(key), `display.${field}`, `a row for ${id} ${key}`);
|
|
425
432
|
}
|
|
426
433
|
const codes = new Set((payload.coupons ?? []).map((coupon) => coupon.code));
|
|
427
434
|
const seen2 = /* @__PURE__ */ new Set();
|
|
@@ -860,6 +867,9 @@ function precheckCommand(envelope, supported) {
|
|
|
860
867
|
if (command.payload.cashRoundings !== void 0 && supported.cashRounding !== true) {
|
|
861
868
|
return rejected(command.id, "invalid_payload", "cashRoundings requires the cashRounding capability, which this server does not declare");
|
|
862
869
|
}
|
|
870
|
+
if (supported.chargeTaxMode !== true && [command.payload.fees, command.payload.shipping].some((items) => Array.isArray(items) && items.some((entry) => entry?.amountIncludesTax !== void 0))) {
|
|
871
|
+
return rejected(command.id, "invalid_payload", "amountIncludesTax requires the chargeTaxMode capability, which this server does not declare");
|
|
872
|
+
}
|
|
863
873
|
const { lines, discountMinor } = command.payload;
|
|
864
874
|
const discounted = discountMinor !== void 0 || Array.isArray(lines) && lines.some((line) => line?.discountMinor !== void 0);
|
|
865
875
|
const payload = command.payload;
|
package/package.json
CHANGED
|
@@ -59,6 +59,11 @@ export function useConnector(): TallyConnector {
|
|
|
59
59
|
return connector;
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
+
/** Returns the active connector, or null without a provider. */
|
|
63
|
+
export function useOptionalConnector(): TallyConnector | null {
|
|
64
|
+
return useContext(ConnectorContext);
|
|
65
|
+
}
|
|
66
|
+
|
|
62
67
|
/**
|
|
63
68
|
* Convenience hook: grab just the product traits from the active connector.
|
|
64
69
|
*/
|
package/src/index.ts
CHANGED
|
@@ -30,7 +30,7 @@ export type {
|
|
|
30
30
|
StoreTaxRate,
|
|
31
31
|
StoreTaxRateLocation,
|
|
32
32
|
} from './types';
|
|
33
|
-
export type { SignInResult, ServerCapabilities, TaxRounding, SettleOutcome, SettleCancelRequest, SettlePayment, SettlePayRequest, SettlePayResult, RefusedOrderSettlement } from './types/connector';
|
|
33
|
+
export type { SignInResult, ServerCapabilities, TaxRounding, SettleOutcome, SettleCancelRequest, SettlePayment, SettlePayRequest, SettlePayResult, SettleReverseLeg, SettleReverseRequest, SettleReverseResult, RefusedOrderSettlement } from './types/connector';
|
|
34
34
|
export type {
|
|
35
35
|
DisplaySignalling, DisplaySignallingContext, DisplaySignallingErrorCode, DisplayAdvertisement, IceServer,
|
|
36
36
|
PendingPairing, DisplayRecord, SignalMessage, TillDevice,
|
|
@@ -105,6 +105,7 @@ export type { ReconcileFeed, ReconcileFeedEntry, ReconcileFetchEntry, KeyedRecon
|
|
|
105
105
|
export {
|
|
106
106
|
ConnectorProvider,
|
|
107
107
|
useConnector,
|
|
108
|
+
useOptionalConnector,
|
|
108
109
|
useProductTraits,
|
|
109
110
|
useCustomerTraits,
|
|
110
111
|
useTraitContext,
|
package/src/server/batch.ts
CHANGED
|
@@ -89,9 +89,10 @@ function unsupportedOptional(envelope: { id: string; type: string; version: numb
|
|
|
89
89
|
* `precheckCommand(envelope, { orderCreate: [1, 2, 3], register: [1], orderRefund: [1], orderReopen: [1], orderUpdate: [1] })` (`orderRefund`, `orderReopen` and `orderUpdate` are optional).
|
|
90
90
|
* `cashRounding` is the server's own word too (ADR-094): without `true`, an order.create (or an order.update's create part)
|
|
91
91
|
* carrying `cashRoundings` is refused as `invalid_payload`, never sent on with the field dropped, which would be a wrong total.
|
|
92
|
+
* Likewise, a fee or shipping charge carrying `amountIncludesTax` is refused unless the server declares `chargeTaxMode: true`.
|
|
92
93
|
*/
|
|
93
94
|
export function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCommandEnvelope, 'id' | 'type' | 'version' | 'payload'>,
|
|
94
|
-
supported: { orderCreate: readonly number[]; register: readonly number[]; orderRefund?: readonly number[]; orderReopen?: readonly number[]; orderUpdate?: readonly number[]; cashRounding?: boolean }): CommandResult | undefined {
|
|
95
|
+
supported: { orderCreate: readonly number[]; register: readonly number[]; orderRefund?: readonly number[]; orderReopen?: readonly number[]; orderUpdate?: readonly number[]; cashRounding?: boolean; chargeTaxMode?: boolean }): CommandResult | undefined {
|
|
95
96
|
// An empty list would send Math.max() of nothing (-Infinity, null in JSON) as the server's version.
|
|
96
97
|
for (const key of ['orderCreate', 'register'] as const) {
|
|
97
98
|
if (!supported[key]?.length) throw new TypeError(`precheckCommand: supported.${key} must list at least one version`)
|
|
@@ -131,6 +132,10 @@ export function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCom
|
|
|
131
132
|
if ((command.payload as { cashRoundings?: unknown }).cashRoundings !== undefined && supported.cashRounding !== true) {
|
|
132
133
|
return rejected(command.id, 'invalid_payload', 'cashRoundings requires the cashRounding capability, which this server does not declare')
|
|
133
134
|
}
|
|
135
|
+
if (supported.chargeTaxMode !== true && [command.payload.fees, command.payload.shipping].some(items =>
|
|
136
|
+
Array.isArray(items) && items.some(entry => entry?.amountIncludesTax !== undefined))) {
|
|
137
|
+
return rejected(command.id, 'invalid_payload', 'amountIncludesTax requires the chargeTaxMode capability, which this server does not declare')
|
|
138
|
+
}
|
|
134
139
|
// ADR-062 sends version 2 exactly when there is a discount, so version 1 can never create adjustments.
|
|
135
140
|
const { lines, discountMinor } = command.payload as { lines?: unknown; discountMinor?: unknown }
|
|
136
141
|
const discounted = discountMinor !== undefined
|
|
@@ -45,8 +45,8 @@ export function fiscalFiguresErrors(payload: OrderCreatePayload): string[] {
|
|
|
45
45
|
if (payload.fees?.length || payload.shipping?.length) check(display.taxInclusive === payload.pricesIncludeTax, 'display.taxInclusive', 'payload.pricesIncludeTax')
|
|
46
46
|
for (const field of ['fees', 'shipping'] as const) {
|
|
47
47
|
const id = field === 'fees' ? 'clientFeeId' : 'clientShippingId'
|
|
48
|
-
const
|
|
49
|
-
'clientFeeId' in entry ? entry.clientFeeId : entry.clientShippingId, entry
|
|
48
|
+
const charges = new Map((payload[field] ?? []).map(entry => [
|
|
49
|
+
'clientFeeId' in entry ? entry.clientFeeId : entry.clientShippingId, entry,
|
|
50
50
|
]))
|
|
51
51
|
const rows = display[field]
|
|
52
52
|
if (rows !== undefined) check(Array.isArray(rows), `display.${field}`, 'an array')
|
|
@@ -56,12 +56,19 @@ export function fiscalFiguresErrors(payload: OrderCreatePayload): string[] {
|
|
|
56
56
|
if (!object(row, path, [id, 'amountMinor'])) return
|
|
57
57
|
check(typeof row[id] === 'string' && row[id].length > 0, `${path}.${id}`, 'a non-empty string')
|
|
58
58
|
money(row, path, ['amountMinor'])
|
|
59
|
-
|
|
59
|
+
const entry = charges.get(row[id] as string)
|
|
60
|
+
check(entry !== undefined, `${path}.${id}`, `a payload.${field}[].${id}`)
|
|
60
61
|
check(!seen.has(row[id]), `${path}.${id}`, `no duplicate ${id}`)
|
|
61
62
|
seen.add(row[id])
|
|
62
|
-
if (
|
|
63
|
+
if (entry) {
|
|
64
|
+
// #1383: the display row stays in display mode, the wire charge is in its own mode, and a converted row may carry the till's one-cent display residue (order-builder.ts).
|
|
65
|
+
const converted = entry.amountIncludesTax !== undefined && entry.amountIncludesTax !== payload.pricesIncludeTax
|
|
66
|
+
const expected = !converted ? entry.amountMinor : entry.amountMinor + (entry.amountIncludesTax ? -entry.taxMinor : entry.taxMinor)
|
|
67
|
+
const matches = converted ? typeof row.amountMinor === 'number' && Math.abs(row.amountMinor - expected) <= 1 : row.amountMinor === expected
|
|
68
|
+
check(matches, `${path}.amountMinor`, `the payload.${field} amountMinor${converted ? ' converted to the display tax mode' : ''}`)
|
|
69
|
+
}
|
|
63
70
|
})
|
|
64
|
-
for (const key of
|
|
71
|
+
for (const key of charges.keys()) check(seen.has(key), `display.${field}`, `a row for ${id} ${key}`)
|
|
65
72
|
}
|
|
66
73
|
const codes = new Set((payload.coupons ?? []).map(coupon => coupon.code))
|
|
67
74
|
const seen = new Set<string>()
|
|
@@ -124,7 +124,7 @@ export function payloadShapeErrors(payload: unknown): string[] {
|
|
|
124
124
|
check(object(item), path, 'an object')
|
|
125
125
|
if (!object(item)) return
|
|
126
126
|
const keys = custom ? ['name', 'sku', 'taxClass', 'taxStatus']
|
|
127
|
-
: [id, 'name', 'amountMinor', 'taxMinor', 'taxStatus', 'taxClass', ...(field === 'shipping' ? ['methodId'] : [])]
|
|
127
|
+
: [id, 'name', 'amountMinor', 'amountIncludesTax', 'taxMinor', 'taxStatus', 'taxClass', ...(field === 'shipping' ? ['methodId'] : [])]
|
|
128
128
|
for (const key of Object.keys(item)) check(keys.includes(key), `${path}.${key}`, 'no unknown key')
|
|
129
129
|
check(typeof item.name === 'string' && item.name.length > 0, `${path}.name`, 'a non-empty string')
|
|
130
130
|
check(item.taxStatus === 'taxable' || item.taxStatus === 'none', `${path}.taxStatus`, 'taxable or none')
|
|
@@ -132,6 +132,7 @@ export function payloadShapeErrors(payload: unknown): string[] {
|
|
|
132
132
|
if (item[key] !== undefined) check(typeof item[key] === 'string', `${path}.${key}`, 'a string')
|
|
133
133
|
}
|
|
134
134
|
if (!custom) {
|
|
135
|
+
if (item.amountIncludesTax !== undefined) check(typeof item.amountIncludesTax === 'boolean', `${path}.amountIncludesTax`, 'a boolean')
|
|
135
136
|
check(typeof item[id] === 'string' && item[id].length > 0, `${path}.${id}`, 'a non-empty string')
|
|
136
137
|
check(!seen.has(item[id]), `${path}.${id}`, `no duplicate ${id}`)
|
|
137
138
|
seen.add(item[id])
|
|
@@ -7,7 +7,7 @@ import type { StoreOrderLine } from '../types/orders'
|
|
|
7
7
|
import { roundRatio } from './round-ratio'
|
|
8
8
|
|
|
9
9
|
/** The fields of an order line this needs; a StoreOrderLine fits. */
|
|
10
|
-
export type RefundableOrderLine = Pick<StoreOrderLine, 'id' | 'quantity' | 'totalMinor' | 'taxMinor'>;
|
|
10
|
+
export type RefundableOrderLine = Pick<StoreOrderLine, 'id' | 'quantity' | 'totalMinor' | 'taxMinor' | 'soldTotalMinor' | 'soldTaxMinor'>;
|
|
11
11
|
/** Earlier refund lines; negative quantities count by magnitude. */
|
|
12
12
|
export interface EarlierRefund { lines: ReadonlyArray<Pick<OrderRefundLine, 'orderLineId' | 'quantity'>> }
|
|
13
13
|
|
|
@@ -37,6 +37,15 @@ export interface PricedRefund {
|
|
|
37
37
|
netMinor: number; taxMinor: number; totalMinor: number;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
+
// Sold figures win when present: a store whose live line totals shrink on return still prices from the sale (medusapos#636).
|
|
41
|
+
function pricingBase({ totalMinor, taxMinor, soldTotalMinor, soldTaxMinor }: RefundableOrderLine): [number, number] {
|
|
42
|
+
if (soldTotalMinor === undefined && soldTaxMinor === undefined) return [totalMinor, taxMinor];
|
|
43
|
+
if (soldTotalMinor === undefined || soldTaxMinor === undefined || !Number.isSafeInteger(soldTotalMinor) || !Number.isSafeInteger(soldTaxMinor)) {
|
|
44
|
+
throw new RangeError('A line carries both sold figures or neither, as safe integers');
|
|
45
|
+
}
|
|
46
|
+
return [soldTotalMinor, soldTaxMinor];
|
|
47
|
+
}
|
|
48
|
+
|
|
40
49
|
/** Returns the quantities and amounts still refundable, in order-line order. */
|
|
41
50
|
export function refundableLines(
|
|
42
51
|
lines: readonly RefundableOrderLine[], refunds: readonly EarlierRefund[],
|
|
@@ -52,7 +61,7 @@ export function refundableLines(
|
|
|
52
61
|
}
|
|
53
62
|
const refundedQuantity = earlier.reduce((sum, refund) => refund.orderLineId === line.id
|
|
54
63
|
? Math.min(line.quantity, sum + Math.abs(refund.quantity)) : sum, 0);
|
|
55
|
-
const [netMinor, taxMinor] =
|
|
64
|
+
const [netMinor, taxMinor] = pricingBase(line).map((total) => line.quantity === 0 ? 0
|
|
56
65
|
: total - Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), 'half_up')));
|
|
57
66
|
return {
|
|
58
67
|
orderLineId: line.id, refundedQuantity, refundableQuantity: line.quantity - refundedQuantity, netMinor, taxMinor,
|
|
@@ -78,7 +87,7 @@ export function priceRefund(
|
|
|
78
87
|
if (quantity < 1) continue;
|
|
79
88
|
const line = lines[index];
|
|
80
89
|
const refundedQuantity = available[index].refundedQuantity;
|
|
81
|
-
const [netMinor, taxMinor] =
|
|
90
|
+
const [netMinor, taxMinor] = pricingBase(line).map((total) =>
|
|
82
91
|
Number(roundRatio(BigInt(refundedQuantity + quantity) * BigInt(total), BigInt(line.quantity), 'half_up'))
|
|
83
92
|
- Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), 'half_up')));
|
|
84
93
|
const totalMinor = netMinor + taxMinor;
|
package/src/types/commands.ts
CHANGED
|
@@ -356,8 +356,10 @@ export interface OrderCreateFee {
|
|
|
356
356
|
clientFeeId: string;
|
|
357
357
|
/** Recorded fee title, 1–255 characters. */
|
|
358
358
|
name: string;
|
|
359
|
-
/** Instruction: integer >= 0, gross when pricesIncludeTax, net otherwise; never discounted. */
|
|
359
|
+
/** Instruction: integer >= 0, gross when its own mode (`amountIncludesTax`, else `pricesIncludeTax`) includes tax, net otherwise; never discounted. */
|
|
360
360
|
amountMinor: number;
|
|
361
|
+
/** Instruction (vendurepos 2.10b): `amountMinor`'s own mode, gross when true and net when false. Absent means `pricesIncludeTax`'s. Sent only to a store whose connector declares `chargeTaxMode`, and only when it differs from `pricesIncludeTax`. */
|
|
362
|
+
amountIncludesTax?: boolean;
|
|
361
363
|
/** Instruction: `none` means no tax on this fee. */
|
|
362
364
|
taxStatus: 'taxable' | 'none';
|
|
363
365
|
/** Instruction, at most 64 characters; absent means the standard class. */
|
package/src/types/connector.ts
CHANGED
|
@@ -92,6 +92,8 @@ export interface ServerCapabilities {
|
|
|
92
92
|
pluginContract?: number;
|
|
93
93
|
/** True only when the store's connector carries order.create's `cashRoundings` (ADR-094). Absent: the till never rounds a cash leg, and finalize refuses an order with entries. */
|
|
94
94
|
cashRounding?: boolean;
|
|
95
|
+
/** True only when the store takes a fee's or shipping charge's own tax mode as order.create's `amountIncludesTax` (vendurepos 2.10b). Absent: finalize converts every charge to the order's mode and sends no `amountIncludesTax`. */
|
|
96
|
+
chargeTaxMode?: boolean;
|
|
95
97
|
}
|
|
96
98
|
|
|
97
99
|
/** #287, ADR-071. `custom`: the till computes as when absent; that server never emits `figures_mismatch` for subtotal or tax. */
|
|
@@ -317,6 +319,14 @@ export interface SettlePayRequest extends SettleCancelRequest { currency: string
|
|
|
317
319
|
/** `recorded`: the ids in `payments` the store holds as captured when the call ends, in request order. */
|
|
318
320
|
export interface SettlePayResult { outcome: SettleOutcome; recorded: readonly string[] }
|
|
319
321
|
|
|
322
|
+
/** One till leg to take off the store order (#1101 slice 4): its store payment id and the void's command id, kept across repeats of an attempt.
|
|
323
|
+
* `amountMinor` is the till leg's amount in minor units, which the connector checks against the store row. */
|
|
324
|
+
export interface SettleReverseLeg { paymentId: string; commandId: string; amountMinor: number }
|
|
325
|
+
/** Void the till's recorded legs on the store order a refused sale left part paid, then cancel it. */
|
|
326
|
+
export interface SettleReverseRequest extends SettleCancelRequest { legs: readonly SettleReverseLeg[] }
|
|
327
|
+
/** `voided`: the request's payment ids the store holds as voided when the call ends, in request order. */
|
|
328
|
+
export interface SettleReverseResult { outcome: SettleOutcome; voided: readonly string[] }
|
|
329
|
+
|
|
320
330
|
/** Settlement of an order the store created before it refused the sale. */
|
|
321
331
|
export interface RefusedOrderSettlement {
|
|
322
332
|
cancel?: (context: SyncContext, request: SettleCancelRequest) => Promise<SettleOutcome>;
|
|
@@ -327,6 +337,16 @@ export interface RefusedOrderSettlement {
|
|
|
327
337
|
* means no definite answer: send again with the same `attemptId` and payment ids.
|
|
328
338
|
*/
|
|
329
339
|
pay?: (context: SyncContext, request: SettlePayRequest) => Promise<SettlePayResult>;
|
|
340
|
+
/**
|
|
341
|
+
* No money moves: the cashier hands it back. `voided` lists the legs the store holds as voided when the call ends.
|
|
342
|
+
* `done`: every leg is voided and the order reads `cancelled`.
|
|
343
|
+
* `changed`: the store shows money or a status the till does not hold, so nothing more was sent.
|
|
344
|
+
* `refused`: the store refused this step, or answered in a way that is not a usable ledger answer (as for `cancel` and `pay`).
|
|
345
|
+
* The order is not cancelled. A refused void always stops the run before any cancel is sent.
|
|
346
|
+
* `gone`: only from the uuid resolver's 404.
|
|
347
|
+
* `retry`: no definite answer. Send again with the same `attemptId` and command ids.
|
|
348
|
+
*/
|
|
349
|
+
reverse?: (context: SyncContext, request: SettleReverseRequest) => Promise<SettleReverseResult>;
|
|
330
350
|
}
|
|
331
351
|
|
|
332
352
|
/**
|
|
@@ -334,6 +354,10 @@ export interface RefusedOrderSettlement {
|
|
|
334
354
|
* Each backend (WooCommerce, Medusa, Vendure, etc.) implements this.
|
|
335
355
|
*/
|
|
336
356
|
export interface TallyConnector {
|
|
357
|
+
/** True when the store's live order-line totals shrink as units are returned while `quantity` stays the sold quantity (Medusa). The refund form then refuses a partial refund of a line without `soldTotalMinor`/`soldTaxMinor`. Absent: line totals are as sold. */
|
|
358
|
+
lineTotalsShrinkOnReturn?: boolean;
|
|
359
|
+
/** True when the store turns each discounted order line into its own taxed row and rounds each taxed row once (Vendure, ADR-048). The till's rounding tolerance then also counts the order's discounted lines. Absent: discounts are not separate taxed rows. */
|
|
360
|
+
discountsAreTaxedRows?: boolean;
|
|
337
361
|
/** Unique identifier for this connector */
|
|
338
362
|
id: string;
|
|
339
363
|
/** Human-readable name */
|
package/src/types/orders.ts
CHANGED
|
@@ -20,6 +20,12 @@ export interface StoreOrderLine {
|
|
|
20
20
|
/** After discounts, excluding tax. */
|
|
21
21
|
totalMinor: number;
|
|
22
22
|
taxMinor: number;
|
|
23
|
+
/** The line's total after discounts, excluding tax, as sold, before any return; set by a connector whose live totals shrink on return (connector-medusa at plugin contract 7), absent otherwise. */
|
|
24
|
+
soldTotalMinor?: number;
|
|
25
|
+
/** The tax beside `soldTotalMinor`, as sold. Present exactly when it is. */
|
|
26
|
+
soldTaxMinor?: number;
|
|
27
|
+
/** The store's returned quantity for the line (requested, received or dismissed returns); absent when the store does not say. Refund pricing does not read it. */
|
|
28
|
+
returnedQuantity?: number;
|
|
23
29
|
}
|
|
24
30
|
|
|
25
31
|
/** A fee or shipping line: excluding tax, the tax beside it. A fee may be negative.
|