@tallyui/core 3.2.1 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,6 +5,9 @@ import {
5
5
  PROTOCOL_VERSION,
6
6
  isCommandBatchResponse
7
7
  } from "./chunk-C4PWPOKO.js";
8
+ import {
9
+ __export
10
+ } from "./chunk-MLKGABMK.js";
8
11
 
9
12
  // src/types/connector.ts
10
13
  function resolveCapabilities(fresh, stored) {
@@ -14,9 +17,10 @@ var GRANULARITIES = ["per_order", "per_line_items", "per_rate_group_items"];
14
17
  var MODES = ["half_away_from_zero", "half_up"];
15
18
  function parseTaxRounding(value, warn) {
16
19
  if (value === void 0) return void 0;
17
- const { granularity, mode } = value ?? {};
20
+ const { granularity, mode, roundAtSubtotal } = value ?? {};
18
21
  if (typeof value === "object" && value !== null && !Array.isArray(value)) {
19
22
  if (granularity === "custom") return { granularity };
23
+ if (granularity === "woocommerce" && typeof roundAtSubtotal === "boolean") return { granularity, roundAtSubtotal };
20
24
  if (GRANULARITIES.includes(granularity) && MODES.includes(mode)) {
21
25
  return { granularity, mode };
22
26
  }
@@ -24,6 +28,15 @@ function parseTaxRounding(value, warn) {
24
28
  warn?.(`ignoring a malformed taxRounding, so the default applies: ${JSON.stringify(value)}`);
25
29
  return void 0;
26
30
  }
31
+ function parseLineTax(value, warn) {
32
+ if (value === void 0) return void 0;
33
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
34
+ const { none, classes } = value;
35
+ if (typeof none === "boolean" && typeof classes === "boolean") return { none, classes };
36
+ }
37
+ warn?.("ignoring a malformed lineTax");
38
+ return void 0;
39
+ }
27
40
  var maxVersion = (list) => {
28
41
  const valid = Array.isArray(list) ? list.filter((v) => typeof v === "number" && Number.isSafeInteger(v) && v > 0) : [];
29
42
  return valid.length > 0 ? Math.max(...valid) : void 0;
@@ -33,17 +46,19 @@ function parseInfoCapabilities(body, warn) {
33
46
  warn?.("non-object info body: capabilities unknown");
34
47
  return void 0;
35
48
  }
36
- const { contracts, taxRounding } = body;
49
+ const { contracts, taxRounding, lineTax } = body;
37
50
  const register = maxVersion(contracts?.register);
38
51
  const rounding = parseTaxRounding(taxRounding);
39
52
  if (taxRounding !== void 0 && rounding === void 0) {
40
53
  warn?.(`malformed taxRounding: rounding is unknown, so settings wait: ${JSON.stringify(taxRounding)}`);
41
54
  return void 0;
42
55
  }
56
+ const parsedLineTax = parseLineTax(lineTax, warn);
43
57
  return {
44
58
  orderCreate: maxVersion(contracts?.["order.create"]) ?? 1,
45
59
  ...register !== void 0 ? { register } : {},
46
- ...rounding ? { taxRounding: rounding } : {}
60
+ ...rounding ? { taxRounding: rounding } : {},
61
+ ...parsedLineTax ? { lineTax: parsedLineTax } : {}
47
62
  };
48
63
  }
49
64
 
@@ -469,6 +484,354 @@ function useCustomerTraits() {
469
484
  const connector = useConnector();
470
485
  return connector.traits.customer;
471
486
  }
487
+
488
+ // src/tax/woocommerce/index.ts
489
+ var woocommerce_exports = {};
490
+ __export(woocommerce_exports, {
491
+ NO_SHIPPING_TAX: () => NO_SHIPPING_TAX,
492
+ STANDARD_TAX_CLASS: () => STANDARD_TAX_CLASS,
493
+ addNumberPrecision: () => addNumberPrecision,
494
+ calculateTaxes: () => calculateTaxes,
495
+ filterTaxRates: () => filterTaxRates,
496
+ getRoundingPrecision: () => getRoundingPrecision,
497
+ normalizeTaxClass: () => normalizeTaxClass,
498
+ removeNumberPrecision: () => removeNumberPrecision,
499
+ resolveInheritedShippingTaxClass: () => resolveInheritedShippingTaxClass,
500
+ roundHalfDown: () => roundHalfDown,
501
+ roundHalfUp: () => roundHalfUp,
502
+ roundTaxTotal: () => roundTaxTotal,
503
+ sumItemizedTaxes: () => sumItemizedTaxes,
504
+ sumTaxes: () => sumTaxes,
505
+ taxClassFromWire: () => taxClassFromWire,
506
+ taxClassToWire: () => taxClassToWire
507
+ });
508
+
509
+ // src/tax/woocommerce/precision.ts
510
+ function toDecimalString(n) {
511
+ const s = String(n);
512
+ if (!s.includes("e") && !s.includes("E")) return s;
513
+ return n.toFixed(20);
514
+ }
515
+ function roundHalfUp(value, precision) {
516
+ if (!Number.isFinite(value) || value === 0) return value;
517
+ const sign = value < 0 ? -1 : 1;
518
+ const abs = Math.abs(value);
519
+ const factor = Math.pow(10, precision);
520
+ const shifted = abs * factor;
521
+ let result = Math.floor(shifted + 0.5);
522
+ const str = toDecimalString(abs);
523
+ const dot = str.indexOf(".");
524
+ if (dot !== -1) {
525
+ const decimals = str.slice(dot + 1);
526
+ if (precision < decimals.length && decimals[precision] === "5") {
527
+ const rest = decimals.slice(precision + 1);
528
+ if (rest === "" || /^0*$/.test(rest)) {
529
+ result = Math.floor(shifted) + 1;
530
+ }
531
+ }
532
+ }
533
+ return sign * result / factor;
534
+ }
535
+ function roundHalfDown(value, precision) {
536
+ if (!Number.isFinite(value) || value === 0) return value;
537
+ const sign = value < 0 ? -1 : 1;
538
+ const abs = Math.abs(value);
539
+ const factor = Math.pow(10, precision);
540
+ const shifted = abs * factor;
541
+ let result = Math.floor(shifted + 0.5);
542
+ const str = toDecimalString(abs);
543
+ const dot = str.indexOf(".");
544
+ if (dot !== -1) {
545
+ const decimals = str.slice(dot + 1);
546
+ if (precision < decimals.length && decimals[precision] === "5") {
547
+ const rest = decimals.slice(precision + 1);
548
+ if (rest === "" || /^0*$/.test(rest)) {
549
+ result = Math.floor(shifted);
550
+ }
551
+ }
552
+ }
553
+ return sign * result / factor;
554
+ }
555
+ function getRoundingPrecision(dp) {
556
+ return Math.max(dp + 2, 6);
557
+ }
558
+ function addNumberPrecision(value, dp, round = true) {
559
+ const factor = Math.pow(10, dp);
560
+ const result = value * factor;
561
+ const roundingPrecision = getRoundingPrecision(dp);
562
+ const roundPrecision = round ? roundingPrecision - dp : roundingPrecision;
563
+ return roundHalfUp(result, roundPrecision);
564
+ }
565
+ function removeNumberPrecision(value, dp) {
566
+ return value / Math.pow(10, dp);
567
+ }
568
+ function roundTaxTotal(value, dp, pricesIncludeTax, precision) {
569
+ const p = precision ?? dp;
570
+ return pricesIncludeTax ? roundHalfDown(value, p) : roundHalfUp(value, p);
571
+ }
572
+
573
+ // src/tax/woocommerce/sum-taxes.ts
574
+ function sumTaxTotals(taxes) {
575
+ if (taxes.length === 0) return 0;
576
+ let result;
577
+ for (const tax of taxes) {
578
+ const current = tax.total;
579
+ if (current !== void 0) result = result === void 0 ? current : result + current;
580
+ }
581
+ return result;
582
+ }
583
+ function sumTaxes({ taxes }) {
584
+ const sum = sumTaxTotals(taxes);
585
+ return sum;
586
+ }
587
+ function sumItemizedTaxes({ taxes }) {
588
+ const groupedTaxes = /* @__PURE__ */ Object.create(null);
589
+ for (const tax of taxes.flat()) {
590
+ (groupedTaxes[tax.id] ??= []).push(tax);
591
+ }
592
+ return Object.entries(groupedTaxes).map(([id, itemized]) => ({
593
+ id: Number(id),
594
+ // groupBy converts the key to a string
595
+ total: sumTaxes({ taxes: itemized })
596
+ }));
597
+ }
598
+
599
+ // src/tax/woocommerce/calculate-taxes.ts
600
+ function calcInclusiveTax({
601
+ amount,
602
+ rates
603
+ }) {
604
+ const taxes = [];
605
+ const compoundRates = [];
606
+ const regularRates = [];
607
+ let nonCompoundAmount = amount;
608
+ rates.forEach((_rate) => {
609
+ const { id, rate, compound } = _rate;
610
+ if (compound) {
611
+ compoundRates.push({ id, rate: Number(rate) });
612
+ } else {
613
+ regularRates.push({ id, rate: Number(rate) });
614
+ }
615
+ });
616
+ compoundRates.reverse();
617
+ compoundRates.forEach((compoundRate) => {
618
+ const { id, rate } = compoundRate;
619
+ const total = nonCompoundAmount - nonCompoundAmount / (1 + rate / 100);
620
+ taxes.push({ id, total });
621
+ nonCompoundAmount -= total;
622
+ });
623
+ const regularTaxRate = 1 + regularRates.reduce((sum, regularRate, index) => index === 0 ? regularRate.rate / 100 : sum + regularRate.rate / 100, 0);
624
+ regularRates.forEach((regularRate) => {
625
+ const { id, rate } = regularRate;
626
+ const theRate = rate / 100 / regularTaxRate;
627
+ const netPrice = amount - theRate * nonCompoundAmount;
628
+ const total = amount - netPrice;
629
+ taxes.push({ id, total });
630
+ });
631
+ return taxes;
632
+ }
633
+ function calcExclusiveTax({
634
+ amount,
635
+ rates
636
+ }) {
637
+ const taxes = [];
638
+ rates.forEach((_rate) => {
639
+ const { id, rate, compound } = _rate;
640
+ if (!compound) {
641
+ const total = amount * (Number(rate) / 100);
642
+ taxes.push({ id, total });
643
+ }
644
+ });
645
+ let preCompoundTotal = sumTaxes({ taxes });
646
+ rates.forEach((_rate) => {
647
+ const { id, rate, compound } = _rate;
648
+ if (compound) {
649
+ const thePriceIncTax = amount + preCompoundTotal;
650
+ const total = thePriceIncTax * (Number(rate) / 100);
651
+ taxes.push({ id, total });
652
+ preCompoundTotal = sumTaxes({ taxes });
653
+ }
654
+ });
655
+ return taxes;
656
+ }
657
+ function calculateTaxes({
658
+ amount,
659
+ rates,
660
+ amountIncludesTax,
661
+ dp = 2,
662
+ perRatePrecision
663
+ }) {
664
+ const sortKey = (rate) => typeof rate.priority === "number" ? rate.priority : rate.order;
665
+ const sortedRates = [...rates].sort((a, b) => {
666
+ if (sortKey(a) !== sortKey(b)) return sortKey(a) - sortKey(b);
667
+ const aCountry = a.country || "";
668
+ const bCountry = b.country || "";
669
+ if (aCountry !== "" !== (bCountry !== "")) return aCountry !== "" ? -1 : 1;
670
+ const aState = a.state || "";
671
+ const bState = b.state || "";
672
+ if (aState !== "" !== (bState !== "")) return aState !== "" ? -1 : 1;
673
+ return a.id - b.id;
674
+ });
675
+ const roundingPrecision = perRatePrecision ?? dp + getRoundingPrecision(dp);
676
+ const normalizedAmount = removeNumberPrecision(addNumberPrecision(amount, dp), dp);
677
+ const taxes = amountIncludesTax ? calcInclusiveTax({ amount: normalizedAmount, rates: sortedRates }) : calcExclusiveTax({ amount: normalizedAmount, rates: sortedRates });
678
+ const roundRate = (value) => perRatePrecision === void 0 ? roundHalfUp(value, roundingPrecision) : roundHalfUp(Number(value.toPrecision(15)), roundingPrecision);
679
+ const roundedItemizedTaxes = taxes.map((tax) => ({
680
+ id: tax.id,
681
+ total: roundRate(tax.total)
682
+ }));
683
+ const total = sumTaxes({ taxes: roundedItemizedTaxes });
684
+ return {
685
+ total: roundHalfUp(total, roundingPrecision),
686
+ taxes: roundedItemizedTaxes
687
+ };
688
+ }
689
+
690
+ // src/tax/woocommerce/filter-tax-rates.ts
691
+ function normalizePostcode(postcode) {
692
+ return String(postcode ?? "").replace(/\s+/g, "").toUpperCase();
693
+ }
694
+ function getMatchingPostcodes(pattern) {
695
+ if (pattern.includes("...")) {
696
+ const [start, end] = pattern.split("...").map(normalizePostcode);
697
+ let current = parseInt(start, 10);
698
+ const last = parseInt(end, 10);
699
+ const matches = [];
700
+ while (current <= last) {
701
+ matches.push(current.toString());
702
+ current++;
703
+ }
704
+ return matches;
705
+ } else if (pattern.endsWith("*")) {
706
+ return [pattern.slice(0, -1)];
707
+ } else {
708
+ return [normalizePostcode(pattern)];
709
+ }
710
+ }
711
+ function postcodePatternMatches(normalizedPostcode, pattern) {
712
+ const matchingPostcodes = getMatchingPostcodes(pattern);
713
+ return matchingPostcodes.some(
714
+ (pc) => pattern.endsWith("*") ? normalizedPostcode.startsWith(pc) : pc === normalizedPostcode
715
+ );
716
+ }
717
+ function postcodeMatcher(postcode, patterns) {
718
+ const normalizedPostcode = normalizePostcode(postcode);
719
+ return patterns.some((pattern) => postcodePatternMatches(normalizedPostcode, pattern));
720
+ }
721
+ function compareTaxRates(rate1, rate2, matchedCounts) {
722
+ const priority1 = rate1.priority ?? 0;
723
+ const priority2 = rate2.priority ?? 0;
724
+ if (priority1 !== priority2) {
725
+ return priority1 < priority2 ? -1 : 1;
726
+ }
727
+ const country1 = rate1.country ?? "";
728
+ const country2 = rate2.country ?? "";
729
+ if (country1 !== country2) {
730
+ if (country1 === "") {
731
+ return 1;
732
+ }
733
+ if (country2 === "") {
734
+ return -1;
735
+ }
736
+ return country1 > country2 ? 1 : -1;
737
+ }
738
+ const state1 = rate1.state ?? "";
739
+ const state2 = rate2.state ?? "";
740
+ if (state1 !== state2) {
741
+ if (state1 === "") {
742
+ return 1;
743
+ }
744
+ if (state2 === "") {
745
+ return -1;
746
+ }
747
+ return state1 > state2 ? 1 : -1;
748
+ }
749
+ const postcodeCount1 = matchedCounts.get(rate1)?.postcodes ?? 0;
750
+ const postcodeCount2 = matchedCounts.get(rate2)?.postcodes ?? 0;
751
+ if (postcodeCount1 !== postcodeCount2) {
752
+ return postcodeCount1 < postcodeCount2 ? 1 : -1;
753
+ }
754
+ const cityCount1 = matchedCounts.get(rate1)?.cities ?? 0;
755
+ const cityCount2 = matchedCounts.get(rate2)?.cities ?? 0;
756
+ if (cityCount1 !== cityCount2) {
757
+ return cityCount1 < cityCount2 ? 1 : -1;
758
+ }
759
+ const id1 = rate1.id ?? 0;
760
+ const id2 = rate2.id ?? 0;
761
+ if (id1 === id2) {
762
+ return 0;
763
+ }
764
+ return id1 < id2 ? -1 : 1;
765
+ }
766
+ function filterTaxRates(taxRates, country = "", state = "", postcode = "", city = "") {
767
+ const taxRatesByClass = /* @__PURE__ */ Object.create(null);
768
+ for (const rate of taxRates) {
769
+ (taxRatesByClass[rate.class] ??= []).push(rate);
770
+ }
771
+ const normalizedPostcode = normalizePostcode(postcode);
772
+ const filteredTaxRatesByClass = Object.values(taxRatesByClass).map((taxRatesInClass) => {
773
+ const cityUpperCase = city.toUpperCase();
774
+ const matchedCounts = new Map(
775
+ taxRatesInClass.map((rate) => [
776
+ rate,
777
+ {
778
+ postcodes: (rate.postcodes ?? []).filter(
779
+ (pattern) => postcodePatternMatches(normalizedPostcode, pattern)
780
+ ).length,
781
+ cities: (rate.cities ?? []).filter((c) => c.toUpperCase() === cityUpperCase).length
782
+ }
783
+ ])
784
+ );
785
+ const sortedTaxRates = [...taxRatesInClass].sort(
786
+ (rate1, rate2) => compareTaxRates(rate1, rate2, matchedCounts)
787
+ );
788
+ let foundMatchAtCurrentPriority = false;
789
+ return sortedTaxRates.filter((rate, index) => {
790
+ const countryMatch = !rate.country?.length || (rate.country ?? "").toUpperCase() === country.toUpperCase();
791
+ const stateMatch = !rate.state?.length || (rate.state ?? "").toUpperCase() === state.toUpperCase();
792
+ const postcodeMatch = !rate.postcodes?.length || postcodeMatcher(postcode, rate.postcodes ?? []);
793
+ const cityMatch = !rate.cities?.length || (rate.cities ?? []).map((city2) => city2.toUpperCase()).includes(cityUpperCase);
794
+ const isMatch = countryMatch && stateMatch && postcodeMatch && cityMatch;
795
+ const isNewPriority = index === 0 || sortedTaxRates[index - 1].priority !== rate.priority;
796
+ if (isNewPriority) {
797
+ foundMatchAtCurrentPriority = false;
798
+ }
799
+ if (isMatch && !foundMatchAtCurrentPriority) {
800
+ foundMatchAtCurrentPriority = true;
801
+ return true;
802
+ }
803
+ return false;
804
+ });
805
+ });
806
+ return filteredTaxRatesByClass.flat();
807
+ }
808
+
809
+ // src/tax/woocommerce/tax-class.ts
810
+ var STANDARD_TAX_CLASS = "standard";
811
+ function normalizeTaxClass(value) {
812
+ return value === "" || value === null || value === void 0 ? STANDARD_TAX_CLASS : value;
813
+ }
814
+ var NO_SHIPPING_TAX = null;
815
+ function resolveInheritedShippingTaxClass(activeLineItems, taxClassSlugs) {
816
+ const itemClasses = new Set(
817
+ activeLineItems.filter((item) => item.taxable).map((item) => normalizeTaxClass(item.tax_class))
818
+ );
819
+ if (itemClasses.size === 0) {
820
+ return activeLineItems.length === 0 ? STANDARD_TAX_CLASS : NO_SHIPPING_TAX;
821
+ }
822
+ if (itemClasses.has(STANDARD_TAX_CLASS)) return STANDARD_TAX_CLASS;
823
+ if (itemClasses.size === 1) return [...itemClasses][0];
824
+ const found = taxClassSlugs.find((slug) => itemClasses.has(normalizeTaxClass(slug)));
825
+ if (found !== void 0) return normalizeTaxClass(found);
826
+ if (taxClassSlugs.length === 0) return STANDARD_TAX_CLASS;
827
+ return NO_SHIPPING_TAX;
828
+ }
829
+ function taxClassFromWire(value) {
830
+ return value === "" || value === null || value === void 0 ? STANDARD_TAX_CLASS : value;
831
+ }
832
+ function taxClassToWire(value) {
833
+ return value === STANDARD_TAX_CLASS || value === null || value === void 0 ? "" : value;
834
+ }
472
835
  export {
473
836
  COMMANDS_PATH,
474
837
  ConnectorProvider,
@@ -497,6 +860,7 @@ export {
497
860
  moneyFromMajor,
498
861
  moneyToMajor,
499
862
  parseInfoCapabilities,
863
+ parseLineTax,
500
864
  parseTaxRounding,
501
865
  resolveCapabilities,
502
866
  resolvePrice,
@@ -508,5 +872,6 @@ export {
508
872
  useStockOverlaid,
509
873
  useStockOverlayAsOf,
510
874
  useTraitContext,
511
- withStockOverlay
875
+ withStockOverlay,
876
+ woocommerce_exports as woocommerceTax
512
877
  };
@@ -1,3 +1,5 @@
1
+ import "../chunk-MLKGABMK.js";
2
+
1
3
  // src/rxdb/read-fresh.ts
2
4
  import { clone } from "rxdb";
3
5
  async function readFresh(collection, query) {
@@ -1,5 +1,5 @@
1
- import { e as CommandError, l as OrderCreatePayload, d as CommandEnvelope, q as RegisterCommandEnvelope, A as AnyCommandEnvelope, f as CommandResult, B as BatchTooLargeBody, c as CommandBatchResponse, C as CommandWarning, r as RegisterCommandResult } from '../commands-BW4YYgRG.js';
2
- export { M as MAX_COMMANDS_PER_BATCH, O as OrderCreateDisplay, n as OrderCreateTaxRate } from '../commands-BW4YYgRG.js';
1
+ import { e as CommandError, l as OrderCreatePayload, d as CommandEnvelope, q as RegisterCommandEnvelope, A as AnyCommandEnvelope, f as CommandResult, B as BatchTooLargeBody, c as CommandBatchResponse, C as CommandWarning, r as RegisterCommandResult } from '../commands-xE2xMmC_.js';
2
+ export { M as MAX_COMMANDS_PER_BATCH, O as OrderCreateDisplay, n as OrderCreateTaxRate } from '../commands-xE2xMmC_.js';
3
3
 
4
4
  /** ISO 4217 minor-unit exponent as resolved by Intl (which rejects malformed codes); depends on the runtime's ICU data. */
5
5
  declare function currencyDecimals(currency: string): number;
@@ -26,7 +26,7 @@ declare function commandFingerprint(envelope: {
26
26
  declare function payloadShapeErrors(payload: unknown): string[];
27
27
  /** Length-bound errors of an order.create payload, e.g. ['lines[0].title: expected at most 255
28
28
  * characters']; [] when every string is within its bound, at most ten. Bounds in UTF-16 code units:
29
- * `customer.email` 254, every other string 255 (`customerId` and `sessionId` keep theirs in
29
+ * `customer.email` 254, v5 ids 36 and class/sku/method 64, other strings 255 (`customerId` and `sessionId` keep theirs in
30
30
  * payloadShapeErrors); only strings are checked. A plugin calls it through precheckCommand, after
31
31
  * its replay lookup, so a bound tightened later never turns an applied command's resend into
32
32
  * `invalid_payload`. */
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  MAX_COMMANDS_PER_BATCH
3
3
  } from "../chunk-C4PWPOKO.js";
4
+ import "../chunk-MLKGABMK.js";
4
5
 
5
6
  // src/server/money.ts
6
7
  function currencyDecimals(currency) {
@@ -74,6 +75,7 @@ function payloadShapeErrors(payload) {
74
75
  check(object(item), path, "an object");
75
76
  if (!object(item)) continue;
76
77
  for (const key of isLines ? ["clientLineId", "variantId"] : ["clientPaymentId", "method"]) {
78
+ if (key === "variantId" && item.custom !== void 0 && item.variantId === void 0) continue;
77
79
  check(typeof item[key] === "string", `${path}.${key}`, "a string");
78
80
  }
79
81
  const optionalString = isLines ? "title" : "reference";
@@ -115,6 +117,35 @@ function payloadShapeErrors(payload) {
115
117
  for (const field of ["registerId", "cashierRef", "locationId"]) {
116
118
  if (payload[field] !== void 0) check(typeof payload[field] === "string", field, "a string");
117
119
  }
120
+ for (const field of ["fees", "shipping", "lines"]) {
121
+ const items = payload[field];
122
+ if (items === void 0 || field === "lines" && !Array.isArray(items)) continue;
123
+ check(Array.isArray(items), field, "an array");
124
+ if (!Array.isArray(items)) continue;
125
+ const id = field === "fees" ? "clientFeeId" : "clientShippingId";
126
+ const seen = /* @__PURE__ */ new Set();
127
+ items.forEach((entry, index) => {
128
+ const custom = field === "lines";
129
+ const item = custom && object(entry) ? entry.custom : entry;
130
+ const path = `${field}[${index}]${custom ? ".custom" : ""}`;
131
+ if (custom && (!object(entry) || item === void 0)) return;
132
+ check(object(item), path, "an object");
133
+ if (!object(item)) return;
134
+ const keys = custom ? ["name", "sku", "taxClass", "taxStatus"] : [id, "name", "amountMinor", "taxMinor", "taxStatus", "taxClass", ...field === "shipping" ? ["methodId"] : []];
135
+ for (const key of Object.keys(item)) check(keys.includes(key), `${path}.${key}`, "no unknown key");
136
+ check(typeof item.name === "string" && item.name.length > 0, `${path}.name`, "a non-empty string");
137
+ check(item.taxStatus === "taxable" || item.taxStatus === "none", `${path}.taxStatus`, "taxable or none");
138
+ for (const key of keys.filter((key2) => ["sku", "taxClass", "methodId"].includes(key2))) {
139
+ if (item[key] !== void 0) check(typeof item[key] === "string", `${path}.${key}`, "a string");
140
+ }
141
+ if (!custom) {
142
+ check(typeof item[id] === "string" && item[id].length > 0, `${path}.${id}`, "a non-empty string");
143
+ check(!seen.has(item[id]), `${path}.${id}`, `no duplicate ${id}`);
144
+ seen.add(item[id]);
145
+ for (const key of ["amountMinor", "taxMinor"]) check(Number.isSafeInteger(item[key]) && item[key] >= 0, `${path}.${key}`, "a safe integer >= 0");
146
+ }
147
+ });
148
+ }
118
149
  for (const [value, path] of payloadStrings(payload)) check(!value.includes("\0"), path, "no NUL character");
119
150
  return errors;
120
151
  }
@@ -134,6 +165,20 @@ function payloadStrings(payload) {
134
165
  }
135
166
  });
136
167
  }
168
+ if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
169
+ if (object(line) && object(line.custom)) for (const key of ["name", "sku", "taxClass", "taxStatus"]) {
170
+ found.push([line.custom[key], `lines[${index}].custom.${key}`, key === "name" ? 255 : 64]);
171
+ }
172
+ });
173
+ for (const field of ["fees", "shipping"]) for (const prefix of ["", "display."]) {
174
+ const parent = prefix ? payload.display : payload;
175
+ const items = object(parent) ? parent[field] : void 0;
176
+ if (Array.isArray(items)) items.forEach((item, index) => {
177
+ if (object(item)) for (const key of prefix ? [field === "fees" ? "clientFeeId" : "clientShippingId"] : [field === "fees" ? "clientFeeId" : "clientShippingId", "name", "taxClass", "taxStatus", ...field === "shipping" ? ["methodId"] : []]) {
178
+ found.push([item[key], `${prefix}${field}[${index}].${key}`, key.startsWith("client") ? 36 : key === "name" ? 255 : 64]);
179
+ }
180
+ });
181
+ }
137
182
  if (object(payload.customer)) found.push([payload.customer.email, "customer.email", 254], [payload.customer.customerId, "customer.customerId", void 0]);
138
183
  found.push([payload.sessionId, "sessionId", void 0]);
139
184
  return found.filter((entry) => typeof entry[0] === "string");
@@ -155,7 +200,7 @@ function fiscalFiguresErrors(payload) {
155
200
  for (const key of keys) check(Number.isSafeInteger(value[key]), `${path}.${key}`, "a safe integer");
156
201
  };
157
202
  const { display, taxByRate } = payload;
158
- if (object(display, "display", ["currency", "exponent", "taxInclusive", "subtotalMinor", "discountMinor", "taxMinor", "totalMinor", "orderDiscountMinor", "lines"])) {
203
+ if (object(display, "display", ["currency", "exponent", "taxInclusive", "subtotalMinor", "discountMinor", "taxMinor", "totalMinor", "orderDiscountMinor", "lines", "fees", "shipping"])) {
159
204
  check(typeof display.currency === "string", "display.currency", "a string");
160
205
  check(Number.isInteger(display.exponent) && display.exponent >= 0, "display.exponent", "an integer >= 0");
161
206
  check(typeof display.taxInclusive === "boolean", "display.taxInclusive", "a boolean");
@@ -175,6 +220,28 @@ function fiscalFiguresErrors(payload) {
175
220
  money(discount, discountPath, ["amountMinor"]);
176
221
  });
177
222
  });
223
+ if (payload.fees?.length || payload.shipping?.length) check(display.taxInclusive === payload.pricesIncludeTax, "display.taxInclusive", "payload.pricesIncludeTax");
224
+ for (const field of ["fees", "shipping"]) {
225
+ const id = field === "fees" ? "clientFeeId" : "clientShippingId";
226
+ const amounts = new Map((payload[field] ?? []).map((entry) => [
227
+ "clientFeeId" in entry ? entry.clientFeeId : entry.clientShippingId,
228
+ entry.amountMinor
229
+ ]));
230
+ const rows = display[field];
231
+ if (rows !== void 0) check(Array.isArray(rows), `display.${field}`, "an array");
232
+ const seen2 = /* @__PURE__ */ new Set();
233
+ if (Array.isArray(rows)) rows.forEach((row, index) => {
234
+ const path = `display.${field}[${index}]`;
235
+ if (!object(row, path, [id, "amountMinor"])) return;
236
+ check(typeof row[id] === "string" && row[id].length > 0, `${path}.${id}`, "a non-empty string");
237
+ money(row, path, ["amountMinor"]);
238
+ check(amounts.has(row[id]), `${path}.${id}`, `a payload.${field}[].${id}`);
239
+ check(!seen2.has(row[id]), `${path}.${id}`, `no duplicate ${id}`);
240
+ seen2.add(row[id]);
241
+ if (amounts.has(row[id])) check(row.amountMinor === amounts.get(row[id]), `${path}.amountMinor`, `the payload.${field} amountMinor`);
242
+ });
243
+ for (const key of amounts.keys()) check(seen2.has(key), `display.${field}`, `a row for ${id} ${key}`);
244
+ }
178
245
  }
179
246
  check(Array.isArray(taxByRate), "taxByRate", "an array");
180
247
  if (Array.isArray(taxByRate)) taxByRate.forEach((rate, index) => {
@@ -280,7 +347,20 @@ function precheckCommand(envelope, supported) {
280
347
  const payload = command.payload;
281
348
  const { display, taxByRate, sessionId } = payload;
282
349
  const v3 = command.version >= 3;
283
- const versionError = command.version === 2 && discountMinor === void 0 ? "version 2 requires discountMinor" : command.version === 1 && discounted ? "discountMinor requires version 2" : !v3 && (display !== void 0 || taxByRate !== void 0) ? "display and taxByRate require version 3" : !v3 && sessionId !== void 0 ? "sessionId requires version 3" : !v3 && payload.customer?.customerId !== void 0 ? "customerId requires version 3" : v3 && display !== void 0 !== (taxByRate !== void 0) ? "display and taxByRate must both be present or both absent" : void 0;
350
+ const v5Fields = ["fees", "shipping"].filter((field) => payload[field] !== void 0);
351
+ if (Array.isArray(lines)) lines.forEach((line, index) => {
352
+ if (line?.custom !== void 0) v5Fields.push(`lines[${index}].custom`);
353
+ });
354
+ for (const field of ["fees", "shipping"]) if (display?.[field] !== void 0) v5Fields.push(`display.${field}`);
355
+ let versionError = command.version < 5 && v5Fields.length ? v5Fields.map((field) => `${field} requires version 5`).join("; ") : command.version === 2 && discountMinor === void 0 ? "version 2 requires discountMinor" : command.version === 1 && discounted ? "discountMinor requires version 2" : !v3 && (display !== void 0 || taxByRate !== void 0) ? "display and taxByRate require version 3" : !v3 && sessionId !== void 0 ? "sessionId requires version 3" : !v3 && payload.customer?.customerId !== void 0 ? "customerId requires version 3" : v3 && display !== void 0 !== (taxByRate !== void 0) ? "display and taxByRate must both be present or both absent" : void 0;
356
+ if (!versionError && Array.isArray(lines)) for (const [index, line] of lines.entries()) {
357
+ if (line?.custom === void 0 && (typeof line?.variantId !== "string" || !line.variantId.length)) {
358
+ versionError = `lines[${index}].variantId is required`;
359
+ } else if (command.version >= 5 && line?.custom !== void 0 && line.variantId !== void 0) {
360
+ versionError = `lines[${index}] has custom and variantId; a custom line has no variantId`;
361
+ }
362
+ if (versionError) break;
363
+ }
284
364
  if (versionError) {
285
365
  return { id: command.id, status: "rejected", error: { code: "invalid_payload", message: versionError } };
286
366
  }
@@ -288,7 +368,8 @@ function precheckCommand(envelope, supported) {
288
368
  if (bounds.length) {
289
369
  return { id: command.id, status: "rejected", error: { code: "invalid_payload", message: bounds.slice(0, 10).join("; ") } };
290
370
  }
291
- const errors = v3 && display !== void 0 && taxByRate !== void 0 && payloadShapeErrors(payload).length === 0 ? fiscalFiguresErrors(payload) : [];
371
+ const shape = payloadShapeErrors(payload);
372
+ const errors = command.version >= 5 && shape.length ? shape : v3 && display !== void 0 && taxByRate !== void 0 && shape.length === 0 ? fiscalFiguresErrors(payload) : [];
292
373
  if (errors.length) {
293
374
  return { id: command.id, status: "rejected", error: { code: "invalid_payload", message: errors.slice(0, 10).join("; ") } };
294
375
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/core",
3
- "version": "3.2.1",
3
+ "version": "3.4.0",
4
4
  "type": "module",
5
5
  "description": "Core interfaces, traits, and context providers for Tally UI",
6
6
  "main": "./dist/index.js",
package/src/index.ts CHANGED
@@ -26,7 +26,7 @@ export type {
26
26
  } from './types';
27
27
  export type { SignInResult, ServerCapabilities, TaxRounding } from './types/connector';
28
28
  export type { CatalogueReconcileAdapter, CatalogueReconcileEntry } from './types/reconcile';
29
- export { parseInfoCapabilities, parseTaxRounding, resolveCapabilities } from './types/connector';
29
+ export { parseInfoCapabilities, parseTaxRounding, parseLineTax, resolveCapabilities } from './types/connector';
30
30
  export { SignInError } from './sign-in';
31
31
  export { ConnectorUnauthorizedError } from './unauthorized';
32
32
  export { isRxdbRemoteVersionMismatch } from './rxdb-remote-version-mismatch';
@@ -74,3 +74,4 @@ export {
74
74
  useStockOverlayAsOf,
75
75
  } from './context/connector-context';
76
76
  export type { ConnectorProviderProps } from './context/connector-context';
77
+ export * as woocommerceTax from './tax/woocommerce';
@@ -87,15 +87,29 @@ export function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCom
87
87
  || (Array.isArray(lines) && lines.some(line => (line as { discountMinor?: unknown } | null)?.discountMinor !== undefined))
88
88
  const payload = command.payload as OrderCreatePayloadV3
89
89
  const { display, taxByRate, sessionId } = payload
90
- // Version 4 carries version 3's fields (#286); only what discountMinor means changes.
90
+ // Versions 4 and 5 carry version 3's fields, with tax-exclusive discountMinor (#286).
91
91
  const v3 = command.version >= 3
92
- const versionError = command.version === 2 && discountMinor === undefined ? 'version 2 requires discountMinor'
92
+ const v5Fields = ['fees', 'shipping'].filter(field => payload[field as 'fees' | 'shipping'] !== undefined)
93
+ if (Array.isArray(lines)) lines.forEach((line, index) => {
94
+ if (line?.custom !== undefined) v5Fields.push(`lines[${index}].custom`)
95
+ })
96
+ for (const field of ['fees', 'shipping'] as const) if (display?.[field] !== undefined) v5Fields.push(`display.${field}`)
97
+ let versionError = command.version < 5 && v5Fields.length ? v5Fields.map(field => `${field} requires version 5`).join('; ')
98
+ : command.version === 2 && discountMinor === undefined ? 'version 2 requires discountMinor'
93
99
  : command.version === 1 && discounted ? 'discountMinor requires version 2'
94
100
  : !v3 && (display !== undefined || taxByRate !== undefined) ? 'display and taxByRate require version 3'
95
101
  : !v3 && sessionId !== undefined ? 'sessionId requires version 3'
96
102
  : !v3 && payload.customer?.customerId !== undefined ? 'customerId requires version 3'
97
103
  : v3 && (display !== undefined) !== (taxByRate !== undefined) ? 'display and taxByRate must both be present or both absent'
98
104
  : undefined
105
+ if (!versionError && Array.isArray(lines)) for (const [index, line] of lines.entries()) {
106
+ if (line?.custom === undefined && (typeof line?.variantId !== 'string' || !line.variantId.length)) {
107
+ versionError = `lines[${index}].variantId is required`
108
+ } else if (command.version >= 5 && line?.custom !== undefined && line.variantId !== undefined) {
109
+ versionError = `lines[${index}] has custom and variantId; a custom line has no variantId`
110
+ }
111
+ if (versionError) break
112
+ }
99
113
  if (versionError) {
100
114
  return { id: command.id, status: 'rejected', error: { code: 'invalid_payload', message: versionError } }
101
115
  }
@@ -103,8 +117,9 @@ export function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCom
103
117
  if (bounds.length) {
104
118
  return { id: command.id, status: 'rejected', error: { code: 'invalid_payload', message: bounds.slice(0, 10).join('; ') } }
105
119
  }
106
- const errors = v3 && display !== undefined && taxByRate !== undefined && payloadShapeErrors(payload).length === 0
107
- ? fiscalFiguresErrors(payload) : []
120
+ const shape = payloadShapeErrors(payload)
121
+ const errors = command.version >= 5 && shape.length ? shape
122
+ : v3 && display !== undefined && taxByRate !== undefined && shape.length === 0 ? fiscalFiguresErrors(payload) : []
108
123
  if (errors.length) {
109
124
  return { id: command.id, status: 'rejected', error: { code: 'invalid_payload', message: errors.slice(0, 10).join('; ') } }
110
125
  }