@tallyui/core 4.2.0 → 5.0.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.
@@ -22,6 +22,7 @@ var server_exports = {};
22
22
  __export(server_exports, {
23
23
  CommandResultError: () => CommandResultError,
24
24
  MAX_COMMANDS_PER_BATCH: () => MAX_COMMANDS_PER_BATCH,
25
+ NEEDS_ADMIN_MESSAGE_MAX: () => NEEDS_ADMIN_MESSAGE_MAX,
25
26
  ORDER_NOTE_MAX: () => ORDER_NOTE_MAX,
26
27
  SUPPORTED_ORDER_CREATE_VERSIONS: () => SUPPORTED_ORDER_CREATE_VERSIONS,
27
28
  SUPPORTED_ORDER_REFUND_VERSIONS: () => SUPPORTED_ORDER_REFUND_VERSIONS,
@@ -41,15 +42,19 @@ __export(server_exports, {
41
42
  majorToMinor: () => majorToMinor,
42
43
  minorToMajor: () => minorToMajor,
43
44
  minorUnitDigits: () => minorUnitDigits,
45
+ needsAdminOutcome: () => needsAdminOutcome,
44
46
  parseCommandResult: () => parseCommandResult,
45
47
  payloadBoundErrors: () => payloadBoundErrors,
46
48
  payloadShapeErrors: () => payloadShapeErrors,
47
49
  platformErrorResult: () => platformErrorResult,
48
50
  precheckCommand: () => precheckCommand,
51
+ priceRefund: () => priceRefund,
49
52
  ratePpmFromPercent: () => ratePpmFromPercent,
50
53
  refundPayloadErrors: () => refundPayloadErrors,
54
+ refundableLines: () => refundableLines,
51
55
  registerPayloadErrors: () => registerPayloadErrors,
52
56
  reopenPayloadErrors: () => reopenPayloadErrors,
57
+ roundRatio: () => roundRatio,
53
58
  totalWarnings: () => totalWarnings,
54
59
  transientOutcome: () => transientOutcome,
55
60
  updatePayloadErrors: () => updatePayloadErrors,
@@ -134,6 +139,7 @@ function commandFingerprint(envelope) {
134
139
  // src/commands.ts
135
140
  var MAX_COMMANDS_PER_BATCH = 50;
136
141
  var ORDER_NOTE_MAX = 1e3;
142
+ var NEEDS_ADMIN_MESSAGE_MAX = 500;
137
143
  var ORDER_TAX_IDS_MAX = 10;
138
144
  var ORDER_TAX_ID_TYPE_MAX = 32;
139
145
  var ORDER_TAX_ID_VALUE_MAX = 64;
@@ -194,6 +200,17 @@ function payloadShapeErrors(payload) {
194
200
  const lineDiscounts = (Array.isArray(payload.lines) ? payload.lines : []).reduce((sum, line, index) => sum + (object(line) ? discount(line.discountMinor, `lines[${index}].discountMinor`) : 0n), 0n);
195
201
  const orderDiscount = discount(payload.discountMinor, "discountMinor");
196
202
  if (errors.length === 0) check2(orderDiscount === lineDiscounts, "discountMinor", "the sum of lines[].discountMinor");
203
+ if (payload.cashRoundings !== void 0) {
204
+ const entries = payload.cashRoundings;
205
+ check2(Array.isArray(entries) && entries.length <= 16, "cashRoundings", "an array of at most 16 entries");
206
+ if (Array.isArray(entries) && entries.length <= 16) for (const [index, entry] of entries.entries()) {
207
+ const path = `cashRoundings[${index}]`;
208
+ check2(object(entry), path, "an object");
209
+ if (!object(entry)) continue;
210
+ check2(typeof entry.paymentId === "string" && entry.paymentId.length > 0, `${path}.paymentId`, "a non-empty string");
211
+ check2(Number.isSafeInteger(entry.minor), `${path}.minor`, "a safe integer");
212
+ }
213
+ }
197
214
  if (payload.customer !== void 0 && payload.customer !== null) {
198
215
  check2(object(payload.customer), "customer", "an object");
199
216
  if (object(payload.customer) && payload.customer.email !== void 0) {
@@ -543,6 +560,17 @@ function fiscalFiguresErrors(payload) {
543
560
  check2(!seen.has(line.clientLineId), `display.lines[${index}].clientLineId`, "no duplicate clientLineId");
544
561
  seen.add(line.clientLineId);
545
562
  });
563
+ if (!errors.length) {
564
+ const sum = (rows) => (rows ?? []).reduce((total, row) => total + BigInt(row.amountMinor), 0n);
565
+ const roundings = (payload.cashRoundings ?? []).reduce((total, entry) => total + BigInt(entry.minor), 0n);
566
+ check2(
567
+ BigInt(display.subtotalMinor) - BigInt(display.discountMinor) + sum(display.fees) + sum(display.shipping) + (display.taxInclusive ? 0n : BigInt(display.taxMinor)) + roundings === BigInt(display.totalMinor),
568
+ "display.totalMinor",
569
+ "subtotalMinor \u2212 discountMinor + fees + shipping (+ taxMinor when exclusive) + cashRoundings"
570
+ );
571
+ check2(sum(display.lines) === BigInt(display.subtotalMinor), "display.subtotalMinor", "the sum of display.lines[].amountMinor");
572
+ check2(BigInt(display.discountMinor) === BigInt(display.orderDiscountMinor) + display.lines.reduce((total, line) => total + sum(line.discounts), 0n) + sum(display.coupons), "display.discountMinor", "orderDiscountMinor + the line discount rows + the coupon rows");
573
+ }
546
574
  try {
547
575
  check2(display.exponent === currencyDecimals(payload.currency), "display.exponent", "the currency decimals");
548
576
  } catch {
@@ -561,7 +589,7 @@ function fiscalFiguresErrors(payload) {
561
589
 
562
590
  // src/server/versions.ts
563
591
  var SUPPORTED_ORDER_CREATE_VERSIONS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
564
- var SUPPORTED_REGISTER_VERSIONS = [1];
592
+ var SUPPORTED_REGISTER_VERSIONS = [1, 2, 3];
565
593
  var SUPPORTED_ORDER_REFUND_VERSIONS = [1];
566
594
  var SUPPORTED_ORDER_REOPEN_VERSIONS = [1];
567
595
  var SUPPORTED_ORDER_UPDATE_VERSIONS = [1];
@@ -712,6 +740,9 @@ function precheckCommand(envelope, supported) {
712
740
  { orderCreate: Math.max(...supported.orderCreate) }
713
741
  );
714
742
  }
743
+ if (command.payload.cashRoundings !== void 0 && supported.cashRounding !== true) {
744
+ return rejected(command.id, "invalid_payload", "cashRoundings requires the cashRounding capability, which this server does not declare");
745
+ }
715
746
  const { lines, discountMinor } = command.payload;
716
747
  const discounted = discountMinor !== void 0 || Array.isArray(lines) && lines.some((line) => line?.discountMinor !== void 0);
717
748
  const payload = command.payload;
@@ -766,6 +797,9 @@ function precheckCommand(envelope, supported) {
766
797
  function inProgressOutcome(id) {
767
798
  return { status: 409, body: { code: "in_progress", id } };
768
799
  }
800
+ function needsAdminOutcome(id, reason, message) {
801
+ return { status: 409, body: { code: "needs_admin", id, reason, message: message.slice(0, NEEDS_ADMIN_MESSAGE_MAX) } };
802
+ }
769
803
  function transientOutcome(id) {
770
804
  return { status: 503, body: { code: "transient", id, message: "Temporary failure, retry later." } };
771
805
  }
@@ -827,7 +861,8 @@ function parseCommandResult(value) {
827
861
  return [key, amount];
828
862
  }));
829
863
  if (Object.values(byMethod).reduce((sum, amount) => sum + amount, 0) !== refund.totalMinor) throw new CommandResultError("Invalid refund.byMethod");
830
- if (!Array.isArray(refund.refunds) || refund.refunds.length === 0) throw new CommandResultError("Invalid refund.refunds");
864
+ if (!Array.isArray(refund.refunds)) throw new CommandResultError("Invalid refund.refunds");
865
+ if (refund.refunds.length === 0 && (refund.totalMinor !== 0 || Object.keys(byMethod).length > 0)) throw new CommandResultError("Invalid refund.refunds");
831
866
  const refunds = refund.refunds.map((value2, index) => {
832
867
  const field = `refund.refunds[${index}]`;
833
868
  if (!object(value2)) throw new CommandResultError(`Invalid ${field}`);
@@ -1884,10 +1919,65 @@ function displaySignallingContract(makeHarness) {
1884
1919
  };
1885
1920
  return Object.entries(cases).map(([name, run]) => ({ name, run: async () => run(await world(makeHarness)) }));
1886
1921
  }
1922
+
1923
+ // src/server/round-ratio.ts
1924
+ function roundRatio(n, d, mode = "half_away_from_zero") {
1925
+ if (mode === "half_away_from_zero" && n < 0n) return -roundRatio(-n, d, mode);
1926
+ const a = 2n * n + d, b = 2n * d;
1927
+ return a / b - (a < 0n && a % b !== 0n ? 1n : 0n);
1928
+ }
1929
+
1930
+ // src/server/refund-share.ts
1931
+ function refundableLines(lines, refunds) {
1932
+ const earlier = refunds.flatMap((refund) => refund.lines);
1933
+ for (const refund of earlier) {
1934
+ if (!Number.isSafeInteger(refund.quantity)) throw new RangeError("Earlier refund quantity must be a safe integer");
1935
+ }
1936
+ return lines.map((line) => {
1937
+ if (!Number.isSafeInteger(line.quantity) || line.quantity < 0 || !Number.isSafeInteger(line.totalMinor) || !Number.isSafeInteger(line.taxMinor)) {
1938
+ throw new RangeError("Order line values must be safe integers and quantity non-negative");
1939
+ }
1940
+ const refundedQuantity = earlier.reduce((sum, refund) => refund.orderLineId === line.id ? Math.min(line.quantity, sum + Math.abs(refund.quantity)) : sum, 0);
1941
+ const [netMinor, taxMinor] = [line.totalMinor, line.taxMinor].map((total) => line.quantity === 0 ? 0 : total - Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), "half_up")));
1942
+ return {
1943
+ orderLineId: line.id,
1944
+ refundedQuantity,
1945
+ refundableQuantity: line.quantity - refundedQuantity,
1946
+ netMinor,
1947
+ taxMinor
1948
+ };
1949
+ });
1950
+ }
1951
+ function priceRefund(lines, refunds, request) {
1952
+ const available = refundableLines(lines, refunds);
1953
+ const seen = /* @__PURE__ */ new Set();
1954
+ const result = { lines: [], priced: [], clamped: [], netMinor: 0, taxMinor: 0, totalMinor: 0 };
1955
+ for (const { orderLineId, quantity: requestedQuantity, restock } of request) {
1956
+ if (!Number.isSafeInteger(requestedQuantity) || requestedQuantity < 0 || seen.has(orderLineId)) {
1957
+ throw new RangeError("Request quantities must be non-negative safe integers and line ids unique");
1958
+ }
1959
+ seen.add(orderLineId);
1960
+ const index = lines.findIndex((line2) => line2.id === orderLineId);
1961
+ const quantity = Math.min(requestedQuantity, available[index]?.refundableQuantity ?? 0);
1962
+ if (quantity < requestedQuantity) result.clamped.push({ orderLineId, requestedQuantity, quantity });
1963
+ if (quantity < 1) continue;
1964
+ const line = lines[index];
1965
+ const refundedQuantity = available[index].refundedQuantity;
1966
+ const [netMinor, taxMinor] = [line.totalMinor, line.taxMinor].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")));
1967
+ const totalMinor = netMinor + taxMinor;
1968
+ result.lines.push({ orderLineId, quantity, restock });
1969
+ result.priced.push({ orderLineId, quantity, netMinor, taxMinor, totalMinor });
1970
+ result.netMinor += netMinor;
1971
+ result.taxMinor += taxMinor;
1972
+ result.totalMinor += totalMinor;
1973
+ }
1974
+ return result;
1975
+ }
1887
1976
  // Annotate the CommonJS export names for ESM import in node:
1888
1977
  0 && (module.exports = {
1889
1978
  CommandResultError,
1890
1979
  MAX_COMMANDS_PER_BATCH,
1980
+ NEEDS_ADMIN_MESSAGE_MAX,
1891
1981
  ORDER_NOTE_MAX,
1892
1982
  SUPPORTED_ORDER_CREATE_VERSIONS,
1893
1983
  SUPPORTED_ORDER_REFUND_VERSIONS,
@@ -1907,15 +1997,19 @@ function displaySignallingContract(makeHarness) {
1907
1997
  majorToMinor,
1908
1998
  minorToMajor,
1909
1999
  minorUnitDigits,
2000
+ needsAdminOutcome,
1910
2001
  parseCommandResult,
1911
2002
  payloadBoundErrors,
1912
2003
  payloadShapeErrors,
1913
2004
  platformErrorResult,
1914
2005
  precheckCommand,
2006
+ priceRefund,
1915
2007
  ratePpmFromPercent,
1916
2008
  refundPayloadErrors,
2009
+ refundableLines,
1917
2010
  registerPayloadErrors,
1918
2011
  reopenPayloadErrors,
2012
+ roundRatio,
1919
2013
  totalWarnings,
1920
2014
  transientOutcome,
1921
2015
  updatePayloadErrors,
@@ -100,6 +100,7 @@ type OrderRefundEnvelope<P = OrderRefundPayload> = Omit<CommandEnvelope<P>, 'typ
100
100
  interface OrderRefundResult {
101
101
  totalMinor: number;
102
102
  byMethod: Record<string, number>;
103
+ /** The platform refunds created, summing to totalMinor. Empty only for a stock-only return: totalMinor 0 and byMethod {} (ADR-080, #1330). */
103
104
  refunds: Array<{
104
105
  id: string;
105
106
  paymentId: string;
@@ -306,7 +307,7 @@ interface RegisterCommandResult {
306
307
  deviceId?: string;
307
308
  deviceName?: string;
308
309
  };
309
- /** The register's counters: a floor for the till's own, never lowered. */
310
+ /** The register's counters: a floor for the till's own, never lowered, with two exceptions for perpetual refunds. The till raises refunds only from answers at the highest closure number among the store's answers, and sets them to the largest store figure at its newest applied closure once nothing of its own is unsent (@tallyui/pos settleStoreRefunds). A closure refused for its number resets the counters outright (@tallyui/pos renumberClosures). */
310
311
  counters?: {
311
312
  lastClosureNumber: number;
312
313
  perpetualSalesTotalMinor: number;
@@ -490,6 +491,11 @@ interface OrderCreatePayload {
490
491
  taxMinor: number;
491
492
  totalMinor: number;
492
493
  payments: OrderCreatePayment[];
494
+ /** ADR-094: each cash leg's signed rounding, in minor units, already summed into `totalMinor`; sent at the order's content version, only for an order that has one, and only to a store whose connector declares `cashRounding` (a server without it refuses the field). */
495
+ cashRoundings?: Array<{
496
+ paymentId: string;
497
+ minor: number;
498
+ }>;
493
499
  /** Version 3+; both or neither. */
494
500
  display?: OrderCreateDisplay;
495
501
  /** Version 3+; both or neither. */
@@ -555,6 +561,28 @@ type BatchTooLargeBody = {
555
561
  message: string;
556
562
  };
557
563
 
564
+ /** A line of an order the store holds (ADR-081). Money in integer minor units of the order's currency, as the store
565
+ * records it: every amount excludes tax, and the tax is beside it.
566
+ * Each tax field is such that net + tax is the gross rounded once. */
567
+ interface StoreOrderLine {
568
+ /** The store's line id: what `OrderRefundLine.orderLineId` names. */
569
+ id: string;
570
+ /** The till's line id when a till created the line (its `clientLineId`); absent otherwise. */
571
+ clientLineId?: string;
572
+ productId?: string;
573
+ /** The sellable the till's `variantId` names (a WooCommerce variation, or the product itself when simple). */
574
+ variantId?: string;
575
+ name: string;
576
+ sku?: string;
577
+ quantity: number;
578
+ /** Before discounts, excluding tax. */
579
+ subtotalMinor: number;
580
+ subtotalTaxMinor: number;
581
+ /** After discounts, excluding tax. */
582
+ totalMinor: number;
583
+ taxMinor: number;
584
+ }
585
+
558
586
  /** One ICE server, in the shape `RTCPeerConnection` takes (ADR-085 d7). */
559
587
  interface IceServer {
560
588
  urls: string | string[];
@@ -734,6 +762,8 @@ interface ServerCapabilities {
734
762
  receiptEmail?: number;
735
763
  /** The platform plugin's own contract version, from `/tally/v1/info`'s top-level `pluginContract` (#1114). Absent when not sent or malformed; each connector says what a version adds. */
736
764
  pluginContract?: number;
765
+ /** 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
+ cashRounding?: boolean;
737
767
  }
738
768
  /** #287, ADR-071. `custom`: the till computes as when absent; that server never emits `figures_mismatch` for subtotal or tax. */
739
769
  type TaxRounding = {
@@ -782,7 +812,11 @@ declare function fiscalFiguresErrors(payload: OrderCreatePayload): string[];
782
812
  * 12 is 11 plus the customer's tax ids, a catalogue line's edited SKU and order meta, as informational fields (ADR-092).
783
813
  */
784
814
  declare const SUPPORTED_ORDER_CREATE_VERSIONS: readonly number[];
785
- /** The till's capability for the contract versions shared by all five register commands; a server passes its own. */
815
+ /**
816
+ * The till's capability for the contract versions shared by all five register commands; a server passes its own.
817
+ * The till builds 1 (every command), 2 (session.open, contract ≥ 2) and 3 (session.open and closure.submit,
818
+ * contract ≥ 3; ADR-082).
819
+ */
786
820
  declare const SUPPORTED_REGISTER_VERSIONS: readonly number[];
787
821
  /** The till's capability for order.refund versions (ADR-080); a server passes its own. */
788
822
  declare const SUPPORTED_ORDER_REFUND_VERSIONS: readonly number[];
@@ -795,6 +829,8 @@ declare const SUPPORTED_ORDER_UPDATE_VERSIONS: readonly number[];
795
829
  declare const MAX_COMMANDS_PER_BATCH = 50;
796
830
  /** The longest order.create `note` (version 7, ADR-083), in UTF-16 code units. WCPOS v2's order note has no cap; this bounds the wire. */
797
831
  declare const ORDER_NOTE_MAX = 1000;
832
+ /** The most UTF-16 units of a `needs_admin` message the till keeps and shows (TallyUI #1280). */
833
+ declare const NEEDS_ADMIN_MESSAGE_MAX = 500;
798
834
 
799
835
  /** An envelope validateBatch accepted: every field's shape is checked, and its version is any positive
800
836
  * safe integer (precheckCommand decides which versions this server supports). */
@@ -844,6 +880,8 @@ declare function validateBatch(body: unknown): {
844
880
  * `supported` is the SERVER's own list (what its /info advertises), never core's constants, which are the
845
881
  * till's capability (#297). The version check, the `unsupported_version` message and its `data` all use it:
846
882
  * `precheckCommand(envelope, { orderCreate: [1, 2, 3], register: [1], orderRefund: [1], orderReopen: [1], orderUpdate: [1] })` (`orderRefund`, `orderReopen` and `orderUpdate` are optional).
883
+ * `cashRounding` is the server's own word too (ADR-094): without `true`, an order.create (or an order.update's create part)
884
+ * carrying `cashRoundings` is refused as `invalid_payload`, never sent on with the field dropped, which would be a wrong total.
847
885
  */
848
886
  declare function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCommandEnvelope, 'id' | 'type' | 'version' | 'payload'>, supported: {
849
887
  orderCreate: readonly number[];
@@ -851,6 +889,7 @@ declare function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCo
851
889
  orderRefund?: readonly number[];
852
890
  orderReopen?: readonly number[];
853
891
  orderUpdate?: readonly number[];
892
+ cashRounding?: boolean;
854
893
  }): CommandResult | undefined;
855
894
 
856
895
  /**
@@ -866,6 +905,14 @@ type BatchOutcome = {
866
905
  code: 'in_progress';
867
906
  id: string;
868
907
  };
908
+ } | {
909
+ status: 409;
910
+ body: {
911
+ code: 'needs_admin';
912
+ id: string;
913
+ reason: string;
914
+ message: string;
915
+ };
869
916
  } | {
870
917
  status: 503;
871
918
  body: {
@@ -875,6 +922,8 @@ type BatchOutcome = {
875
922
  };
876
923
  };
877
924
  declare function inProgressOutcome(id: string): BatchOutcome;
925
+ /** A command an admin must finish (TallyUI #1280). `reason` is snake_case; `message` is cut to NEEDS_ADMIN_MESSAGE_MAX. */
926
+ declare function needsAdminOutcome(id: string, reason: string, message: string): BatchOutcome;
878
927
  /** The message is fixed so a server never leaks its internal error (log that separately). */
879
928
  declare function transientOutcome(id: string): BatchOutcome;
880
929
 
@@ -1036,4 +1085,57 @@ declare function displaySignallingContract(makeHarness: () => Promise<DisplaySig
1036
1085
  run: () => Promise<void>;
1037
1086
  }>;
1038
1087
 
1039
- export { type BatchOutcome, type BatchTooLargeBody, type CommandErrorWithData, type CommandRejectionCode, CommandResultError, type DisplaySignallingHarness, MAX_COMMANDS_PER_BATCH, ORDER_NOTE_MAX, type OrderCreateDisplay, type OrderCreatePayloadV3, type OrderCreateTaxRate, type OrderRejectionCode, type RegisterConflictCode, type RegisterOutcome, type Rejection, SUPPORTED_ORDER_CREATE_VERSIONS, SUPPORTED_ORDER_REFUND_VERSIONS, SUPPORTED_ORDER_REOPEN_VERSIONS, SUPPORTED_ORDER_UPDATE_VERSIONS, SUPPORTED_REGISTER_VERSIONS, type ValidatedCommandEnvelope, canonicalJson, commandFingerprint, createMemoryDisplaySignalling, currencyDecimals, deriveSessionFigures, deriveVariance, displaySignallingContract, fiscalFiguresErrors, inProgressOutcome, internalErrorResult, majorToMinor, minorToMajor, minorUnitDigits, parseCommandResult, payloadBoundErrors, payloadShapeErrors, platformErrorResult, precheckCommand, ratePpmFromPercent, refundPayloadErrors, registerPayloadErrors, reopenPayloadErrors, totalWarnings, transientOutcome, updatePayloadErrors, validateBatch };
1088
+ /** #287: `half_up` is Math.round's rule, Vendure's DefaultMoneyStrategy (default-money-strategy.js:19-21). */
1089
+ type RoundingMode = 'half_away_from_zero' | 'half_up';
1090
+ /** `n / d` (d > 0) rounded to an integer in `mode`, exactly; the modes differ only on exact negative halves. */
1091
+ declare function roundRatio(n: bigint, d: bigint, mode?: RoundingMode): bigint;
1092
+
1093
+ /**
1094
+ * Ports v2 calculate-refund.ts (calculateLineItemRefund, computeRemainingRefundQuantity).
1095
+ * Amounts follow ADR-080 amendment 2's cumulative-share rule.
1096
+ */
1097
+
1098
+ /** The fields of an order line this needs; a StoreOrderLine fits. */
1099
+ type RefundableOrderLine = Pick<StoreOrderLine, 'id' | 'quantity' | 'totalMinor' | 'taxMinor'>;
1100
+ /** Earlier refund lines; negative quantities count by magnitude. */
1101
+ interface EarlierRefund {
1102
+ lines: ReadonlyArray<Pick<OrderRefundLine, 'orderLineId' | 'quantity'>>;
1103
+ }
1104
+ /** Remaining quantities and amounts, with earlier refund magnitudes capped at the line quantity. */
1105
+ interface RefundableLine {
1106
+ orderLineId: string;
1107
+ refundedQuantity: number;
1108
+ refundableQuantity: number;
1109
+ netMinor: number;
1110
+ taxMinor: number;
1111
+ }
1112
+ /** A selected quantity's cumulative shares of net and tax, and their sum. */
1113
+ interface PricedRefundLine {
1114
+ orderLineId: string;
1115
+ quantity: number;
1116
+ netMinor: number;
1117
+ taxMinor: number;
1118
+ totalMinor: number;
1119
+ }
1120
+ /** Payload-ready lines and their amounts; the caller adds shipping and adjustment to totalMinor. */
1121
+ interface PricedRefund {
1122
+ /** Exactly orderLineId, quantity (>= 1), and restock. */
1123
+ lines: OrderRefundLine[];
1124
+ /** Amounts in the same order as lines. */
1125
+ priced: PricedRefundLine[];
1126
+ /** Requests cut to availability, including unknown lines cut to zero. */
1127
+ clamped: Array<{
1128
+ orderLineId: string;
1129
+ requestedQuantity: number;
1130
+ quantity: number;
1131
+ }>;
1132
+ netMinor: number;
1133
+ taxMinor: number;
1134
+ totalMinor: number;
1135
+ }
1136
+ /** Returns the quantities and amounts still refundable, in order-line order. */
1137
+ declare function refundableLines(lines: readonly RefundableOrderLine[], refunds: readonly EarlierRefund[]): RefundableLine[];
1138
+ /** Prices requested quantities with cumulative shares, clamping them to what remains refundable. */
1139
+ declare function priceRefund(lines: readonly RefundableOrderLine[], refunds: readonly EarlierRefund[], request: readonly OrderRefundLine[]): PricedRefund;
1140
+
1141
+ export { type BatchOutcome, type BatchTooLargeBody, type CommandErrorWithData, type CommandRejectionCode, CommandResultError, type DisplaySignallingHarness, type EarlierRefund, MAX_COMMANDS_PER_BATCH, NEEDS_ADMIN_MESSAGE_MAX, ORDER_NOTE_MAX, type OrderCreateDisplay, type OrderCreatePayloadV3, type OrderCreateTaxRate, type OrderRejectionCode, type PricedRefund, type PricedRefundLine, type RefundableLine, type RefundableOrderLine, type RegisterConflictCode, type RegisterOutcome, type Rejection, type RoundingMode, SUPPORTED_ORDER_CREATE_VERSIONS, SUPPORTED_ORDER_REFUND_VERSIONS, SUPPORTED_ORDER_REOPEN_VERSIONS, SUPPORTED_ORDER_UPDATE_VERSIONS, SUPPORTED_REGISTER_VERSIONS, type ValidatedCommandEnvelope, canonicalJson, commandFingerprint, createMemoryDisplaySignalling, currencyDecimals, deriveSessionFigures, deriveVariance, displaySignallingContract, fiscalFiguresErrors, inProgressOutcome, internalErrorResult, majorToMinor, minorToMajor, minorUnitDigits, needsAdminOutcome, parseCommandResult, payloadBoundErrors, payloadShapeErrors, platformErrorResult, precheckCommand, priceRefund, ratePpmFromPercent, refundPayloadErrors, refundableLines, registerPayloadErrors, reopenPayloadErrors, roundRatio, totalWarnings, transientOutcome, updatePayloadErrors, validateBatch };
@@ -1,5 +1,5 @@
1
- import { J as CommandError, ax as OrderCreatePayload, H as CommandEnvelope, bg as RegisterCommandEnvelope, A as AnyCommandEnvelope, K as CommandResult, B as BatchTooLargeBody, G as CommandBatchResponse, C as CommandWarning, bh as RegisterCommandResult, aJ as OrderRefundRejectionCode, aP as OrderReopenRejectionCode, aW as OrderUpdateRejectionCode, aa as DisplaySignalling, b as SyncContext, ab as DisplaySignallingContext } from '../tax-rate-DCJhfJbZ.js';
2
- export { N as CommandResultError, ah as MAX_COMMANDS_PER_BATCH, al as ORDER_NOTE_MAX, at as OrderCreateDisplay, aA as OrderCreateTaxRate, cd as currencyDecimals, bR as deriveSessionFigures, bS as deriveVariance, ce as majorToMinor, bX as minorToMajor, bY as minorUnitDigits, c3 as parseCommandResult, c8 as ratePpmFromPercent } from '../tax-rate-DCJhfJbZ.js';
1
+ import { J as CommandError, aA as OrderCreatePayload, H as CommandEnvelope, bn as RegisterCommandEnvelope, A as AnyCommandEnvelope, K as CommandResult, B as BatchTooLargeBody, G as CommandBatchResponse, C as CommandWarning, bo as RegisterCommandResult, aM as OrderRefundRejectionCode, aS as OrderReopenRejectionCode, aZ as OrderUpdateRejectionCode, aa as DisplaySignalling, b as SyncContext, ab as DisplaySignallingContext } from '../refund-share-BZ_Ff9Zk.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, bz as RoundingMode, cs as currencyDecimals, c1 as deriveSessionFigures, c2 as deriveVariance, ct as majorToMinor, c7 as minorToMajor, c8 as minorUnitDigits, cf as parseCommandResult, ck as priceRefund, cl as ratePpmFromPercent, cm as refundableLines, cq as roundRatio } from '../refund-share-BZ_Ff9Zk.js';
3
3
  import 'rxdb';
4
4
  import 'rxjs';
5
5
 
@@ -47,7 +47,11 @@ declare function fiscalFiguresErrors(payload: OrderCreatePayload): string[];
47
47
  * 12 is 11 plus the customer's tax ids, a catalogue line's edited SKU and order meta, as informational fields (ADR-092).
48
48
  */
49
49
  declare const SUPPORTED_ORDER_CREATE_VERSIONS: readonly number[];
50
- /** The till's capability for the contract versions shared by all five register commands; a server passes its own. */
50
+ /**
51
+ * The till's capability for the contract versions shared by all five register commands; a server passes its own.
52
+ * The till builds 1 (every command), 2 (session.open, contract ≥ 2) and 3 (session.open and closure.submit,
53
+ * contract ≥ 3; ADR-082).
54
+ */
51
55
  declare const SUPPORTED_REGISTER_VERSIONS: readonly number[];
52
56
  /** The till's capability for order.refund versions (ADR-080); a server passes its own. */
53
57
  declare const SUPPORTED_ORDER_REFUND_VERSIONS: readonly number[];
@@ -104,6 +108,8 @@ declare function validateBatch(body: unknown): {
104
108
  * `supported` is the SERVER's own list (what its /info advertises), never core's constants, which are the
105
109
  * till's capability (#297). The version check, the `unsupported_version` message and its `data` all use it:
106
110
  * `precheckCommand(envelope, { orderCreate: [1, 2, 3], register: [1], orderRefund: [1], orderReopen: [1], orderUpdate: [1] })` (`orderRefund`, `orderReopen` and `orderUpdate` are optional).
111
+ * `cashRounding` is the server's own word too (ADR-094): without `true`, an order.create (or an order.update's create part)
112
+ * carrying `cashRoundings` is refused as `invalid_payload`, never sent on with the field dropped, which would be a wrong total.
107
113
  */
108
114
  declare function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCommandEnvelope, 'id' | 'type' | 'version' | 'payload'>, supported: {
109
115
  orderCreate: readonly number[];
@@ -111,6 +117,7 @@ declare function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCo
111
117
  orderRefund?: readonly number[];
112
118
  orderReopen?: readonly number[];
113
119
  orderUpdate?: readonly number[];
120
+ cashRounding?: boolean;
114
121
  }): CommandResult | undefined;
115
122
 
116
123
  /**
@@ -126,6 +133,14 @@ type BatchOutcome = {
126
133
  code: 'in_progress';
127
134
  id: string;
128
135
  };
136
+ } | {
137
+ status: 409;
138
+ body: {
139
+ code: 'needs_admin';
140
+ id: string;
141
+ reason: string;
142
+ message: string;
143
+ };
129
144
  } | {
130
145
  status: 503;
131
146
  body: {
@@ -135,6 +150,8 @@ type BatchOutcome = {
135
150
  };
136
151
  };
137
152
  declare function inProgressOutcome(id: string): BatchOutcome;
153
+ /** A command an admin must finish (TallyUI #1280). `reason` is snake_case; `message` is cut to NEEDS_ADMIN_MESSAGE_MAX. */
154
+ declare function needsAdminOutcome(id: string, reason: string, message: string): BatchOutcome;
138
155
  /** The message is fixed so a server never leaks its internal error (log that separately). */
139
156
  declare function transientOutcome(id: string): BatchOutcome;
140
157
 
@@ -256,4 +273,4 @@ declare function displaySignallingContract(makeHarness: () => Promise<DisplaySig
256
273
  run: () => Promise<void>;
257
274
  }>;
258
275
 
259
- export { type BatchOutcome, BatchTooLargeBody, type CommandErrorWithData, type CommandRejectionCode, type DisplaySignallingHarness, type OrderCreatePayloadV3, type OrderRejectionCode, type RegisterConflictCode, type RegisterOutcome, type Rejection, SUPPORTED_ORDER_CREATE_VERSIONS, SUPPORTED_ORDER_REFUND_VERSIONS, SUPPORTED_ORDER_REOPEN_VERSIONS, SUPPORTED_ORDER_UPDATE_VERSIONS, SUPPORTED_REGISTER_VERSIONS, type ValidatedCommandEnvelope, canonicalJson, commandFingerprint, createMemoryDisplaySignalling, displaySignallingContract, fiscalFiguresErrors, inProgressOutcome, internalErrorResult, payloadBoundErrors, payloadShapeErrors, platformErrorResult, precheckCommand, refundPayloadErrors, registerPayloadErrors, reopenPayloadErrors, totalWarnings, transientOutcome, updatePayloadErrors, validateBatch };
276
+ export { type BatchOutcome, BatchTooLargeBody, type CommandErrorWithData, type CommandRejectionCode, type DisplaySignallingHarness, type OrderCreatePayloadV3, type OrderRejectionCode, type RegisterConflictCode, type RegisterOutcome, type Rejection, SUPPORTED_ORDER_CREATE_VERSIONS, SUPPORTED_ORDER_REFUND_VERSIONS, SUPPORTED_ORDER_REOPEN_VERSIONS, SUPPORTED_ORDER_UPDATE_VERSIONS, SUPPORTED_REGISTER_VERSIONS, type ValidatedCommandEnvelope, canonicalJson, commandFingerprint, createMemoryDisplaySignalling, displaySignallingContract, fiscalFiguresErrors, inProgressOutcome, internalErrorResult, needsAdminOutcome, payloadBoundErrors, payloadShapeErrors, platformErrorResult, precheckCommand, refundPayloadErrors, registerPayloadErrors, reopenPayloadErrors, totalWarnings, transientOutcome, updatePayloadErrors, validateBatch };
@@ -3,6 +3,7 @@ import {
3
3
  DISPLAY_PAIR_CAPABILITY,
4
4
  DisplaySignallingError,
5
5
  MAX_COMMANDS_PER_BATCH,
6
+ NEEDS_ADMIN_MESSAGE_MAX,
6
7
  ORDER_LINE_SKU_MAX,
7
8
  ORDER_META_KEY_MAX,
8
9
  ORDER_META_MAX,
@@ -17,9 +18,12 @@ import {
17
18
  minorToMajor,
18
19
  minorUnitDigits,
19
20
  parseCommandResult,
21
+ priceRefund,
20
22
  rateLimitSource,
21
- ratePpmFromPercent
22
- } from "../chunk-XF3RD6GX.js";
23
+ ratePpmFromPercent,
24
+ refundableLines,
25
+ roundRatio
26
+ } from "../chunk-RPBSJ3FB.js";
23
27
  import "../chunk-MLKGABMK.js";
24
28
 
25
29
  // src/server/fingerprint.ts
@@ -90,6 +94,17 @@ function payloadShapeErrors(payload) {
90
94
  const lineDiscounts = (Array.isArray(payload.lines) ? payload.lines : []).reduce((sum, line, index) => sum + (object(line) ? discount(line.discountMinor, `lines[${index}].discountMinor`) : 0n), 0n);
91
95
  const orderDiscount = discount(payload.discountMinor, "discountMinor");
92
96
  if (errors.length === 0) check2(orderDiscount === lineDiscounts, "discountMinor", "the sum of lines[].discountMinor");
97
+ if (payload.cashRoundings !== void 0) {
98
+ const entries = payload.cashRoundings;
99
+ check2(Array.isArray(entries) && entries.length <= 16, "cashRoundings", "an array of at most 16 entries");
100
+ if (Array.isArray(entries) && entries.length <= 16) for (const [index, entry] of entries.entries()) {
101
+ const path = `cashRoundings[${index}]`;
102
+ check2(object(entry), path, "an object");
103
+ if (!object(entry)) continue;
104
+ check2(typeof entry.paymentId === "string" && entry.paymentId.length > 0, `${path}.paymentId`, "a non-empty string");
105
+ check2(Number.isSafeInteger(entry.minor), `${path}.minor`, "a safe integer");
106
+ }
107
+ }
93
108
  if (payload.customer !== void 0 && payload.customer !== null) {
94
109
  check2(object(payload.customer), "customer", "an object");
95
110
  if (object(payload.customer) && payload.customer.email !== void 0) {
@@ -439,6 +454,17 @@ function fiscalFiguresErrors(payload) {
439
454
  check2(!seen.has(line.clientLineId), `display.lines[${index}].clientLineId`, "no duplicate clientLineId");
440
455
  seen.add(line.clientLineId);
441
456
  });
457
+ if (!errors.length) {
458
+ const sum = (rows) => (rows ?? []).reduce((total, row) => total + BigInt(row.amountMinor), 0n);
459
+ const roundings = (payload.cashRoundings ?? []).reduce((total, entry) => total + BigInt(entry.minor), 0n);
460
+ check2(
461
+ BigInt(display.subtotalMinor) - BigInt(display.discountMinor) + sum(display.fees) + sum(display.shipping) + (display.taxInclusive ? 0n : BigInt(display.taxMinor)) + roundings === BigInt(display.totalMinor),
462
+ "display.totalMinor",
463
+ "subtotalMinor \u2212 discountMinor + fees + shipping (+ taxMinor when exclusive) + cashRoundings"
464
+ );
465
+ check2(sum(display.lines) === BigInt(display.subtotalMinor), "display.subtotalMinor", "the sum of display.lines[].amountMinor");
466
+ check2(BigInt(display.discountMinor) === BigInt(display.orderDiscountMinor) + display.lines.reduce((total, line) => total + sum(line.discounts), 0n) + sum(display.coupons), "display.discountMinor", "orderDiscountMinor + the line discount rows + the coupon rows");
467
+ }
442
468
  try {
443
469
  check2(display.exponent === currencyDecimals(payload.currency), "display.exponent", "the currency decimals");
444
470
  } catch {
@@ -457,7 +483,7 @@ function fiscalFiguresErrors(payload) {
457
483
 
458
484
  // src/server/versions.ts
459
485
  var SUPPORTED_ORDER_CREATE_VERSIONS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
460
- var SUPPORTED_REGISTER_VERSIONS = [1];
486
+ var SUPPORTED_REGISTER_VERSIONS = [1, 2, 3];
461
487
  var SUPPORTED_ORDER_REFUND_VERSIONS = [1];
462
488
  var SUPPORTED_ORDER_REOPEN_VERSIONS = [1];
463
489
  var SUPPORTED_ORDER_UPDATE_VERSIONS = [1];
@@ -608,6 +634,9 @@ function precheckCommand(envelope, supported) {
608
634
  { orderCreate: Math.max(...supported.orderCreate) }
609
635
  );
610
636
  }
637
+ if (command.payload.cashRoundings !== void 0 && supported.cashRounding !== true) {
638
+ return rejected(command.id, "invalid_payload", "cashRoundings requires the cashRounding capability, which this server does not declare");
639
+ }
611
640
  const { lines, discountMinor } = command.payload;
612
641
  const discounted = discountMinor !== void 0 || Array.isArray(lines) && lines.some((line) => line?.discountMinor !== void 0);
613
642
  const payload = command.payload;
@@ -662,6 +691,9 @@ function precheckCommand(envelope, supported) {
662
691
  function inProgressOutcome(id) {
663
692
  return { status: 409, body: { code: "in_progress", id } };
664
693
  }
694
+ function needsAdminOutcome(id, reason, message) {
695
+ return { status: 409, body: { code: "needs_admin", id, reason, message: message.slice(0, NEEDS_ADMIN_MESSAGE_MAX) } };
696
+ }
665
697
  function transientOutcome(id) {
666
698
  return { status: 503, body: { code: "transient", id, message: "Temporary failure, retry later." } };
667
699
  }
@@ -1509,6 +1541,7 @@ function displaySignallingContract(makeHarness) {
1509
1541
  export {
1510
1542
  CommandResultError,
1511
1543
  MAX_COMMANDS_PER_BATCH,
1544
+ NEEDS_ADMIN_MESSAGE_MAX,
1512
1545
  ORDER_NOTE_MAX,
1513
1546
  SUPPORTED_ORDER_CREATE_VERSIONS,
1514
1547
  SUPPORTED_ORDER_REFUND_VERSIONS,
@@ -1528,15 +1561,19 @@ export {
1528
1561
  majorToMinor,
1529
1562
  minorToMajor,
1530
1563
  minorUnitDigits,
1564
+ needsAdminOutcome,
1531
1565
  parseCommandResult,
1532
1566
  payloadBoundErrors,
1533
1567
  payloadShapeErrors,
1534
1568
  platformErrorResult,
1535
1569
  precheckCommand,
1570
+ priceRefund,
1536
1571
  ratePpmFromPercent,
1537
1572
  refundPayloadErrors,
1573
+ refundableLines,
1538
1574
  registerPayloadErrors,
1539
1575
  reopenPayloadErrors,
1576
+ roundRatio,
1540
1577
  totalWarnings,
1541
1578
  transientOutcome,
1542
1579
  updatePayloadErrors,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/core",
3
- "version": "4.2.0",
3
+ "version": "5.0.0",
4
4
  "type": "module",
5
5
  "description": "Core interfaces, traits, and context providers for Tally UI",
6
6
  "main": "./dist/index.js",
@@ -51,6 +51,9 @@
51
51
  "rxjs": ">=7"
52
52
  },
53
53
  "peerDependenciesMeta": {
54
+ "react": {
55
+ "optional": true
56
+ },
54
57
  "rxdb": {
55
58
  "optional": true
56
59
  },
package/src/commands.ts CHANGED
@@ -10,6 +10,8 @@ export const PROTOCOL_VERSION = 1;
10
10
  export const MAX_COMMANDS_PER_BATCH = 50;
11
11
  /** The longest order.create `note` (version 7, ADR-083), in UTF-16 code units. WCPOS v2's order note has no cap; this bounds the wire. */
12
12
  export const ORDER_NOTE_MAX = 1000;
13
+ /** The most UTF-16 units of a `needs_admin` message the till keeps and shows (TallyUI #1280). */
14
+ export const NEEDS_ADMIN_MESSAGE_MAX = 500;
13
15
  /** The most tax ids order.create 12 carries in `customer.taxIds` (ADR-092). */
14
16
  export const ORDER_TAX_IDS_MAX = 10;
15
17
  /** The longest order.create 12 tax id `type` (the connector's scheme id), in UTF-16 code units (ADR-092). */
package/src/index.ts CHANGED
@@ -54,9 +54,10 @@ export type {
54
54
  } from './types/payment-methods';
55
55
  export type { ReceiptTemplate, ReceiptTemplateKind } from './types/receipt-templates';
56
56
  export type {
57
- StoreOrder, StoreOrderLine, StoreOrderCharge, StoreOrderPayment, StoreOrderRefund, ListOrdersQuery, StoreOrderPage, OrderFilterField,
57
+ StoreOrder, StoreOrderLine, StoreOrderCharge, StoreOrderPayment, StoreOrderRefund, StoreOrderRefundLine, ListOrdersQuery, StoreOrderPage, OrderFilterField,
58
+ StoreRefund, StoreRefundOrphan, ListRefundsQuery, StoreRefundPage,
58
59
  } from './types/orders';
59
- export { ORDER_FILTER_FIELDS, UnsupportedOrderFilterError, orderFilterFields, assertOrderFiltersSupported, assertOrderDateRange } from './order-filters';
60
+ export { ORDER_FILTER_FIELDS, UnsupportedOrderFilterError, StoreRefundsUnsupportedError, orderFilterFields, assertOrderFiltersSupported, assertOrderDateRange } from './order-filters';
60
61
  export type { RegisterInfo } from './types/registers';
61
62
  export type { ApproverCredentials, Correction, StoreClosure, ClosureReads } from './types/closures';
62
63
  export { CASHIER_PERMISSIONS, cashierPermissions, isCashierPermission, type Cashier, type CashierPermission } from './types/cashier';
@@ -83,7 +84,7 @@ export type {
83
84
  export type { OrderAddress, OrderCreateCouponLine } from './types/commands';
84
85
 
85
86
  export {
86
- COMMANDS_PATH, PROTOCOL_HEADER, PROTOCOL_VERSION, MAX_COMMANDS_PER_BATCH, ORDER_NOTE_MAX,
87
+ COMMANDS_PATH, PROTOCOL_HEADER, PROTOCOL_VERSION, MAX_COMMANDS_PER_BATCH, ORDER_NOTE_MAX, NEEDS_ADMIN_MESSAGE_MAX,
87
88
  ORDER_TAX_IDS_MAX, ORDER_TAX_ID_TYPE_MAX, ORDER_TAX_ID_VALUE_MAX, ORDER_META_MAX, ORDER_META_KEY_MAX, ORDER_LINE_SKU_MAX,
88
89
  isCommandBatchResponse,
89
90
  } from './commands';
@@ -123,3 +124,7 @@ export { parseCommandResult, CommandResultError } from './server/command-result'
123
124
  export { deriveSessionFigures, deriveVariance } from './server/register-figures';
124
125
  // Browser-safe: tax-rate.ts has no imports. The till and servers convert percentages to the same integer ppm.
125
126
  export { ratePpmFromPercent } from './server/tax-rate';
127
+ // Browser-safe: round-ratio.ts has no imports. The till and servers round exact ratios the same way.
128
+ export { roundRatio, type RoundingMode } from './server/round-ratio';
129
+ // Browser-safe: refund-share.ts imports only types and round-ratio. The till and servers share one BigInt refund share (desk, 22 Nov).
130
+ export { refundableLines, priceRefund, type RefundableOrderLine, type EarlierRefund, type RefundableLine, type PricedRefundLine, type PricedRefund } from './server/refund-share';