@tallyui/core 3.2.1 → 3.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.
@@ -0,0 +1,31 @@
1
+ // Ported from @wcpos/order-math, MIT, Copyright (c) 2021-2026 WCPOS.
2
+ // WooCommerce tax parity (ADR-076): keep the arithmetic as in the original; see docs/DECISIONS.md.
3
+ import type { ItemizedTax } from './types';
4
+
5
+ function sumTaxTotals(taxes: { total: number }[]): number {
6
+ if (taxes.length === 0) return 0;
7
+ let result: number | undefined;
8
+ for (const tax of taxes) {
9
+ const current = tax.total;
10
+ if (current !== undefined) result = result === undefined ? current : result + current;
11
+ }
12
+ // Preserve lodash's number return type; all-undefined totals yield undefined at runtime.
13
+ return result as number;
14
+ }
15
+
16
+ export function sumTaxes({ taxes }: { taxes: { total: number; [key: string]: any }[] }) {
17
+ const sum = sumTaxTotals(taxes);
18
+ return sum;
19
+ }
20
+
21
+ export function sumItemizedTaxes({ taxes }: { taxes: (ItemizedTax | ItemizedTax[])[] }) {
22
+ // group taxes by id
23
+ const groupedTaxes: Record<string, ItemizedTax[]> = Object.create(null);
24
+ for (const tax of taxes.flat()) {
25
+ (groupedTaxes[tax.id] ??= []).push(tax);
26
+ }
27
+ return Object.entries(groupedTaxes).map(([id, itemized]) => ({
28
+ id: Number(id), // groupBy converts the key to a string
29
+ total: sumTaxes({ taxes: itemized }),
30
+ }));
31
+ }
@@ -0,0 +1,105 @@
1
+ // Ported from @wcpos/order-math, MIT, Copyright (c) 2021-2026 WCPOS.
2
+ // WooCommerce tax parity (ADR-076): keep the arithmetic as in the original; see docs/DECISIONS.md.
3
+ /**
4
+ * The WooCommerce REST API spells the standard tax class as an empty string on
5
+ * order documents and line items (the wc/v3 taxes endpoint spells rate classes
6
+ * 'standard'). Every read of an item's tax_class for rate matching must
7
+ * normalize through this helper; the sites that inline the ternary are exactly
8
+ * the ones that drift.
9
+ *
10
+ * The UI ⇄ wire codec for the same quirk lives below in this module.
11
+ */
12
+ export const STANDARD_TAX_CLASS = 'standard';
13
+
14
+ export function normalizeTaxClass(value?: string | null): string {
15
+ return value === '' || value === null || value === undefined ? STANDARD_TAX_CLASS : value;
16
+ }
17
+
18
+ /**
19
+ * WooCommerce's "shipping tax class based on the cart items" sentinel — the value a
20
+ * store's `woocommerce_shipping_tax_class` option holds by default. It is not a class:
21
+ * it matches no tax rate, and it must be resolved against the order's line items
22
+ * before any rate lookup.
23
+ */
24
+ export const INHERIT_TAX_CLASS = 'inherit';
25
+
26
+ /** Resolved to "no shipping tax at all", which is distinct from "the standard class". */
27
+ export const NO_SHIPPING_TAX = null;
28
+
29
+ /**
30
+ * Port of the `'inherit'` branch of `WC_Abstract_Order::calculate_taxes()` — the path
31
+ * WooCommerce takes for an order, which is what this package builds (the storefront's
32
+ * `WC_Tax::get_shipping_tax_rates()` reaches the same answer through the live cart).
33
+ *
34
+ * ```php
35
+ * $found_classes = array_intersect( array_merge( array( '' ), WC_Tax::get_tax_class_slugs() ), $this->get_items_tax_classes() );
36
+ * $shipping_tax_class = count( $found_classes ) ? current( $found_classes ) : false;
37
+ * // Orders without product line items have no tax class to inherit, so use the standard class.
38
+ * if ( false === $shipping_tax_class && 0 === count( $this->get_items() ) ) {
39
+ * $shipping_tax_class = '';
40
+ * }
41
+ * ```
42
+ *
43
+ * Three details the PHP encodes positionally and are easy to lose in a port:
44
+ *
45
+ * 1. `array_intersect` preserves the order of its FIRST argument, so the candidate
46
+ * order is the configured tax-class order with the standard class ahead of it —
47
+ * **the standard class wins whenever any line item carries it**, never "the first
48
+ * class in the cart".
49
+ * 2. `get_items()` defaults to `'line_item'`, so **fee lines are not inherited from**,
50
+ * and only line items count toward the "no items" fallback.
51
+ * 3. `get_items_tax_classes()` skips items that are not taxable. Line items that exist
52
+ * but are all non-taxable therefore give `false`, not `''` — and WooCommerce then
53
+ * charges **no shipping tax**. Returning the standard class there would invent tax
54
+ * on an order WooCommerce leaves untaxed.
55
+ */
56
+ export function resolveInheritedShippingTaxClass(
57
+ activeLineItems: readonly { tax_class?: string | null; taxable: boolean }[],
58
+ taxClassSlugs: readonly string[]
59
+ ): string | typeof NO_SHIPPING_TAX {
60
+ const itemClasses = new Set(
61
+ activeLineItems.filter((item) => item.taxable).map((item) => normalizeTaxClass(item.tax_class))
62
+ );
63
+
64
+ // No taxable classes to inherit. An order with no line items at all (shipping- or
65
+ // fee-only) falls back to the standard class; one whose items are ALL non-taxable
66
+ // does not — see (3).
67
+ if (itemClasses.size === 0) {
68
+ return activeLineItems.length === 0 ? STANDARD_TAX_CLASS : NO_SHIPPING_TAX;
69
+ }
70
+
71
+ // (1) and (2) are decided by the cart alone. Ordering them ahead of the configured
72
+ // list is not just an optimisation: `taxClassSlugs` comes from a lazily fetched
73
+ // endpoint, and resolving the common carts without it means an unfetched list
74
+ // cannot silently zero the shipping tax.
75
+ if (itemClasses.has(STANDARD_TAX_CLASS)) return STANDARD_TAX_CLASS;
76
+ if (itemClasses.size === 1) return [...itemClasses][0];
77
+
78
+ // (3) Several non-standard classes: the configured order breaks the tie.
79
+ const found = taxClassSlugs.find((slug) => itemClasses.has(normalizeTaxClass(slug)));
80
+ if (found !== undefined) return normalizeTaxClass(found);
81
+
82
+ // Nothing matched. `wc/v3 taxes/classes` always contains the standard class, so an
83
+ // EMPTY list means it has not loaded yet (or its fetch failed) — not that the cart's
84
+ // classes were all rejected. Charging nothing on unloaded reference data would
85
+ // under-tax the order and stay wrong for as long as the fetch keeps failing, so the
86
+ // unknown case takes the standard class and only a genuinely loaded list that
87
+ // matches nothing yields no shipping tax.
88
+ if (taxClassSlugs.length === 0) return STANDARD_TAX_CLASS;
89
+ return NO_SHIPPING_TAX;
90
+ }
91
+
92
+ /**
93
+ * The WooCommerce REST API spells the standard tax class as an empty string and
94
+ * rejects the literal 'standard' with an error, while UI selects can't hold ''
95
+ * as a value — so the app spells it 'standard'. Every read of a wire/document
96
+ * tax_class and every write back to one must go through this codec; the sites
97
+ * that inline the ternary are exactly the ones that drift.
98
+ */
99
+ export function taxClassFromWire(value?: string | null): string {
100
+ return value === '' || value === null || value === undefined ? STANDARD_TAX_CLASS : value;
101
+ }
102
+
103
+ export function taxClassToWire(value?: string | null): string {
104
+ return value === STANDARD_TAX_CLASS || value === null || value === undefined ? '' : value;
105
+ }
@@ -0,0 +1,40 @@
1
+ // Ported from @wcpos/order-math, MIT, Copyright (c) 2021-2026 WCPOS.
2
+ // WooCommerce tax parity (ADR-076): keep the arithmetic as in the original; see docs/DECISIONS.md.
3
+ export interface WooTaxRate {
4
+ id: number;
5
+ country: string;
6
+ state: string;
7
+ postcode: string;
8
+ city: string;
9
+ postcodes: string[];
10
+ cities: string[];
11
+ rate: string;
12
+ name: string;
13
+ priority: number;
14
+ compound: boolean;
15
+ shipping: boolean;
16
+ order: number;
17
+ class: string;
18
+ }
19
+
20
+ export interface CalculateTaxesInput {
21
+ amount: number;
22
+ rates: {
23
+ id: number;
24
+ rate: string;
25
+ compound: boolean;
26
+ order: number;
27
+ priority?: number;
28
+ [key: string]: any;
29
+ }[];
30
+ amountIncludesTax: boolean;
31
+ dp?: number;
32
+ perRatePrecision?: number;
33
+ }
34
+
35
+ export type ItemizedTax = { id: number; total: number; [key: string]: any };
36
+
37
+ export interface CalculateTaxesResult {
38
+ total: number;
39
+ taxes: { id: number; total: number }[];
40
+ }
@@ -6,8 +6,9 @@ export interface CommandEnvelope<P = unknown> {
6
6
  id: string; // UUIDv7, the idempotency key; never reused
7
7
  type: CommandType;
8
8
  /** 3 when the order carries ADR-065's `display` and `taxByRate` (the store accepts 3), else 2 when discounted, else 1;
9
- * 4 is 3 with every `discountMinor` tax-exclusive, built only when capped at 4 or more (#286). */
10
- version: 1 | 2 | 3 | 4;
9
+ * 4 is 3 with every `discountMinor` tax-exclusive, built only when capped at 4 or more (#286).
10
+ * 5 is 4 plus fees, shipping and custom lines (ADR-075), sent only for an order that has one. */
11
+ version: 1 | 2 | 3 | 4 | 5;
11
12
  payload: P;
12
13
  createdAt: string; // ISO 8601, client clock
13
14
  deviceId: string;
@@ -23,8 +24,8 @@ export type RegisterCommandEnvelope<P = Record<string, unknown>> =
23
24
  /** Any command a transport can carry. */
24
25
  export type AnyCommandEnvelope = CommandEnvelope<unknown> | RegisterCommandEnvelope<unknown>;
25
26
 
26
- /** An order.create envelope: its version is 1 | 2 | 3 | 4 (ADR-062, ADR-065, #286). */
27
- export type OrderCreateEnvelope = CommandEnvelope<OrderCreatePayload> & { type: 'order.create'; version: 1 | 2 | 3 | 4 };
27
+ /** An order.create envelope: 5 is 4 plus fees, shipping and custom lines (ADR-075), sent only for an order that has one. */
28
+ export type OrderCreateEnvelope = CommandEnvelope<OrderCreatePayload> & { type: 'order.create'; version: 1 | 2 | 3 | 4 | 5 };
28
29
 
29
30
  /** Outcome of processing a command. */
30
31
  export type CommandStatus = 'applied' | 'duplicate' | 'rejected';
@@ -132,7 +133,19 @@ export interface RegisterClosureSubmitPayload {
132
133
  /** Order line with client identity and price in minor units. */
133
134
  export interface OrderCreateLine {
134
135
  clientLineId: string;
135
- variantId: string;
136
+ /** Required unless `custom` is set (version 5). */
137
+ variantId?: string;
138
+ /** Version 5 instruction: a non-catalogue line, without variantId; takes line and order discounts. */
139
+ custom?: {
140
+ /** Recorded title, 1–255 characters. */
141
+ name: string;
142
+ /** Recorded SKU, at most 64 characters when present. */
143
+ sku?: string;
144
+ /** Instruction, at most 64 characters; absent means the standard class. */
145
+ taxClass?: string;
146
+ /** Instruction: `none` means no tax on this line. */
147
+ taxStatus: 'taxable' | 'none';
148
+ };
136
149
  title?: string;
137
150
  quantity: number;
138
151
  unitPriceMinor: number;
@@ -146,11 +159,35 @@ export interface OrderCreateLine {
146
159
  * Version 2 (ADR-062): this line's total discount, its own line discounts plus its allocated share of
147
160
  * the order discount, in the line's own tax mode and integer minor units. The line is taxed on
148
161
  * `unitPriceMinor × quantity − discountMinor`. Present only when above 0.
149
- * Version 4 (#286): tax-exclusive (net) in every mode; an inclusive line's is `net(A) − net(A − D)`.
162
+ * Version 4+ (#286): tax-exclusive (net) in every mode; an inclusive line's is `net(A) − net(A − D)`.
150
163
  */
151
164
  discountMinor?: number;
152
165
  }
153
166
 
167
+ /** Version 5: a fee, never discounted (ADR-075). */
168
+ export interface OrderCreateFee {
169
+ /** Identity: UUID, stable for the order's life, at most 36 characters. */
170
+ clientFeeId: string;
171
+ /** Recorded fee title, 1–255 characters. */
172
+ name: string;
173
+ /** Instruction: integer >= 0, gross when pricesIncludeTax, net otherwise; never discounted. */
174
+ amountMinor: number;
175
+ /** Instruction: `none` means no tax on this fee. */
176
+ taxStatus: 'taxable' | 'none';
177
+ /** Instruction, at most 64 characters; absent means the standard class. */
178
+ taxClass?: string;
179
+ /** Informational till tax, integer >= 0; a server difference is total_mismatch, not a refusal. */
180
+ taxMinor: number;
181
+ }
182
+
183
+ /** Version 5: the same instructions and recorded/informational fields as a fee, never discounted. */
184
+ export interface OrderCreateShipping extends Omit<OrderCreateFee, 'clientFeeId'> {
185
+ /** Identity: UUID, stable for the order's life, at most 36 characters. */
186
+ clientShippingId: string;
187
+ /** Recorded shipping method id, at most 64 characters; absent means a POS-entered charge. */
188
+ methodId?: string;
189
+ }
190
+
154
191
  /** Supported order payment method. */
155
192
  export type PaymentMethodKind = 'cash' | 'external';
156
193
 
@@ -179,6 +216,20 @@ export interface OrderCreateDisplay {
179
216
  amountMinor: number;
180
217
  discounts: Array<{ discountId: string; label?: string; amountMinor: number }>;
181
218
  }>;
219
+ /** Version 5 recorded figures: one row per payload fee, in the display tax mode. */
220
+ fees?: Array<{
221
+ /** Identity: the payload fee's clientFeeId. */
222
+ clientFeeId: string;
223
+ /** Recorded integer minor units, equal to the payload fee amount. */
224
+ amountMinor: number;
225
+ }>;
226
+ /** Version 5 recorded figures: one row per payload shipping charge, in the display tax mode. */
227
+ shipping?: Array<{
228
+ /** Identity: the payload shipping charge's clientShippingId. */
229
+ clientShippingId: string;
230
+ /** Recorded integer minor units, equal to the payload shipping amount. */
231
+ amountMinor: number;
232
+ }>;
182
233
  }
183
234
 
184
235
  /** Version 3 (ADR-065): one tax rate's net, tax and gross, as the receipt's tax summary splits them. */
@@ -197,28 +248,32 @@ export interface OrderCreatePayload {
197
248
  currency: string;
198
249
  pricesIncludeTax: boolean;
199
250
  lines: OrderCreateLine[];
251
+ /** Version 5 instructions: fees in the order's tax mode; omitted when none. */
252
+ fees?: OrderCreateFee[];
253
+ /** Version 5 instructions: shipping in the order's tax mode; omitted when none. */
254
+ shipping?: OrderCreateShipping[];
200
255
  subtotalMinor: number;
201
256
  /**
202
257
  * Version 2 (ADR-062): the order's total discount, equal to Σ `lines[].discountMinor`. Present only when above 0.
203
- * Version 4 (#286) means every `discountMinor`, this and each line's, is tax-exclusive, so the sum still holds.
258
+ * Version 4+ (#286) means every `discountMinor`, this and each line's, is tax-exclusive, so the sum still holds.
204
259
  */
205
260
  discountMinor?: number;
206
261
  taxMinor: number;
207
262
  totalMinor: number;
208
263
  payments: OrderCreatePayment[];
209
- /** version 3 only; both or neither. */
264
+ /** Version 3+; both or neither. */
210
265
  display?: OrderCreateDisplay;
211
- /** version 3 only; both or neither. */
266
+ /** Version 3+; both or neither. */
212
267
  taxByRate?: OrderCreateTaxRate[];
213
268
  customer?: {
214
269
  email?: string;
215
- /** Version 3 only: the platform's id for the customer picked at the till, a soft reference of at most 64 characters. Absent for a guest sale, or when no customer was picked. */
270
+ /** Version 3+: the platform's id for the customer picked at the till, a soft reference of at most 64 characters. Absent for a guest sale, or when no customer was picked. */
216
271
  customerId?: string;
217
272
  } | null;
218
273
  registerId?: string;
219
274
  cashierRef?: string;
220
275
  locationId?: string;
221
- /** Version 3 only: the register session the sale was taken for, stamped or late (ADR-032). A late sale names the session that refused its stamp; the server tells the two apart by the session's closure `orderIds`. Absent when the sale had no session. */
276
+ /** Version 3+: the register session the sale was taken for, stamped or late (ADR-032). A late sale names the session that refused its stamp; the server tells the two apart by the session's closure `orderIds`. Absent when the sale had no session. */
222
277
  sessionId?: string;
223
278
  }
224
279
 
@@ -43,11 +43,21 @@ export interface ServerCapabilities {
43
43
  register?: number;
44
44
  /** How the store rounds tax (#287). Absent: an older server, per_order + half_away_from_zero. */
45
45
  taxRounding?: TaxRounding;
46
+ /** Whether one order may carry several payments. Absent means it may: order.create's `payments` has always been a
47
+ * list. A WooCommerce store says false until its plugin records the list (`order_payments_list`). The app offers
48
+ * split tender only when this is not false. */
49
+ multiplePayments?: boolean;
50
+ /**
51
+ * What the store accepts for a fee's, a shipping charge's or a custom line's tax (order.create 5, ADR-075):
52
+ * `none` is `taxStatus: 'none'`, `classes` is a `taxClass`. Absent means neither; the UI hides what is false.
53
+ */
54
+ lineTax?: { none: boolean; classes: boolean };
46
55
  }
47
56
 
48
57
  /** #287, ADR-071. `custom`: the till computes as when absent; that server never emits `figures_mismatch` for subtotal or tax. */
49
58
  export type TaxRounding =
50
59
  | { granularity: 'per_order' | 'per_line_items' | 'per_rate_group_items'; mode: 'half_away_from_zero' | 'half_up' }
60
+ | { granularity: 'woocommerce'; roundAtSubtotal: boolean }
51
61
  | { granularity: 'custom' };
52
62
 
53
63
  /**
@@ -75,9 +85,10 @@ const MODES = ['half_away_from_zero', 'half_up'];
75
85
  */
76
86
  export function parseTaxRounding(value: unknown, warn?: (reason: string) => void): TaxRounding | undefined {
77
87
  if (value === undefined) return undefined;
78
- const { granularity, mode } = (value ?? {}) as { granularity?: unknown; mode?: unknown };
88
+ const { granularity, mode, roundAtSubtotal } = (value ?? {}) as { granularity?: unknown; mode?: unknown; roundAtSubtotal?: unknown };
79
89
  if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
80
90
  if (granularity === 'custom') return { granularity };
91
+ if (granularity === 'woocommerce' && typeof roundAtSubtotal === 'boolean') return { granularity, roundAtSubtotal };
81
92
  if (GRANULARITIES.includes(granularity as string) && MODES.includes(mode as string)) {
82
93
  return { granularity, mode } as TaxRounding;
83
94
  }
@@ -86,6 +97,16 @@ export function parseTaxRounding(value: unknown, warn?: (reason: string) => void
86
97
  return undefined;
87
98
  }
88
99
 
100
+ export function parseLineTax(value: unknown, warn?: (reason: string) => void): { none: boolean; classes: boolean } | undefined {
101
+ if (value === undefined) return undefined;
102
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
103
+ const { none, classes } = value as { none?: unknown; classes?: unknown };
104
+ if (typeof none === 'boolean' && typeof classes === 'boolean') return { none, classes };
105
+ }
106
+ warn?.('ignoring a malformed lineTax');
107
+ return undefined;
108
+ }
109
+
89
110
  const maxVersion = (list: unknown): number | undefined => {
90
111
  const valid = Array.isArray(list) ? list.filter((v): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v > 0) : [];
91
112
  return valid.length > 0 ? Math.max(...valid) : undefined;
@@ -94,7 +115,7 @@ const maxVersion = (list: unknown): number | undefined => {
94
115
  /**
95
116
  * Reads a 2xx body of `GET /tally/v1/info` (ADR-062): `orderCreate` is the max of
96
117
  * `contracts["order.create"]`, or 1 when it's missing or malformed; `register` is the max of
97
- * `contracts.register` when valid; `taxRounding` is the top-level sibling of `contracts` (#287).
118
+ * `contracts.register` when valid; `taxRounding` is the top-level sibling of `contracts` (#287); malformed `lineTax` is ignored.
98
119
  * Absent `taxRounding` uses the default; a present malformed value is unknown, so settings wait.
99
120
  * A non-object body is also unknown, not a statement of the store's defaults.
100
121
  */
@@ -103,15 +124,17 @@ export function parseInfoCapabilities(body: unknown, warn?: (reason: string) =>
103
124
  warn?.('non-object info body: capabilities unknown');
104
125
  return undefined;
105
126
  }
106
- const { contracts, taxRounding } = body as { contracts?: Record<string, unknown> | null; taxRounding?: unknown };
127
+ const { contracts, taxRounding, lineTax } = body as { contracts?: Record<string, unknown> | null; taxRounding?: unknown; lineTax?: unknown };
107
128
  const register = maxVersion(contracts?.register);
108
129
  const rounding = parseTaxRounding(taxRounding);
109
130
  if (taxRounding !== undefined && rounding === undefined) {
110
131
  warn?.(`malformed taxRounding: rounding is unknown, so settings wait: ${JSON.stringify(taxRounding)}`);
111
132
  return undefined;
112
133
  }
134
+ const parsedLineTax = parseLineTax(lineTax, warn);
113
135
  return { orderCreate: maxVersion(contracts?.['order.create']) ?? 1,
114
- ...(register !== undefined ? { register } : {}), ...(rounding ? { taxRounding: rounding } : {}) };
136
+ ...(register !== undefined ? { register } : {}), ...(rounding ? { taxRounding: rounding } : {}),
137
+ ...(parsedLineTax ? { lineTax: parsedLineTax } : {}) };
115
138
  }
116
139
 
117
140
  export interface AuthField {
@@ -10,6 +10,11 @@ export interface StoreSettings {
10
10
  taxRatesPpm: { default: number; [taxClass: string]: number };
11
11
  /** The backend's tax rate name per tax class (same keys as `taxRatesPpm`, including `default`), for `per_rate_group_items`' grouping (#324). Set by a connector whose rounding groups by rate name; absent otherwise. */
12
12
  taxRateCodes?: Record<string, string>;
13
+ /** WooCommerce rates already filtered to the store's tax address; the empty class uses `standard`. */
14
+ taxRates?: Record<string, { id: number; code: string; label: string; rate: string; priority: number; compound: boolean; shipping: boolean }[]>;
15
+ taxRoundAtSubtotal?: boolean;
16
+ shippingTaxClass?: string;
17
+ taxClassSlugs?: string[];
13
18
  /** Connector-specific and opaque to the app: what the connector needs to price documents. The app passes it back to the connector unchanged, and never logs it. */
14
19
  pricingContext?: Record<string, string>;
15
20
  /** Derived, never read by `storeSettings`: the store's `ServerCapabilities.taxRounding`, which `useStoreSettings` fills in (#324). */
@@ -65,6 +65,12 @@ export interface ProductTraits<Doc = any> {
65
65
  */
66
66
  getTaxClass?: (doc: Doc, variantId?: string) => string | undefined;
67
67
 
68
+ /**
69
+ * Whether the variant `variantId` (or the product's default variant) is taxed: 'none' means the line carries no
70
+ * tax. Undefined means taxable. Optional: without it, every line is taxable.
71
+ */
72
+ getTaxStatus?: (doc: Doc, variantId?: string) => 'taxable' | 'none' | undefined;
73
+
68
74
  /** @deprecated Use `getPrices` with `resolvePrice`. */
69
75
  getPrice: (doc: Doc) => string | undefined;
70
76