@tallyui/core 3.7.1 → 3.9.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
@@ -48,6 +48,7 @@ function parseInfoCapabilities(body, warn) {
48
48
  }
49
49
  const { contracts, taxRounding, lineTax } = body;
50
50
  const register = maxVersion(contracts?.register);
51
+ const orderRefund = maxVersion(contracts?.["order.refund"]);
51
52
  const rounding = parseTaxRounding(taxRounding);
52
53
  if (taxRounding !== void 0 && rounding === void 0) {
53
54
  warn?.(`malformed taxRounding: rounding is unknown, so settings wait: ${JSON.stringify(taxRounding)}`);
@@ -56,6 +57,7 @@ function parseInfoCapabilities(body, warn) {
56
57
  const parsedLineTax = parseLineTax(lineTax, warn);
57
58
  return {
58
59
  orderCreate: maxVersion(contracts?.["order.create"]) ?? 1,
60
+ ...orderRefund !== void 0 ? { orderRefund } : {},
59
61
  ...register !== void 0 ? { register } : {},
60
62
  ...rounding ? { taxRounding: rounding } : {},
61
63
  ...parsedLineTax ? { lineTax: parsedLineTax } : {}
@@ -575,6 +577,9 @@ function roundTaxTotal(value, dp, pricesIncludeTax, precision) {
575
577
  const p = precision ?? dp;
576
578
  return pricesIncludeTax ? roundHalfDown(value, p) : roundHalfUp(value, p);
577
579
  }
580
+ function roundDiscount(value, precision) {
581
+ return roundHalfDown(value, precision);
582
+ }
578
583
 
579
584
  // src/tax/woocommerce/sum-taxes.ts
580
585
  function sumTaxTotals(taxes) {
@@ -838,6 +843,911 @@ function taxClassFromWire(value) {
838
843
  function taxClassToWire(value) {
839
844
  return value === STANDARD_TAX_CLASS || value === null || value === void 0 ? "" : value;
840
845
  }
846
+
847
+ // src/coupons/woocommerce/index.ts
848
+ var woocommerce_exports2 = {};
849
+ __export(woocommerce_exports2, {
850
+ calculateOrderTotals: () => calculateOrderTotals,
851
+ enrichCategoriesWithAncestors: () => enrichCategoriesWithAncestors,
852
+ recalculateCoupons: () => recalculateCoupons,
853
+ toCouponConfigs: () => toCouponConfigs,
854
+ validateCoupon: () => validateCoupon
855
+ });
856
+
857
+ // src/coupons/woocommerce/pos-data.ts
858
+ var POS_DATA_META_KEY = "_woocommerce_pos_data";
859
+ var isPosData = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
860
+ var getMetaDataValueByKey = (metaData, key) => {
861
+ if (!Array.isArray(metaData)) {
862
+ return;
863
+ }
864
+ const meta = metaData.find((m) => m.key === key);
865
+ return meta ? meta.value : void 0;
866
+ };
867
+ var parsePosData = (item) => {
868
+ const value = getMetaDataValueByKey(item.meta_data, POS_DATA_META_KEY);
869
+ if (!value) {
870
+ return null;
871
+ }
872
+ if (isPosData(value)) {
873
+ return value;
874
+ }
875
+ if (typeof value !== "string") {
876
+ return null;
877
+ }
878
+ try {
879
+ const parsed = JSON.parse(value);
880
+ return isPosData(parsed) ? parsed : null;
881
+ } catch {
882
+ return null;
883
+ }
884
+ };
885
+ var getLineItemTaxStatus = (item) => {
886
+ const isValid = (value) => value === "taxable" || value === "none" || value === "shipping";
887
+ const topLevel = item?.tax_status;
888
+ if (isValid(topLevel)) {
889
+ return topLevel;
890
+ }
891
+ const posData = Array.isArray(item?.meta_data) ? parsePosData(item) : null;
892
+ const fromPosData = posData?.tax_status;
893
+ if (isValid(fromPosData)) {
894
+ return fromPosData;
895
+ }
896
+ return "taxable";
897
+ };
898
+
899
+ // src/coupons/woocommerce/helpers.ts
900
+ function getEligibleItems(items, restrictions) {
901
+ return items.filter((item) => {
902
+ if (restrictions.product_ids.length > 0 && !restrictions.product_ids.includes(item.product_id)) {
903
+ return false;
904
+ }
905
+ if (restrictions.excluded_product_ids.includes(item.product_id)) {
906
+ return false;
907
+ }
908
+ if (restrictions.product_categories.length > 0) {
909
+ const itemCategoryIds = item.categories.map((c) => c.id);
910
+ if (!restrictions.product_categories.some((catId) => itemCategoryIds.includes(catId))) {
911
+ return false;
912
+ }
913
+ }
914
+ if (restrictions.excluded_product_categories.length > 0) {
915
+ const itemCategoryIds = item.categories.map((c) => c.id);
916
+ if (restrictions.excluded_product_categories.some((catId) => itemCategoryIds.includes(catId))) {
917
+ return false;
918
+ }
919
+ }
920
+ if (restrictions.exclude_sale_items && item.on_sale) {
921
+ return false;
922
+ }
923
+ return true;
924
+ });
925
+ }
926
+ function enrichCategoriesWithAncestors(productCategories, categoryParentMap) {
927
+ if (categoryParentMap.size === 0) return productCategories;
928
+ const enriched = /* @__PURE__ */ new Map();
929
+ for (const [productId, categories] of productCategories) {
930
+ const allCategoryIds = /* @__PURE__ */ new Set();
931
+ for (const cat of categories) {
932
+ allCategoryIds.add(cat.id);
933
+ let parentId = categoryParentMap.get(cat.id);
934
+ while (parentId && parentId > 0 && !allCategoryIds.has(parentId)) {
935
+ allCategoryIds.add(parentId);
936
+ parentId = categoryParentMap.get(parentId);
937
+ }
938
+ }
939
+ enriched.set(
940
+ productId,
941
+ Array.from(allCategoryIds).map((id) => ({ id }))
942
+ );
943
+ }
944
+ return enriched;
945
+ }
946
+ function computeDiscountedLineItems(lineItems, allPerItemDiscounts, roundingPrecision = 6) {
947
+ if (allPerItemDiscounts.length === 0) return lineItems;
948
+ const hasLineIndex = allPerItemDiscounts.some((list) => list.some((e) => e.lineIndex != null));
949
+ if (hasLineIndex) {
950
+ const discountByLine = /* @__PURE__ */ new Map();
951
+ for (const perItemDiscounts of allPerItemDiscounts) {
952
+ for (const entry of perItemDiscounts) {
953
+ if (entry.lineIndex != null) {
954
+ discountByLine.set(
955
+ entry.lineIndex,
956
+ (discountByLine.get(entry.lineIndex) || 0) + entry.discount
957
+ );
958
+ }
959
+ }
960
+ }
961
+ if (discountByLine.size === 0) return lineItems;
962
+ return lineItems.map((item, idx) => {
963
+ const lineDiscount = discountByLine.get(idx);
964
+ if (!lineDiscount || lineDiscount <= 0) return item;
965
+ const currentTotal = parseFloat(item.total || "0");
966
+ if (currentTotal <= 0) return item;
967
+ const newTotal = Math.max(0, currentTotal - lineDiscount);
968
+ const ratio = currentTotal > 0 ? newTotal / currentTotal : 0;
969
+ const taxes = (item.taxes || []).map((tax) => ({
970
+ ...tax,
971
+ total: roundHalfUp(parseFloat(tax.total || "0") * ratio, roundingPrecision).toFixed(
972
+ roundingPrecision
973
+ )
974
+ }));
975
+ const newTotalTax = taxes.reduce((sum, tax) => sum + parseFloat(tax.total), 0);
976
+ return {
977
+ ...item,
978
+ total: String(roundHalfUp(newTotal, roundingPrecision)),
979
+ total_tax: String(roundHalfUp(newTotalTax, roundingPrecision)),
980
+ taxes
981
+ };
982
+ });
983
+ }
984
+ const discountMap = /* @__PURE__ */ new Map();
985
+ for (const perItemDiscounts of allPerItemDiscounts) {
986
+ for (const { product_id, discount } of perItemDiscounts) {
987
+ discountMap.set(product_id, (discountMap.get(product_id) || 0) + discount);
988
+ }
989
+ }
990
+ if (discountMap.size === 0) return lineItems;
991
+ const totalByProductId = /* @__PURE__ */ new Map();
992
+ for (const item of lineItems) {
993
+ const pid = item.product_id;
994
+ if (pid == null || !discountMap.has(pid)) continue;
995
+ totalByProductId.set(pid, (totalByProductId.get(pid) || 0) + parseFloat(item.total || "0"));
996
+ }
997
+ return lineItems.map((item) => {
998
+ const pid = item.product_id;
999
+ if (pid == null || !discountMap.has(pid)) return item;
1000
+ const totalDiscountForProduct = discountMap.get(pid);
1001
+ if (totalDiscountForProduct <= 0) return item;
1002
+ const currentTotal = parseFloat(item.total || "0");
1003
+ if (currentTotal <= 0) return item;
1004
+ const productTotal = totalByProductId.get(pid) || currentTotal;
1005
+ const itemDiscount = totalDiscountForProduct * (currentTotal / productTotal);
1006
+ const newTotal = Math.max(0, currentTotal - itemDiscount);
1007
+ const ratio = currentTotal > 0 ? newTotal / currentTotal : 0;
1008
+ const taxes = (item.taxes || []).map((tax) => ({
1009
+ ...tax,
1010
+ total: roundHalfUp(parseFloat(tax.total || "0") * ratio, roundingPrecision).toFixed(
1011
+ roundingPrecision
1012
+ )
1013
+ }));
1014
+ const newTotalTax = taxes.reduce((sum, tax) => sum + parseFloat(tax.total), 0);
1015
+ return {
1016
+ ...item,
1017
+ total: String(roundHalfUp(newTotal, roundingPrecision)),
1018
+ total_tax: String(roundHalfUp(newTotalTax, roundingPrecision)),
1019
+ taxes
1020
+ };
1021
+ });
1022
+ }
1023
+ function calculateCouponDiscountTaxSplit(perItemDiscounts, lineItems, taxRates, options) {
1024
+ const pricesIncludeTax = options?.pricesIncludeTax ?? false;
1025
+ const taxRoundAtSubtotal = options?.taxRoundAtSubtotal ?? false;
1026
+ const dp = options?.dp ?? 2;
1027
+ let totalDiscount = 0;
1028
+ let totalDiscountTax = 0;
1029
+ for (const entry of perItemDiscounts) {
1030
+ if (entry.discount <= 0) continue;
1031
+ const lineItem = entry.lineIndex != null ? lineItems[entry.lineIndex] : lineItems.find((item) => item.product_id === entry.product_id);
1032
+ const taxStatus = getLineItemTaxStatus(lineItem);
1033
+ if (taxStatus !== "taxable") {
1034
+ totalDiscount += entry.discount;
1035
+ continue;
1036
+ }
1037
+ const taxClass = normalizeTaxClass(lineItem?.tax_class);
1038
+ const applicableRates = taxRates.filter((r) => r.class === taxClass);
1039
+ if (applicableRates.length > 0) {
1040
+ const taxResult = calculateTaxes({
1041
+ amount: entry.discount,
1042
+ rates: applicableRates,
1043
+ amountIncludesTax: false,
1044
+ dp
1045
+ });
1046
+ const perItemTax = taxRoundAtSubtotal ? taxResult.total : roundTaxTotal(taxResult.total, dp, pricesIncludeTax);
1047
+ totalDiscount += entry.discount;
1048
+ totalDiscountTax += perItemTax;
1049
+ } else {
1050
+ totalDiscount += entry.discount;
1051
+ }
1052
+ }
1053
+ return {
1054
+ discount: String(roundHalfUp(totalDiscount, 6)),
1055
+ discount_tax: String(roundHalfUp(totalDiscountTax, 6))
1056
+ };
1057
+ }
1058
+
1059
+ // src/coupons/woocommerce/discount.ts
1060
+ function calculateCouponDiscount(config, items, dp = 2) {
1061
+ const amount = parseFloat(config.amount) || 0;
1062
+ if (amount === 0 || items.length === 0) {
1063
+ return { totalDiscount: 0, perItem: [] };
1064
+ }
1065
+ if (config.discount_type === "fixed_cart" && config.exclude_sale_items && items.some((item) => item.on_sale)) {
1066
+ return { totalDiscount: 0, perItem: [] };
1067
+ }
1068
+ const eligible = getEligibleItems(items, {
1069
+ product_ids: config.product_ids,
1070
+ excluded_product_ids: config.excluded_product_ids,
1071
+ product_categories: config.product_categories,
1072
+ excluded_product_categories: config.excluded_product_categories,
1073
+ exclude_sale_items: config.exclude_sale_items
1074
+ });
1075
+ if (eligible.length === 0) {
1076
+ return { totalDiscount: 0, perItem: [] };
1077
+ }
1078
+ switch (config.discount_type) {
1079
+ case "percent":
1080
+ return calculatePercentDiscount(amount, eligible, config.limit_usage_to_x_items, dp);
1081
+ case "fixed_cart":
1082
+ return calculateFixedCartDiscount(amount, items, dp);
1083
+ case "fixed_product":
1084
+ return calculateFixedProductDiscount(amount, eligible, config.limit_usage_to_x_items, dp);
1085
+ default:
1086
+ return { totalDiscount: 0, perItem: [] };
1087
+ }
1088
+ }
1089
+ function selectTopPricedUnits(items, limitToXItems) {
1090
+ if (limitToXItems === null || limitToXItems <= 0) {
1091
+ return items;
1092
+ }
1093
+ const expanded = [];
1094
+ items.forEach((item, itemIndex) => {
1095
+ for (let i = 0; i < item.quantity; i++) {
1096
+ expanded.push({ item, itemIndex });
1097
+ }
1098
+ });
1099
+ expanded.sort((a, b) => b.item.price - a.item.price);
1100
+ const quantityMap = /* @__PURE__ */ new Map();
1101
+ for (const { itemIndex } of expanded.slice(0, limitToXItems)) {
1102
+ quantityMap.set(itemIndex, (quantityMap.get(itemIndex) || 0) + 1);
1103
+ }
1104
+ return items.reduce((acc, item, itemIndex) => {
1105
+ const qty = quantityMap.get(itemIndex);
1106
+ if (qty) acc.push({ ...item, quantity: qty });
1107
+ return acc;
1108
+ }, []);
1109
+ }
1110
+ function calculatePercentDiscount(percent, items, limitToXItems, dp) {
1111
+ const targetItems = selectTopPricedUnits(items, limitToXItems);
1112
+ const itemDiscountsCents = [];
1113
+ let totalDiscountCents = 0;
1114
+ for (let i = 0; i < targetItems.length; i++) {
1115
+ const item = targetItems[i];
1116
+ const itemTotalCents = addNumberPrecision(item.price * item.quantity, dp);
1117
+ const discountCents = Math.floor(itemTotalCents * (percent / 100));
1118
+ const cappedCents = Math.min(discountCents, itemTotalCents);
1119
+ itemDiscountsCents.push({ item, discountCents: cappedCents, index: i });
1120
+ totalDiscountCents += cappedCents;
1121
+ }
1122
+ const exactTotalCents = targetItems.reduce((sum, item) => {
1123
+ const itemTotalCents = addNumberPrecision(item.price * item.quantity, dp);
1124
+ return sum + itemTotalCents * (percent / 100);
1125
+ }, 0);
1126
+ const expectedTotalCents = roundDiscount(exactTotalCents, 0);
1127
+ applyCouponRemainder(itemDiscountsCents, expectedTotalCents - totalDiscountCents, dp);
1128
+ const perItem = [];
1129
+ let totalDiscount = 0;
1130
+ for (const { item, discountCents } of itemDiscountsCents) {
1131
+ const discount = removeNumberPrecision(discountCents, dp);
1132
+ perItem.push({ product_id: item.product_id, discount, lineIndex: item.lineIndex });
1133
+ totalDiscount += discount;
1134
+ }
1135
+ return { totalDiscount: roundDiscount(totalDiscount, dp), perItem };
1136
+ }
1137
+ function calculateFixedCartDiscount(amount, items, dp) {
1138
+ const discountableItems = items.filter((item) => item.price > 0);
1139
+ if (discountableItems.length === 0) {
1140
+ return { totalDiscount: 0, perItem: [] };
1141
+ }
1142
+ const cartTotalCents = discountableItems.reduce(
1143
+ (sum, item) => sum + addNumberPrecision(item.price * item.quantity, dp),
1144
+ 0
1145
+ );
1146
+ if (cartTotalCents === 0) {
1147
+ return { totalDiscount: 0, perItem: [] };
1148
+ }
1149
+ const amountCents = addNumberPrecision(
1150
+ Math.min(amount, removeNumberPrecision(cartTotalCents, dp)),
1151
+ dp
1152
+ );
1153
+ const totalItemCount = discountableItems.reduce((sum, item) => sum + item.quantity, 0);
1154
+ const perItemCents = Math.floor(amountCents / totalItemCount);
1155
+ const itemDiscountsCents = [];
1156
+ let totalDiscountCents = 0;
1157
+ for (let i = 0; i < discountableItems.length; i++) {
1158
+ const item = discountableItems[i];
1159
+ const itemTotalCents = addNumberPrecision(item.price * item.quantity, dp);
1160
+ const discountCents = Math.min(perItemCents * item.quantity, itemTotalCents);
1161
+ itemDiscountsCents.push({ item, discountCents, index: i });
1162
+ totalDiscountCents += discountCents;
1163
+ }
1164
+ applyCouponRemainder(itemDiscountsCents, amountCents - totalDiscountCents, dp);
1165
+ const perItem = [];
1166
+ let totalDiscount = 0;
1167
+ for (const { item, discountCents } of itemDiscountsCents) {
1168
+ const discount = removeNumberPrecision(discountCents, dp);
1169
+ perItem.push({ product_id: item.product_id, discount, lineIndex: item.lineIndex });
1170
+ totalDiscount += discount;
1171
+ }
1172
+ return { totalDiscount: roundDiscount(totalDiscount, dp), perItem };
1173
+ }
1174
+ function calculateFixedProductDiscount(amount, items, limitToXItems, dp) {
1175
+ const targetItems = selectTopPricedUnits(items, limitToXItems);
1176
+ const amountCents = addNumberPrecision(amount, dp);
1177
+ const itemDiscountsCents = [];
1178
+ for (let i = 0; i < targetItems.length; i++) {
1179
+ const item = targetItems[i];
1180
+ const itemPriceCents = addNumberPrecision(item.price, dp);
1181
+ const perUnitCents = Math.min(amountCents, itemPriceCents);
1182
+ const discountCents = Math.floor(perUnitCents * item.quantity);
1183
+ itemDiscountsCents.push({ item, discountCents });
1184
+ }
1185
+ const perItem = [];
1186
+ let totalDiscount = 0;
1187
+ for (const { item, discountCents } of itemDiscountsCents) {
1188
+ const discount = removeNumberPrecision(discountCents, dp);
1189
+ perItem.push({ product_id: item.product_id, discount, lineIndex: item.lineIndex });
1190
+ totalDiscount += discount;
1191
+ }
1192
+ return { totalDiscount: roundDiscount(totalDiscount, dp), perItem };
1193
+ }
1194
+ function applyCouponRemainder(itemDiscounts, remainderCents, dp) {
1195
+ if (remainderCents <= 0) return;
1196
+ let remaining = remainderCents;
1197
+ while (remaining > 0) {
1198
+ const withCapacity = [...itemDiscounts].filter((entry) => {
1199
+ const itemTotalCents = addNumberPrecision(entry.item.price * entry.item.quantity, dp);
1200
+ return entry.discountCents < itemTotalCents;
1201
+ }).sort((a, b) => b.item.price - a.item.price);
1202
+ if (withCapacity.length === 0) break;
1203
+ let distributed = false;
1204
+ for (const entry of withCapacity) {
1205
+ const itemTotalCents = addNumberPrecision(entry.item.price * entry.item.quantity, dp);
1206
+ const original = itemDiscounts.find((d) => d.index === entry.index);
1207
+ if (!original) continue;
1208
+ for (let unit = 0; unit < entry.item.quantity; unit++) {
1209
+ if (remaining <= 0) return;
1210
+ if (original.discountCents < itemTotalCents) {
1211
+ const addCent = Math.min(1, remaining);
1212
+ original.discountCents += addCent;
1213
+ remaining -= addCent;
1214
+ distributed = true;
1215
+ }
1216
+ if (remaining <= 0) return;
1217
+ }
1218
+ }
1219
+ if (!distributed) break;
1220
+ }
1221
+ }
1222
+
1223
+ // src/coupons/woocommerce/recalculate.ts
1224
+ function serializeLineItemTaxes(items, roundingPrecision) {
1225
+ return items.map((item) => {
1226
+ if (!Array.isArray(item.taxes)) return item;
1227
+ return {
1228
+ ...item,
1229
+ taxes: item.taxes.map((tax) => {
1230
+ const widen = (value) => {
1231
+ const parsed = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : NaN;
1232
+ return Number.isFinite(parsed) ? roundHalfUp(parsed, roundingPrecision).toFixed(roundingPrecision) : value;
1233
+ };
1234
+ return {
1235
+ ...tax,
1236
+ ...tax.subtotal === "" || tax.subtotal == null ? {} : { subtotal: widen(tax.subtotal) },
1237
+ ...tax.total == null ? {} : { total: widen(tax.total) }
1238
+ };
1239
+ })
1240
+ };
1241
+ });
1242
+ }
1243
+ function isLineItemOnSale(item) {
1244
+ if (!item) return false;
1245
+ const posData = parsePosData(item);
1246
+ if (posData?.price == null || posData.regular_price == null) return false;
1247
+ const price = parseFloat(String(posData.price));
1248
+ const regularPrice = parseFloat(String(posData.regular_price));
1249
+ if (isNaN(price) || isNaN(regularPrice) || regularPrice <= 0) return false;
1250
+ return price < regularPrice;
1251
+ }
1252
+ function recalculateCoupons(input) {
1253
+ const {
1254
+ lineItems,
1255
+ couponLines,
1256
+ couponConfigs,
1257
+ pricesIncludeTax,
1258
+ calcDiscountsSequentially,
1259
+ taxRates,
1260
+ productCategories,
1261
+ taxRoundAtSubtotal = false,
1262
+ dp = 2
1263
+ } = input;
1264
+ const activeCouponLines = couponLines.filter(
1265
+ (cl) => cl.code != null
1266
+ );
1267
+ const resetItems = lineItems.map((item) => {
1268
+ const posData = parsePosData(item);
1269
+ const parsedPosPrice = posData?.price != null ? parseFloat(String(posData.price)) : NaN;
1270
+ if (Number.isFinite(parsedPosPrice)) {
1271
+ const qty = item.quantity ?? 1;
1272
+ const posTotal = parsedPosPrice * qty;
1273
+ const taxStatus = getLineItemTaxStatus(item);
1274
+ const normalizedClass = normalizeTaxClass(item.tax_class);
1275
+ const itemRates = taxStatus === "taxable" ? taxRates.filter((r) => normalizeTaxClass(r.class) === normalizedClass) : [];
1276
+ const taxResult = calculateTaxes({
1277
+ amount: posTotal,
1278
+ rates: itemRates.map((r) => ({
1279
+ id: r.id,
1280
+ rate: r.rate,
1281
+ compound: r.compound,
1282
+ order: r.order,
1283
+ // WC sorts compound rates by tax_rate_priority (#1548) — must survive this map.
1284
+ priority: r.priority
1285
+ })),
1286
+ amountIncludesTax: pricesIncludeTax,
1287
+ dp
1288
+ });
1289
+ const taxTotal = taxResult.total;
1290
+ const exTaxTotal = pricesIncludeTax ? posTotal - taxTotal : posTotal;
1291
+ const taxes = taxResult.taxes.map((tax) => {
1292
+ const origTax = (item.taxes || []).find((t) => t.id === tax.id);
1293
+ return {
1294
+ ...origTax || { id: tax.id },
1295
+ subtotal: origTax?.subtotal ?? String(tax.total),
1296
+ total: String(tax.total)
1297
+ };
1298
+ });
1299
+ return {
1300
+ ...item,
1301
+ total: String(roundHalfUp(exTaxTotal, 6)),
1302
+ total_tax: String(roundHalfUp(taxTotal, 6)),
1303
+ taxes
1304
+ };
1305
+ }
1306
+ return {
1307
+ ...item,
1308
+ total: item.subtotal,
1309
+ total_tax: item.subtotal_tax,
1310
+ taxes: (item.taxes || []).map((tax) => ({
1311
+ ...tax,
1312
+ total: tax.subtotal ?? tax.total
1313
+ }))
1314
+ };
1315
+ });
1316
+ if (activeCouponLines.length === 0) {
1317
+ return {
1318
+ lineItems: serializeLineItemTaxes(resetItems, getRoundingPrecision(dp)),
1319
+ couponLines
1320
+ };
1321
+ }
1322
+ const buildCouponLineItems = (items) => items.map((item, lineIndex) => ({ item, lineIndex })).filter(({ item }) => item.product_id != null).map(({ item, lineIndex }) => {
1323
+ const qty = item.quantity ?? 1;
1324
+ const posData = parsePosData(item);
1325
+ let basePrice;
1326
+ const posPriceParsed = posData?.price != null ? parseFloat(String(posData.price)) : NaN;
1327
+ if (Number.isFinite(posPriceParsed)) {
1328
+ basePrice = posPriceParsed * qty;
1329
+ } else {
1330
+ const subtotal = parseFloat(item.subtotal || "0");
1331
+ const subtotalTax = parseFloat(item.subtotal_tax || "0");
1332
+ basePrice = pricesIncludeTax ? subtotal + subtotalTax : subtotal;
1333
+ }
1334
+ return {
1335
+ lineIndex,
1336
+ product_id: item.product_id,
1337
+ quantity: qty,
1338
+ price: qty > 0 ? basePrice / qty : 0,
1339
+ subtotal: item.subtotal || "0",
1340
+ total: item.total || "0",
1341
+ categories: productCategories.get(item.product_id) || [],
1342
+ on_sale: isLineItemOnSale(item)
1343
+ };
1344
+ });
1345
+ const allPerItemDiscounts = [];
1346
+ let currentItems = buildCouponLineItems(resetItems);
1347
+ currentItems.sort((a, b) => b.price - a.price);
1348
+ const cumulativeDiscounts = /* @__PURE__ */ new Map();
1349
+ const updatedCouponLines = activeCouponLines.map((cl) => {
1350
+ const config = couponConfigs.get(cl.code.toLowerCase());
1351
+ if (!config) {
1352
+ return {
1353
+ ...cl,
1354
+ discount: "0",
1355
+ discount_tax: "0"
1356
+ };
1357
+ }
1358
+ const discountResult = calculateCouponDiscount(config, currentItems, dp);
1359
+ for (const entry of discountResult.perItem) {
1360
+ const idx = entry.lineIndex ?? -1;
1361
+ const item = currentItems.find((i) => i.lineIndex === idx);
1362
+ if (!item) continue;
1363
+ const itemTotal = item.price * item.quantity;
1364
+ let remaining;
1365
+ if (calcDiscountsSequentially) {
1366
+ remaining = itemTotal;
1367
+ } else {
1368
+ const cumulative = cumulativeDiscounts.get(idx) || 0;
1369
+ remaining = Math.max(0, itemTotal - cumulative);
1370
+ }
1371
+ entry.discount = Math.min(entry.discount, remaining);
1372
+ if (!calcDiscountsSequentially) {
1373
+ const cumulative = cumulativeDiscounts.get(idx) || 0;
1374
+ cumulativeDiscounts.set(idx, cumulative + entry.discount);
1375
+ }
1376
+ }
1377
+ discountResult.totalDiscount = discountResult.perItem.reduce((sum, e) => sum + e.discount, 0);
1378
+ const exTaxPerItem = pricesIncludeTax ? discountResult.perItem.map((entry) => {
1379
+ if (entry.discount <= 0) return entry;
1380
+ const li = entry.lineIndex != null ? resetItems[entry.lineIndex] : resetItems.find((item) => item.product_id === entry.product_id);
1381
+ if (!li) return entry;
1382
+ if (getLineItemTaxStatus(li) !== "taxable") return entry;
1383
+ const itemTaxClass = normalizeTaxClass(li.tax_class);
1384
+ const itemRates = taxRates.filter((r) => normalizeTaxClass(r.class) === itemTaxClass);
1385
+ if (itemRates.length === 0) return entry;
1386
+ const taxResult = calculateTaxes({
1387
+ amount: entry.discount,
1388
+ rates: itemRates.map((r) => ({
1389
+ id: r.id,
1390
+ rate: r.rate,
1391
+ compound: r.compound,
1392
+ order: r.order,
1393
+ // WC sorts compound rates by tax_rate_priority (#1548) — must survive this map.
1394
+ priority: r.priority
1395
+ })),
1396
+ amountIncludesTax: true,
1397
+ dp
1398
+ });
1399
+ const exTaxDiscount = entry.discount - taxResult.total;
1400
+ return { ...entry, discount: roundHalfUp(exTaxDiscount, 6) };
1401
+ }) : discountResult.perItem;
1402
+ allPerItemDiscounts.push(exTaxPerItem);
1403
+ if (calcDiscountsSequentially) {
1404
+ currentItems = currentItems.map((item) => {
1405
+ const discount2 = item.lineIndex != null ? discountResult.perItem.find((d) => d.lineIndex === item.lineIndex) : discountResult.perItem.find((d) => d.product_id === item.product_id);
1406
+ if (!discount2 || discount2.discount <= 0) return item;
1407
+ const qty = item.quantity || 1;
1408
+ return {
1409
+ ...item,
1410
+ price: Math.max(0, item.price - discount2.discount / qty)
1411
+ };
1412
+ });
1413
+ }
1414
+ const { discount, discount_tax } = calculateCouponDiscountTaxSplit(
1415
+ exTaxPerItem,
1416
+ resetItems,
1417
+ taxRates,
1418
+ { pricesIncludeTax, taxRoundAtSubtotal, dp }
1419
+ );
1420
+ return { ...cl, discount, discount_tax };
1421
+ });
1422
+ const discountedLineItems = computeDiscountedLineItems(
1423
+ resetItems,
1424
+ allPerItemDiscounts,
1425
+ getRoundingPrecision(dp)
1426
+ );
1427
+ const finalCouponLines = couponLines.map((cl) => {
1428
+ if (cl.code == null) return cl;
1429
+ const updated = updatedCouponLines.find(
1430
+ (u) => u.code?.toLowerCase() === cl.code?.toLowerCase()
1431
+ );
1432
+ return updated || cl;
1433
+ });
1434
+ return {
1435
+ lineItems: serializeLineItemTaxes(discountedLineItems, getRoundingPrecision(dp)),
1436
+ couponLines: finalCouponLines
1437
+ };
1438
+ }
1439
+
1440
+ // src/coupons/woocommerce/order-totals.ts
1441
+ var WC_NORMALIZE_PRECISION = 6;
1442
+ function parseNumber(value) {
1443
+ if (value == null || isNaN(value)) {
1444
+ return 0;
1445
+ }
1446
+ const parsed = parseFloat(value);
1447
+ return isNaN(parsed) ? 0 : parsed;
1448
+ }
1449
+ function calculateOrderTotals({
1450
+ lineItems = [],
1451
+ shippingLines = [],
1452
+ feeLines = [],
1453
+ couponLines = [],
1454
+ taxRates = [],
1455
+ taxRoundAtSubtotal = false,
1456
+ dp = 2,
1457
+ pricesIncludeTax = false
1458
+ }, onWarning) {
1459
+ const activeLineItems = lineItems.filter((item) => item.product_id !== null);
1460
+ const activeFeeLines = feeLines.filter((item) => item.name !== null);
1461
+ const activeShippingLines = shippingLines.filter((item) => item.method_id !== null);
1462
+ const activeCouponLines = couponLines.filter((item) => item.code != null);
1463
+ let discount_total = 0;
1464
+ let discount_tax = 0;
1465
+ let shipping_total = 0;
1466
+ let shipping_tax = 0;
1467
+ let cart_tax = 0;
1468
+ let subtotal = 0;
1469
+ let subtotal_tax = 0;
1470
+ let total = 0;
1471
+ let total_tax = 0;
1472
+ let fee_total = 0;
1473
+ let fee_tax = 0;
1474
+ let coupon_total = 0;
1475
+ let coupon_tax = 0;
1476
+ const taxLines = taxRates.reduce((acc, taxRate) => {
1477
+ const rateId = taxRate.id ?? 0;
1478
+ acc[rateId] = {
1479
+ rate_id: rateId,
1480
+ label: taxRate.name ?? "",
1481
+ compound: taxRate.compound ?? false,
1482
+ tax_total: 0,
1483
+ shipping_tax_total: 0,
1484
+ rate_percent: parseFloat(taxRate.rate ?? "0"),
1485
+ meta_data: []
1486
+ };
1487
+ return acc;
1488
+ }, {});
1489
+ activeLineItems.forEach((item) => {
1490
+ const parsedSubtotal = parseNumber(item.subtotal);
1491
+ const parsedTotal = parseNumber(item.total);
1492
+ const parsedSubtotalTax = parseNumber(item.subtotal_tax);
1493
+ const parsedTotalTax = parseNumber(item.total_tax);
1494
+ const roundedItemSubtotal = taxRoundAtSubtotal ? parsedSubtotal : roundHalfUp(parsedSubtotal, dp);
1495
+ const roundedItemTotal = taxRoundAtSubtotal ? parsedTotal : roundHalfUp(parsedTotal, dp);
1496
+ discount_total += roundedItemSubtotal - roundedItemTotal;
1497
+ const hasPerRateSubtotals = Array.isArray(item.taxes) && item.taxes.length > 0 && item.taxes[0].subtotal != null;
1498
+ if (hasPerRateSubtotals) {
1499
+ item.taxes.forEach((tax) => {
1500
+ const subtotalTaxForRate = parseNumber(tax.subtotal);
1501
+ const totalTaxForRate = parseNumber(tax.total);
1502
+ discount_tax += roundHalfUp(subtotalTaxForRate - totalTaxForRate, getRoundingPrecision(dp));
1503
+ });
1504
+ } else {
1505
+ discount_tax += roundHalfUp(parsedSubtotalTax - parsedTotalTax, getRoundingPrecision(dp));
1506
+ }
1507
+ subtotal += roundedItemSubtotal;
1508
+ subtotal_tax += parsedSubtotalTax;
1509
+ total += roundedItemTotal;
1510
+ total_tax += parsedTotalTax;
1511
+ if (Array.isArray(item.taxes)) {
1512
+ item.taxes.forEach((tax) => {
1513
+ const taxAmount = parseNumber(tax.total);
1514
+ const rateId = tax.id ?? 0;
1515
+ if (!taxLines[rateId]) {
1516
+ taxLines[rateId] = {
1517
+ rate_id: rateId,
1518
+ label: "",
1519
+ compound: false,
1520
+ tax_total: 0,
1521
+ shipping_tax_total: 0,
1522
+ rate_percent: 0,
1523
+ meta_data: []
1524
+ };
1525
+ onWarning?.({ code: "unknown_tax_rate_id", rateId });
1526
+ }
1527
+ taxLines[rateId].tax_total += taxRoundAtSubtotal ? taxAmount : roundTaxTotal(taxAmount, dp, pricesIncludeTax);
1528
+ });
1529
+ }
1530
+ });
1531
+ const accumulateTaxes = (taxes, target) => {
1532
+ if (!Array.isArray(taxes)) return;
1533
+ taxes.forEach((tax) => {
1534
+ const taxAmount = parseNumber(tax.total);
1535
+ const rateId = tax.id ?? 0;
1536
+ if (!taxLines[rateId]) {
1537
+ taxLines[rateId] = {
1538
+ rate_id: rateId,
1539
+ label: "",
1540
+ compound: false,
1541
+ tax_total: 0,
1542
+ shipping_tax_total: 0,
1543
+ rate_percent: 0,
1544
+ meta_data: []
1545
+ };
1546
+ onWarning?.({ code: "unknown_tax_rate_id", rateId });
1547
+ }
1548
+ taxLines[rateId][target] += taxRoundAtSubtotal ? taxAmount : roundTaxTotal(taxAmount, dp, pricesIncludeTax);
1549
+ });
1550
+ };
1551
+ activeFeeLines.forEach((line) => {
1552
+ fee_total += parseNumber(line.total);
1553
+ fee_tax += parseNumber(line.total_tax);
1554
+ total += parseNumber(line.total);
1555
+ total_tax += parseNumber(line.total_tax);
1556
+ accumulateTaxes(line.taxes, "tax_total");
1557
+ });
1558
+ activeShippingLines.forEach((line) => {
1559
+ const roundedLineTotal = roundHalfUp(parseNumber(line.total), dp);
1560
+ shipping_total += roundedLineTotal;
1561
+ shipping_tax += parseNumber(line.total_tax);
1562
+ total += roundedLineTotal;
1563
+ total_tax += parseNumber(line.total_tax);
1564
+ accumulateTaxes(line.taxes, "shipping_tax_total");
1565
+ });
1566
+ activeCouponLines.forEach((line) => {
1567
+ coupon_total += parseNumber(line.discount);
1568
+ coupon_tax += parseNumber(line.discount_tax);
1569
+ });
1570
+ const taxLinesArray = Object.values(taxLines) || [];
1571
+ const fullPrecisionCartTax = taxLinesArray.reduce((sum, tl) => sum + tl.tax_total, 0);
1572
+ const fullPrecisionShippingTax = taxLinesArray.reduce(
1573
+ (sum, tl) => sum + tl.shipping_tax_total,
1574
+ 0
1575
+ );
1576
+ const filteredTaxLines = taxLinesArray.map((taxLine) => {
1577
+ const { tax_total, shipping_tax_total } = taxLine;
1578
+ if (tax_total === 0 && shipping_tax_total === 0) {
1579
+ return null;
1580
+ }
1581
+ return {
1582
+ ...taxLine,
1583
+ tax_total: taxRoundAtSubtotal ? Number(tax_total).toFixed(6) : String(roundTaxTotal(tax_total, dp, pricesIncludeTax)),
1584
+ shipping_tax_total: taxRoundAtSubtotal ? Number(shipping_tax_total).toFixed(6) : String(roundTaxTotal(shipping_tax_total, dp, pricesIncludeTax))
1585
+ };
1586
+ }).filter((line) => line !== null);
1587
+ const roundedCartTax = roundHalfUp(fullPrecisionCartTax, getRoundingPrecision(dp));
1588
+ const roundedShippingTax = roundHalfUp(fullPrecisionShippingTax, getRoundingPrecision(dp));
1589
+ const roundedTotalTax = taxRoundAtSubtotal ? roundHalfUp(roundHalfUp(roundedCartTax + roundedShippingTax, WC_NORMALIZE_PRECISION), dp) : roundTaxTotal(
1590
+ roundHalfUp(roundedCartTax + roundedShippingTax, WC_NORMALIZE_PRECISION),
1591
+ dp,
1592
+ pricesIncludeTax
1593
+ );
1594
+ return {
1595
+ /**
1596
+ * These properties are stored on the order document
1597
+ */
1598
+ discount_total: String(roundHalfUp(discount_total, dp)),
1599
+ discount_tax: String(
1600
+ roundTaxTotal(roundHalfUp(discount_tax, WC_NORMALIZE_PRECISION), dp, pricesIncludeTax)
1601
+ ),
1602
+ shipping_total: String(roundHalfUp(shipping_total, dp)),
1603
+ shipping_tax: String(roundedShippingTax),
1604
+ cart_tax: String(roundedCartTax),
1605
+ // WC: `set_total( round( $cart_total + $fees_total + $shipping_total
1606
+ // + $this->get_cart_tax() + $this->get_shipping_tax(), $price_decimals ) )`.
1607
+ // The tax summands are the FULL-PRECISION props, not the display-rounded
1608
+ // `total_tax` — rounding the tax first and rounding again here is a double
1609
+ // rounding that can land a cent away from the store whenever the untaxed part
1610
+ // of the sum is not itself at display decimals (a raw fee total is the common
1611
+ // way in). `total_tax` stays its own rounded field, which is what WC stores.
1612
+ total: String(
1613
+ roundHalfUp(
1614
+ roundHalfUp(total + roundedCartTax + roundedShippingTax, WC_NORMALIZE_PRECISION),
1615
+ dp
1616
+ )
1617
+ ),
1618
+ total_tax: String(roundTaxTotal(roundedTotalTax, dp, pricesIncludeTax)),
1619
+ tax_lines: filteredTaxLines,
1620
+ /**
1621
+ * Subtotals are not stored on the order document, but we need them to display in the cart
1622
+ */
1623
+ subtotal: String(roundHalfUp(subtotal, dp)),
1624
+ subtotal_tax: String(roundHalfUp(subtotal_tax, dp)),
1625
+ /**
1626
+ * Need to add fee_total to display in the cart, to match the WC Admin display
1627
+ */
1628
+ fee_total: String(roundHalfUp(fee_total, dp)),
1629
+ fee_tax: String(roundHalfUp(fee_tax, dp)),
1630
+ coupon_total: String(roundHalfUp(coupon_total, dp)),
1631
+ coupon_tax: String(roundHalfUp(coupon_tax, dp))
1632
+ };
1633
+ }
1634
+
1635
+ // src/coupons/woocommerce/validate.ts
1636
+ function parseGmtDate(dateStr) {
1637
+ if (!/Z|[+-]\d{2}:\d{2}$/.test(dateStr)) {
1638
+ return /* @__PURE__ */ new Date(dateStr + "Z");
1639
+ }
1640
+ return new Date(dateStr);
1641
+ }
1642
+ function validateCoupon(coupon, context) {
1643
+ const codeLower = coupon.code?.toLowerCase();
1644
+ if (context.appliedCoupons.some((c) => c.toLowerCase() === codeLower)) {
1645
+ return { valid: false, rejection: { code: "already_applied" } };
1646
+ }
1647
+ if (coupon.date_expires_gmt) {
1648
+ const expiry = parseGmtDate(coupon.date_expires_gmt);
1649
+ if (expiry.getTime() < context.now) {
1650
+ return { valid: false, rejection: { code: "expired" } };
1651
+ }
1652
+ }
1653
+ if (coupon.usage_limit !== null && coupon.usage_limit > 0 && coupon.usage_count >= coupon.usage_limit) {
1654
+ return { valid: false, rejection: { code: "usage_limit_reached" } };
1655
+ }
1656
+ if (coupon.usage_limit_per_user !== null && coupon.usage_limit_per_user > 0 && (context.customerId !== null || context.customerEmail)) {
1657
+ const identifier = context.customerId !== null ? String(context.customerId) : context.customerEmail.toLowerCase();
1658
+ const userUsageCount = (coupon.used_by || []).filter(
1659
+ (id) => String(id).toLowerCase() === identifier
1660
+ ).length;
1661
+ if (userUsageCount >= coupon.usage_limit_per_user) {
1662
+ return { valid: false, rejection: { code: "usage_limit_reached_for_customer" } };
1663
+ }
1664
+ }
1665
+ if (coupon.minimum_amount && parseFloat(coupon.minimum_amount) > 0) {
1666
+ if (context.cartSubtotal < parseFloat(coupon.minimum_amount)) {
1667
+ return {
1668
+ valid: false,
1669
+ rejection: { code: "minimum_spend_not_met", params: { amount: coupon.minimum_amount } }
1670
+ };
1671
+ }
1672
+ }
1673
+ if (coupon.maximum_amount && parseFloat(coupon.maximum_amount) > 0) {
1674
+ if (context.cartSubtotal > parseFloat(coupon.maximum_amount)) {
1675
+ return {
1676
+ valid: false,
1677
+ rejection: { code: "maximum_spend_exceeded", params: { amount: coupon.maximum_amount } }
1678
+ };
1679
+ }
1680
+ }
1681
+ if (coupon.individual_use && context.appliedCoupons.length > 0) {
1682
+ return {
1683
+ valid: false,
1684
+ rejection: { code: "individual_use", params: { code: coupon.code } }
1685
+ };
1686
+ }
1687
+ if (context.appliedCouponsWithIndividualUse && context.appliedCouponsWithIndividualUse.length > 0) {
1688
+ return {
1689
+ valid: false,
1690
+ rejection: {
1691
+ code: "individual_use_conflict",
1692
+ params: { code: context.appliedCouponsWithIndividualUse[0] }
1693
+ }
1694
+ };
1695
+ }
1696
+ if (coupon.email_restrictions && coupon.email_restrictions.length > 0) {
1697
+ if (!context.customerEmail) {
1698
+ return { valid: false, rejection: { code: "email_required" } };
1699
+ }
1700
+ const emailLower = context.customerEmail.toLowerCase();
1701
+ const matches = coupon.email_restrictions.some((pattern) => {
1702
+ const patternLower = pattern.toLowerCase().trim();
1703
+ if (patternLower.includes("*")) {
1704
+ const regex = new RegExp(
1705
+ "^" + patternLower.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, ".*") + "$"
1706
+ );
1707
+ return regex.test(emailLower);
1708
+ }
1709
+ return emailLower === patternLower;
1710
+ });
1711
+ if (!matches) {
1712
+ return { valid: false, rejection: { code: "email_not_allowed" } };
1713
+ }
1714
+ }
1715
+ const eligible = getEligibleItems(context.lineItems, {
1716
+ product_ids: coupon.product_ids || [],
1717
+ excluded_product_ids: coupon.excluded_product_ids || [],
1718
+ product_categories: coupon.product_categories || [],
1719
+ excluded_product_categories: coupon.excluded_product_categories || [],
1720
+ exclude_sale_items: coupon.exclude_sale_items || false
1721
+ });
1722
+ const hasRestrictions = coupon.product_ids?.length > 0 || coupon.excluded_product_ids?.length > 0 || coupon.product_categories?.length > 0 || coupon.excluded_product_categories?.length > 0 || coupon.exclude_sale_items;
1723
+ if (hasRestrictions && eligible.length === 0) {
1724
+ return { valid: false, rejection: { code: "not_applicable_to_cart" } };
1725
+ }
1726
+ if (coupon.discount_type === "fixed_cart" && coupon.exclude_sale_items && context.lineItems.some((item) => item.on_sale)) {
1727
+ return { valid: false, rejection: { code: "not_applicable_to_cart" } };
1728
+ }
1729
+ return { valid: true };
1730
+ }
1731
+
1732
+ // src/coupons/woocommerce/to-coupon-configs.ts
1733
+ function toCouponConfigs(codes, coupons) {
1734
+ const couponConfigs = /* @__PURE__ */ new Map();
1735
+ for (const code of codes) {
1736
+ const coupon = coupons.get(code);
1737
+ if (!coupon) continue;
1738
+ couponConfigs.set(code, {
1739
+ discount_type: coupon.discount_type,
1740
+ amount: coupon.amount || "0",
1741
+ limit_usage_to_x_items: coupon.limit_usage_to_x_items ?? null,
1742
+ product_ids: [...coupon.product_ids ?? []],
1743
+ excluded_product_ids: [...coupon.excluded_product_ids ?? []],
1744
+ product_categories: [...coupon.product_categories ?? []],
1745
+ excluded_product_categories: [...coupon.excluded_product_categories ?? []],
1746
+ exclude_sale_items: coupon.exclude_sale_items ?? false
1747
+ });
1748
+ }
1749
+ return couponConfigs;
1750
+ }
841
1751
  export {
842
1752
  COMMANDS_PATH,
843
1753
  ConnectorProvider,
@@ -879,5 +1789,6 @@ export {
879
1789
  useStockOverlayAsOf,
880
1790
  useTraitContext,
881
1791
  withStockOverlay,
1792
+ woocommerce_exports2 as woocommerceCoupons,
882
1793
  woocommerce_exports as woocommerceTax
883
1794
  };