@tallyui/core 3.8.0 → 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/{commands-BvRgJMgX.d.ts → commands-BPNfbeF9.d.ts} +64 -2
- package/dist/index.d.ts +391 -24
- package/dist/index.js +911 -0
- package/dist/server/index.d.ts +23 -9
- package/dist/server/index.js +146 -2
- package/package.json +5 -3
- package/src/coupons/woocommerce/discount.ts +333 -0
- package/src/coupons/woocommerce/helpers.ts +399 -0
- package/src/coupons/woocommerce/index.ts +15 -0
- package/src/coupons/woocommerce/order-totals.ts +360 -0
- package/src/coupons/woocommerce/pos-data.ts +89 -0
- package/src/coupons/woocommerce/recalculate.ts +405 -0
- package/src/coupons/woocommerce/to-coupon-configs.ts +41 -0
- package/src/coupons/woocommerce/types.ts +155 -0
- package/src/coupons/woocommerce/validate.ts +193 -0
- package/src/index.ts +3 -0
- package/src/server/batch.ts +14 -3
- package/src/server/command-result.ts +27 -1
- package/src/server/index.ts +2 -1
- package/src/server/refund-payload-shape.ts +63 -0
- package/src/server/register-figures.ts +18 -3
- package/src/server/rejection-codes.ts +4 -4
- package/src/server/versions.ts +2 -0
- package/src/types/commands.ts +32 -1
- package/src/types/connector.ts +16 -0
- package/src/types/index.ts +2 -0
- package/src/types/store-settings.ts +2 -0
package/dist/server/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { e as CommandError, l as OrderCreatePayload, d as CommandEnvelope,
|
|
2
|
-
export { M as MAX_COMMANDS_PER_BATCH, O as OrderCreateDisplay, n as OrderCreateTaxRate } from '../commands-
|
|
1
|
+
import { e as CommandError, l as OrderCreatePayload, d as CommandEnvelope, z as RegisterCommandEnvelope, A as AnyCommandEnvelope, f as CommandResult, B as BatchTooLargeBody, c as CommandBatchResponse, C as CommandWarning, D as RegisterCommandResult, v as OrderRefundRejectionCode } from '../commands-BPNfbeF9.js';
|
|
2
|
+
export { M as MAX_COMMANDS_PER_BATCH, O as OrderCreateDisplay, n as OrderCreateTaxRate } from '../commands-BPNfbeF9.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;
|
|
@@ -47,13 +47,18 @@ declare function fiscalFiguresErrors(payload: OrderCreatePayloadV3): string[];
|
|
|
47
47
|
declare const SUPPORTED_ORDER_CREATE_VERSIONS: readonly number[];
|
|
48
48
|
/** The till's capability for the contract versions shared by all five register commands; a server passes its own. */
|
|
49
49
|
declare const SUPPORTED_REGISTER_VERSIONS: readonly number[];
|
|
50
|
+
/** The till's capability for order.refund versions (ADR-080); a server passes its own. */
|
|
51
|
+
declare const SUPPORTED_ORDER_REFUND_VERSIONS: readonly number[];
|
|
50
52
|
|
|
51
53
|
/** An envelope validateBatch accepted: every field's shape is checked, and its version is any positive
|
|
52
54
|
* safe integer (precheckCommand decides which versions this server supports). */
|
|
53
55
|
type ValidatedCommandEnvelope = (Omit<CommandEnvelope<Record<string, unknown>>, 'version'> & {
|
|
54
56
|
type: 'order.create';
|
|
55
57
|
version: number;
|
|
56
|
-
}) | RegisterCommandEnvelope<Record<string, unknown
|
|
58
|
+
}) | RegisterCommandEnvelope<Record<string, unknown>> | (Omit<CommandEnvelope<Record<string, unknown>>, 'type' | 'version'> & {
|
|
59
|
+
type: 'order.refund';
|
|
60
|
+
version: number;
|
|
61
|
+
});
|
|
57
62
|
/** Validates every envelope before any command is claimed. */
|
|
58
63
|
declare function validateBatch(body: unknown): {
|
|
59
64
|
ok: true;
|
|
@@ -83,11 +88,12 @@ declare function validateBatch(body: unknown): {
|
|
|
83
88
|
*
|
|
84
89
|
* `supported` is the SERVER's own list (what its /info advertises), never core's constants, which are the
|
|
85
90
|
* till's capability (#297). The version check, the `unsupported_version` message and its `data` all use it:
|
|
86
|
-
* `precheckCommand(envelope, { orderCreate: [1, 2, 3], register: [1] })
|
|
91
|
+
* `precheckCommand(envelope, { orderCreate: [1, 2, 3], register: [1], orderRefund: [1] })` (`orderRefund` is optional).
|
|
87
92
|
*/
|
|
88
93
|
declare function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCommandEnvelope, 'id' | 'type' | 'version' | 'payload'>, supported: {
|
|
89
94
|
orderCreate: readonly number[];
|
|
90
95
|
register: readonly number[];
|
|
96
|
+
orderRefund?: readonly number[];
|
|
91
97
|
}): CommandResult | undefined;
|
|
92
98
|
|
|
93
99
|
/**
|
|
@@ -134,11 +140,15 @@ declare function parseCommandResult(value: unknown): CommandResult;
|
|
|
134
140
|
/** Shape errors before a register command claims a ledger row. Unknown top-level keys are allowed. */
|
|
135
141
|
declare function registerPayloadErrors(type: string, payload: unknown): string[];
|
|
136
142
|
|
|
143
|
+
/** Strict shape errors per ADR-070 and ADR-080 for order.refund v1; plugins run this before any lookup. */
|
|
144
|
+
declare function refundPayloadErrors(payload: unknown): string[];
|
|
145
|
+
|
|
137
146
|
/**
|
|
138
147
|
* A session's expected figures per method: the counted float in cash, plus each order's payments, plus paid_in
|
|
139
148
|
* and minus paid_out movements that are not voided. The plugin chooses which orders count (for Medusa: completed,
|
|
140
149
|
* archived and cancelled POS orders, so a received sale stays counted after an admin archives or cancels it) and
|
|
141
|
-
* passes each order's recorded POS payments; this function only sums.
|
|
150
|
+
* passes each order's recorded POS payments; this function only sums. Refunds made in the session (by the refund's
|
|
151
|
+
* own sessionId, ADR-080) lower expected per method.
|
|
142
152
|
*/
|
|
143
153
|
declare function deriveSessionFigures(input: {
|
|
144
154
|
countedFloatMinor: number;
|
|
@@ -154,9 +164,13 @@ declare function deriveSessionFigures(input: {
|
|
|
154
164
|
amountMinor: number;
|
|
155
165
|
voids: string | null;
|
|
156
166
|
}[];
|
|
167
|
+
refunds?: {
|
|
168
|
+
byMethod: Record<string, number>;
|
|
169
|
+
}[];
|
|
157
170
|
}): {
|
|
158
171
|
expected: Record<string, number>;
|
|
159
172
|
salesCount: number;
|
|
173
|
+
refundsTotalMinor?: number;
|
|
160
174
|
};
|
|
161
175
|
declare function deriveVariance(counted: Record<string, number>, expected: Record<string, number>): Record<string, number>;
|
|
162
176
|
|
|
@@ -175,11 +189,11 @@ type RegisterOutcome = {
|
|
|
175
189
|
|
|
176
190
|
/** Every error.code a plugin may put on a rejected result (ADR-038 and its amendments, ADR-068),
|
|
177
191
|
* except `register_approval_required`, which arrives with registers c2c. */
|
|
178
|
-
type CommandRejectionCode = 'invalid_payload' | 'unsupported_version' | 'idempotency_mismatch' | 'store_configuration' | 'platform_error' | 'insufficient_stock' | 'unsupported_tax_mode' | 'internal_error' | OrderRejectionCode | RegisterConflictCode;
|
|
192
|
+
type CommandRejectionCode = 'invalid_payload' | 'unsupported_version' | 'idempotency_mismatch' | 'store_configuration' | 'platform_error' | 'insufficient_stock' | 'unsupported_tax_mode' | 'internal_error' | OrderRejectionCode | RegisterConflictCode | OrderRefundRejectionCode;
|
|
179
193
|
/**
|
|
180
194
|
* The rejected result for a platform-native error the plugin has judged permanent (a replay would fail
|
|
181
195
|
* the same way, e.g. a Vendure ErrorResult code) and the contract has no code for. `platform_error` is
|
|
182
|
-
* for `order.create`
|
|
196
|
+
* for `order.create` and `order.refund` (ADR-080): a rejected register command halts that register's queue until c2c,
|
|
183
197
|
* so register refusals use the ADR-068 codes.
|
|
184
198
|
*
|
|
185
199
|
* Return it only when the platform made no durable change for this command: the plugin threw so its
|
|
@@ -203,11 +217,11 @@ declare function platformErrorResult(id: string, platformCode: string, platformM
|
|
|
203
217
|
* the correlation id links it to the plugin's log.
|
|
204
218
|
*
|
|
205
219
|
* Database, network, unknown-SQLSTATE and any other unclassifiable errors stay transient (503), never
|
|
206
|
-
* `internal_error`. `order.create`
|
|
220
|
+
* `internal_error`. `order.create` and `order.refund` (ADR-080), as for `platform_error`.
|
|
207
221
|
*
|
|
208
222
|
* See ADR-038's `internal_error` amendment (needs-admin on a failed compensation; on Vendure only
|
|
209
223
|
* before the first write).
|
|
210
224
|
*/
|
|
211
225
|
declare function internalErrorResult(id: string, correlationId: string): CommandResult;
|
|
212
226
|
|
|
213
|
-
export { type BatchOutcome, BatchTooLargeBody, type CommandErrorWithData, type CommandRejectionCode, CommandResultError, type OrderCreatePayloadV3, type OrderRejectionCode, type RegisterConflictCode, type RegisterOutcome, type Rejection, SUPPORTED_ORDER_CREATE_VERSIONS, SUPPORTED_REGISTER_VERSIONS, type ValidatedCommandEnvelope, canonicalJson, commandFingerprint, currencyDecimals, deriveSessionFigures, deriveVariance, fiscalFiguresErrors, inProgressOutcome, internalErrorResult, majorToMinor, minorToMajor, parseCommandResult, payloadBoundErrors, payloadShapeErrors, platformErrorResult, precheckCommand, registerPayloadErrors, totalWarnings, transientOutcome, validateBatch };
|
|
227
|
+
export { type BatchOutcome, BatchTooLargeBody, type CommandErrorWithData, type CommandRejectionCode, CommandResultError, type OrderCreatePayloadV3, type OrderRejectionCode, type RegisterConflictCode, type RegisterOutcome, type Rejection, SUPPORTED_ORDER_CREATE_VERSIONS, SUPPORTED_ORDER_REFUND_VERSIONS, SUPPORTED_REGISTER_VERSIONS, type ValidatedCommandEnvelope, canonicalJson, commandFingerprint, currencyDecimals, deriveSessionFigures, deriveVariance, fiscalFiguresErrors, inProgressOutcome, internalErrorResult, majorToMinor, minorToMajor, parseCommandResult, payloadBoundErrors, payloadShapeErrors, platformErrorResult, precheckCommand, refundPayloadErrors, registerPayloadErrors, totalWarnings, transientOutcome, validateBatch };
|
package/dist/server/index.js
CHANGED
|
@@ -284,6 +284,7 @@ function fiscalFiguresErrors(payload) {
|
|
|
284
284
|
// src/server/versions.ts
|
|
285
285
|
var SUPPORTED_ORDER_CREATE_VERSIONS = [1, 2, 3, 4];
|
|
286
286
|
var SUPPORTED_REGISTER_VERSIONS = [1];
|
|
287
|
+
var SUPPORTED_ORDER_REFUND_VERSIONS = [1];
|
|
287
288
|
|
|
288
289
|
// src/server/batch.ts
|
|
289
290
|
function validateBatch(body) {
|
|
@@ -305,6 +306,7 @@ function validateBatch(body) {
|
|
|
305
306
|
if (typeof command.id !== "string" || command.id.length === 0 || command.id.length > 64) field = "id";
|
|
306
307
|
else if (![
|
|
307
308
|
"order.create",
|
|
309
|
+
"order.refund",
|
|
308
310
|
"register.session.open",
|
|
309
311
|
"register.session.transition",
|
|
310
312
|
"register.movement.record",
|
|
@@ -324,6 +326,17 @@ function precheckCommand(envelope, supported) {
|
|
|
324
326
|
for (const key of ["orderCreate", "register"]) {
|
|
325
327
|
if (!supported[key]?.length) throw new TypeError(`precheckCommand: supported.${key} must list at least one version`);
|
|
326
328
|
}
|
|
329
|
+
if (envelope.type === "order.refund") {
|
|
330
|
+
const versions = supported.orderRefund ?? [];
|
|
331
|
+
if (!versions.includes(envelope.version)) {
|
|
332
|
+
return { id: envelope.id, status: "rejected", error: {
|
|
333
|
+
code: "unsupported_version",
|
|
334
|
+
message: `order.refund version ${envelope.version} is not supported; this server ${versions.length ? `supports ${versions.join(", ")}` : "takes no refunds"}`,
|
|
335
|
+
data: { orderRefund: versions.length ? Math.max(...versions) : 0 }
|
|
336
|
+
} };
|
|
337
|
+
}
|
|
338
|
+
return void 0;
|
|
339
|
+
}
|
|
327
340
|
if (envelope.type !== "order.create") {
|
|
328
341
|
if (!supported.register.includes(envelope.version)) {
|
|
329
342
|
return { id: envelope.id, status: "rejected", error: {
|
|
@@ -430,7 +443,33 @@ function parseCommandResult(value) {
|
|
|
430
443
|
if (!object(input.register)) throw new CommandResultError("Invalid register");
|
|
431
444
|
result.register = input.register;
|
|
432
445
|
}
|
|
433
|
-
if (
|
|
446
|
+
if (input.refund !== void 0) {
|
|
447
|
+
if (!object(input.refund)) throw new CommandResultError("Invalid refund");
|
|
448
|
+
const refund = input.refund;
|
|
449
|
+
if (!Number.isSafeInteger(refund.totalMinor) || refund.totalMinor < 0) throw new CommandResultError("Invalid refund.totalMinor");
|
|
450
|
+
if (!object(refund.byMethod)) throw new CommandResultError("Invalid refund.byMethod");
|
|
451
|
+
const byMethod = Object.fromEntries(Object.entries(refund.byMethod).map(([key, amount]) => {
|
|
452
|
+
if (!key.length) throw new CommandResultError("Invalid refund.byMethod");
|
|
453
|
+
if (!Number.isSafeInteger(amount) || amount < 0) throw new CommandResultError(`Invalid refund.byMethod.${key}`);
|
|
454
|
+
return [key, amount];
|
|
455
|
+
}));
|
|
456
|
+
if (Object.values(byMethod).reduce((sum, amount) => sum + amount, 0) !== refund.totalMinor) throw new CommandResultError("Invalid refund.byMethod");
|
|
457
|
+
if (!Array.isArray(refund.refunds) || refund.refunds.length === 0) throw new CommandResultError("Invalid refund.refunds");
|
|
458
|
+
const refunds = refund.refunds.map((value2, index) => {
|
|
459
|
+
const field = `refund.refunds[${index}]`;
|
|
460
|
+
if (!object(value2)) throw new CommandResultError(`Invalid ${field}`);
|
|
461
|
+
const entry = value2;
|
|
462
|
+
for (const key of ["id", "paymentId"]) {
|
|
463
|
+
if (typeof entry[key] !== "string" || entry[key].length === 0) throw new CommandResultError(`Invalid ${field}.${key}`);
|
|
464
|
+
}
|
|
465
|
+
if (!Number.isSafeInteger(entry.totalMinor) || entry.totalMinor < 0) throw new CommandResultError(`Invalid ${field}.totalMinor`);
|
|
466
|
+
if (typeof entry.state !== "string" || entry.state.length === 0) throw new CommandResultError(`Invalid ${field}.state`);
|
|
467
|
+
return { id: entry.id, paymentId: entry.paymentId, totalMinor: entry.totalMinor, state: entry.state };
|
|
468
|
+
});
|
|
469
|
+
if (refunds.reduce((sum, entry) => sum + entry.totalMinor, 0) !== refund.totalMinor) throw new CommandResultError("Invalid refund.refunds");
|
|
470
|
+
result.refund = { totalMinor: refund.totalMinor, byMethod, refunds };
|
|
471
|
+
}
|
|
472
|
+
if (result.status === "applied" && result.serverRefs === void 0 && result.register === void 0 && result.refund === void 0) {
|
|
434
473
|
throw new CommandResultError("Invalid serverRefs: required for applied");
|
|
435
474
|
}
|
|
436
475
|
if (input.warnings !== void 0) {
|
|
@@ -638,6 +677,94 @@ function registerPayloadErrors(type, payload) {
|
|
|
638
677
|
return errors;
|
|
639
678
|
}
|
|
640
679
|
|
|
680
|
+
// src/server/refund-payload-shape.ts
|
|
681
|
+
function refundPayloadErrors(payload) {
|
|
682
|
+
const errors = [];
|
|
683
|
+
const object = (value) => typeof value === "object" && value !== null && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
|
684
|
+
const check = (valid, field, expected) => {
|
|
685
|
+
if (!valid && errors.length < 10) errors.push(`${field}: expected ${expected}`);
|
|
686
|
+
};
|
|
687
|
+
if (!object(payload)) return ["payload: expected an object"];
|
|
688
|
+
const noNul = (value, field) => {
|
|
689
|
+
if (typeof value === "string") check(!value.includes("\0"), field, "no NUL character");
|
|
690
|
+
};
|
|
691
|
+
const fields = [
|
|
692
|
+
"clientRefundId",
|
|
693
|
+
"orderId",
|
|
694
|
+
"registerId",
|
|
695
|
+
"sessionId",
|
|
696
|
+
"clientOrderId",
|
|
697
|
+
"cashierRef",
|
|
698
|
+
"lines",
|
|
699
|
+
"shippingMinor",
|
|
700
|
+
"totalMinor",
|
|
701
|
+
"adjustmentMinor",
|
|
702
|
+
"destination",
|
|
703
|
+
"reason",
|
|
704
|
+
"createdAt"
|
|
705
|
+
];
|
|
706
|
+
for (const key of Object.keys(payload)) {
|
|
707
|
+
if (!fields.includes(key) && errors.length < 10) {
|
|
708
|
+
errors.push(`${key.includes("\0") ? JSON.stringify(key) : key}: unknown field for order.refund version 1`);
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
for (const field of ["clientRefundId", "orderId", "registerId", "sessionId", "clientOrderId", "cashierRef"]) {
|
|
712
|
+
const value = payload[field];
|
|
713
|
+
if (["clientOrderId", "cashierRef"].includes(field) && value === void 0) continue;
|
|
714
|
+
check(
|
|
715
|
+
typeof value === "string" && value.length > 0 && value.length <= 64,
|
|
716
|
+
field,
|
|
717
|
+
"a non-empty string of at most 64 characters"
|
|
718
|
+
);
|
|
719
|
+
noNul(value, field);
|
|
720
|
+
}
|
|
721
|
+
check(Array.isArray(payload.lines) && payload.lines.length <= 500, "lines", "an array of at most 500 lines");
|
|
722
|
+
const seen = /* @__PURE__ */ new Set();
|
|
723
|
+
if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
|
|
724
|
+
const path = `lines[${index}]`;
|
|
725
|
+
if (!object(line)) {
|
|
726
|
+
check(false, path, "an object");
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
for (const key of Object.keys(line)) {
|
|
730
|
+
if (!["orderLineId", "quantity", "restock"].includes(key) && errors.length < 10) {
|
|
731
|
+
errors.push(`${path}.${key.includes("\0") ? JSON.stringify(key) : key}: unknown field for order.refund version 1`);
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
check(
|
|
735
|
+
typeof line.orderLineId === "string" && line.orderLineId.length > 0 && line.orderLineId.length <= 64,
|
|
736
|
+
`${path}.orderLineId`,
|
|
737
|
+
"a non-empty string of at most 64 characters"
|
|
738
|
+
);
|
|
739
|
+
noNul(line.orderLineId, `${path}.orderLineId`);
|
|
740
|
+
if (typeof line.orderLineId === "string") {
|
|
741
|
+
check(!seen.has(line.orderLineId), `${path}.orderLineId`, "unique in lines");
|
|
742
|
+
seen.add(line.orderLineId);
|
|
743
|
+
}
|
|
744
|
+
check(Number.isSafeInteger(line.quantity) && line.quantity >= 1, `${path}.quantity`, "a safe integer >= 1");
|
|
745
|
+
check(typeof line.restock === "boolean", `${path}.restock`, "a boolean");
|
|
746
|
+
});
|
|
747
|
+
for (const field of ["shippingMinor", "totalMinor"]) {
|
|
748
|
+
check(Number.isSafeInteger(payload[field]) && payload[field] >= 0, field, "a safe integer >= 0");
|
|
749
|
+
}
|
|
750
|
+
check(Number.isSafeInteger(payload.adjustmentMinor), "adjustmentMinor", "a safe integer");
|
|
751
|
+
check(payload.destination === "original_method" || payload.destination === "cash", "destination", "original_method or cash");
|
|
752
|
+
noNul(payload.destination, "destination");
|
|
753
|
+
check(
|
|
754
|
+
typeof payload.reason === "string" && payload.reason.trim().length > 0 && payload.reason.length <= 500,
|
|
755
|
+
"reason",
|
|
756
|
+
"a non-empty string after trim of at most 500 characters"
|
|
757
|
+
);
|
|
758
|
+
noNul(payload.reason, "reason");
|
|
759
|
+
check(
|
|
760
|
+
typeof payload.createdAt === "string" && payload.createdAt.length > 0 && !Number.isNaN(Date.parse(payload.createdAt)),
|
|
761
|
+
"createdAt",
|
|
762
|
+
"a valid date"
|
|
763
|
+
);
|
|
764
|
+
noNul(payload.createdAt, "createdAt");
|
|
765
|
+
return errors;
|
|
766
|
+
}
|
|
767
|
+
|
|
641
768
|
// src/server/register-figures.ts
|
|
642
769
|
function deriveSessionFigures(input) {
|
|
643
770
|
const expected = Object.assign(/* @__PURE__ */ Object.create(null), { cash: input.countedFloatMinor });
|
|
@@ -654,7 +781,22 @@ function deriveSessionFigures(input) {
|
|
|
654
781
|
if (row.type === "paid_in") expected.cash += row.amountMinor;
|
|
655
782
|
if (row.type === "paid_out") expected.cash -= row.amountMinor;
|
|
656
783
|
}
|
|
657
|
-
|
|
784
|
+
let refundsTotalMinor = 0;
|
|
785
|
+
for (const refund of input.refunds ?? []) {
|
|
786
|
+
if (typeof refund !== "object" || refund === null) continue;
|
|
787
|
+
const byMethod = refund.byMethod;
|
|
788
|
+
if (typeof byMethod !== "object" || byMethod === null || Object.getPrototypeOf(byMethod) !== Object.prototype && Object.getPrototypeOf(byMethod) !== null) continue;
|
|
789
|
+
for (const [method, amount] of Object.entries(byMethod)) {
|
|
790
|
+
if (!method.length || !Number.isSafeInteger(amount) || amount < 0) continue;
|
|
791
|
+
expected[method] = (expected[method] ?? 0) - amount;
|
|
792
|
+
refundsTotalMinor += amount;
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
return {
|
|
796
|
+
expected: { ...expected },
|
|
797
|
+
salesCount: input.orders.length,
|
|
798
|
+
...input.refunds !== void 0 ? { refundsTotalMinor } : {}
|
|
799
|
+
};
|
|
658
800
|
}
|
|
659
801
|
function deriveVariance(counted, expected) {
|
|
660
802
|
return Object.fromEntries(Object.entries(counted).map(([key, value]) => [key, value - (expected[key] ?? 0)]));
|
|
@@ -671,6 +813,7 @@ export {
|
|
|
671
813
|
CommandResultError,
|
|
672
814
|
MAX_COMMANDS_PER_BATCH,
|
|
673
815
|
SUPPORTED_ORDER_CREATE_VERSIONS,
|
|
816
|
+
SUPPORTED_ORDER_REFUND_VERSIONS,
|
|
674
817
|
SUPPORTED_REGISTER_VERSIONS,
|
|
675
818
|
canonicalJson,
|
|
676
819
|
commandFingerprint,
|
|
@@ -687,6 +830,7 @@ export {
|
|
|
687
830
|
payloadShapeErrors,
|
|
688
831
|
platformErrorResult,
|
|
689
832
|
precheckCommand,
|
|
833
|
+
refundPayloadErrors,
|
|
690
834
|
registerPayloadErrors,
|
|
691
835
|
totalWarnings,
|
|
692
836
|
transientOutcome,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tallyui/core",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.9.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Core interfaces, traits, and context providers for Tally UI",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -10,12 +10,14 @@
|
|
|
10
10
|
".": {
|
|
11
11
|
"types": "./dist/index.d.ts",
|
|
12
12
|
"import": "./dist/index.js",
|
|
13
|
-
"source": "./src/index.ts"
|
|
13
|
+
"source": "./src/index.ts",
|
|
14
|
+
"default": "./dist/index.js"
|
|
14
15
|
},
|
|
15
16
|
"./rxdb": {
|
|
16
17
|
"types": "./dist/rxdb/index.d.ts",
|
|
17
18
|
"import": "./dist/rxdb/index.js",
|
|
18
|
-
"source": "./src/rxdb/index.ts"
|
|
19
|
+
"source": "./src/rxdb/index.ts",
|
|
20
|
+
"default": "./dist/rxdb/index.js"
|
|
19
21
|
},
|
|
20
22
|
"./server": {
|
|
21
23
|
"types": "./dist/server/index.d.ts",
|
|
@@ -0,0 +1,333 @@
|
|
|
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 { addNumberPrecision, removeNumberPrecision, roundDiscount } from '../../tax/woocommerce/precision';
|
|
4
|
+
import { getEligibleItems } from './helpers';
|
|
5
|
+
|
|
6
|
+
import type { CouponLineItem } from './helpers';
|
|
7
|
+
|
|
8
|
+
export interface CouponDiscountConfig {
|
|
9
|
+
discount_type: 'percent' | 'fixed_cart' | 'fixed_product';
|
|
10
|
+
amount: string;
|
|
11
|
+
limit_usage_to_x_items: number | null;
|
|
12
|
+
product_ids: number[];
|
|
13
|
+
excluded_product_ids: number[];
|
|
14
|
+
product_categories: number[];
|
|
15
|
+
excluded_product_categories: number[];
|
|
16
|
+
exclude_sale_items: boolean;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface PerItemDiscount {
|
|
20
|
+
product_id: number;
|
|
21
|
+
discount: number;
|
|
22
|
+
/** Stable index into the source line-items array for per-line matching */
|
|
23
|
+
lineIndex?: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface DiscountResult {
|
|
27
|
+
totalDiscount: number;
|
|
28
|
+
perItem: PerItemDiscount[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Calculates coupon discount amounts for the three WooCommerce discount types:
|
|
33
|
+
* - percent: percentage off each eligible item
|
|
34
|
+
* - fixed_cart: fixed amount distributed proportionally across eligible items
|
|
35
|
+
* - fixed_product: fixed amount per unit of each eligible item
|
|
36
|
+
*
|
|
37
|
+
* All calculations use cent-precision math with Math.floor() and penny distribution
|
|
38
|
+
* to match WooCommerce's WC_Discounts class exactly.
|
|
39
|
+
*
|
|
40
|
+
* @param dp - Price decimal places (wc_get_price_decimals), default 2
|
|
41
|
+
*/
|
|
42
|
+
export function calculateCouponDiscount(
|
|
43
|
+
config: CouponDiscountConfig,
|
|
44
|
+
items: CouponLineItem[],
|
|
45
|
+
dp = 2
|
|
46
|
+
): DiscountResult {
|
|
47
|
+
const amount = parseFloat(config.amount) || 0;
|
|
48
|
+
if (amount === 0 || items.length === 0) {
|
|
49
|
+
return { totalDiscount: 0, perItem: [] };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// WooCommerce: fixed_cart + exclude_sale_items rejects the entire coupon
|
|
53
|
+
// when ANY sale item is in the cart. This must be enforced here (not only
|
|
54
|
+
// in validateCoupon) because recalculation can run without re-validation
|
|
55
|
+
// when cart items change after the coupon has been applied.
|
|
56
|
+
if (
|
|
57
|
+
config.discount_type === 'fixed_cart' &&
|
|
58
|
+
config.exclude_sale_items &&
|
|
59
|
+
items.some((item) => item.on_sale)
|
|
60
|
+
) {
|
|
61
|
+
return { totalDiscount: 0, perItem: [] };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const eligible = getEligibleItems(items, {
|
|
65
|
+
product_ids: config.product_ids,
|
|
66
|
+
excluded_product_ids: config.excluded_product_ids,
|
|
67
|
+
product_categories: config.product_categories,
|
|
68
|
+
excluded_product_categories: config.excluded_product_categories,
|
|
69
|
+
exclude_sale_items: config.exclude_sale_items,
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
if (eligible.length === 0) {
|
|
73
|
+
return { totalDiscount: 0, perItem: [] };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
switch (config.discount_type) {
|
|
77
|
+
case 'percent':
|
|
78
|
+
return calculatePercentDiscount(amount, eligible, config.limit_usage_to_x_items, dp);
|
|
79
|
+
case 'fixed_cart':
|
|
80
|
+
// WC: fixed_cart distributes across ALL items, not just category-eligible ones.
|
|
81
|
+
// product_categories/product_ids restrictions only affect validation (the
|
|
82
|
+
// eligible.length === 0 early return above), not which items receive the discount.
|
|
83
|
+
// This matches WC_Discounts::get_items_to_apply_coupon() where is_valid_for_cart()
|
|
84
|
+
// returns true for fixed_cart, bypassing per-item product checks.
|
|
85
|
+
return calculateFixedCartDiscount(amount, items, dp);
|
|
86
|
+
case 'fixed_product':
|
|
87
|
+
return calculateFixedProductDiscount(amount, eligible, config.limit_usage_to_x_items, dp);
|
|
88
|
+
default:
|
|
89
|
+
return { totalDiscount: 0, perItem: [] };
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Select the top N highest-priced units from the given items.
|
|
95
|
+
* Expands each item into individual units, sorts by price descending,
|
|
96
|
+
* takes the top N, and re-aggregates by item index (not product_id,
|
|
97
|
+
* since multiple line items can share the same product_id).
|
|
98
|
+
* Returns the original items unchanged when no limit applies.
|
|
99
|
+
*/
|
|
100
|
+
function selectTopPricedUnits(
|
|
101
|
+
items: CouponLineItem[],
|
|
102
|
+
limitToXItems: number | null
|
|
103
|
+
): CouponLineItem[] {
|
|
104
|
+
if (limitToXItems === null || limitToXItems <= 0) {
|
|
105
|
+
return items;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const expanded: { item: CouponLineItem; itemIndex: number }[] = [];
|
|
109
|
+
items.forEach((item, itemIndex) => {
|
|
110
|
+
for (let i = 0; i < item.quantity; i++) {
|
|
111
|
+
expanded.push({ item, itemIndex });
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
expanded.sort((a, b) => b.item.price - a.item.price);
|
|
115
|
+
|
|
116
|
+
const quantityMap = new Map<number, number>();
|
|
117
|
+
for (const { itemIndex } of expanded.slice(0, limitToXItems)) {
|
|
118
|
+
quantityMap.set(itemIndex, (quantityMap.get(itemIndex) || 0) + 1);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return items.reduce<CouponLineItem[]>((acc, item, itemIndex) => {
|
|
122
|
+
const qty = quantityMap.get(itemIndex);
|
|
123
|
+
if (qty) acc.push({ ...item, quantity: qty });
|
|
124
|
+
return acc;
|
|
125
|
+
}, []);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* WC: WC_Discounts::apply_coupon_percent
|
|
130
|
+
*
|
|
131
|
+
* Percentage discount: shift to cents, floor() per-item, then distribute remainder
|
|
132
|
+
* 1 cent at a time to most-expensive items first.
|
|
133
|
+
*/
|
|
134
|
+
function calculatePercentDiscount(
|
|
135
|
+
percent: number,
|
|
136
|
+
items: CouponLineItem[],
|
|
137
|
+
limitToXItems: number | null,
|
|
138
|
+
dp: number
|
|
139
|
+
): DiscountResult {
|
|
140
|
+
const targetItems = selectTopPricedUnits(items, limitToXItems);
|
|
141
|
+
|
|
142
|
+
// Compute per-item discount in cents using floor
|
|
143
|
+
const itemDiscountsCents: { item: CouponLineItem; discountCents: number; index: number }[] = [];
|
|
144
|
+
let totalDiscountCents = 0;
|
|
145
|
+
|
|
146
|
+
for (let i = 0; i < targetItems.length; i++) {
|
|
147
|
+
const item = targetItems[i];
|
|
148
|
+
const itemTotalCents = addNumberPrecision(item.price * item.quantity, dp);
|
|
149
|
+
const discountCents = Math.floor(itemTotalCents * (percent / 100));
|
|
150
|
+
// Cap at item total
|
|
151
|
+
const cappedCents = Math.min(discountCents, itemTotalCents);
|
|
152
|
+
itemDiscountsCents.push({ item, discountCents: cappedCents, index: i });
|
|
153
|
+
totalDiscountCents += cappedCents;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Calculate exact total discount and distribute remainder
|
|
157
|
+
const exactTotalCents = targetItems.reduce((sum, item) => {
|
|
158
|
+
const itemTotalCents = addNumberPrecision(item.price * item.quantity, dp);
|
|
159
|
+
return sum + itemTotalCents * (percent / 100);
|
|
160
|
+
}, 0);
|
|
161
|
+
const expectedTotalCents = roundDiscount(exactTotalCents, 0);
|
|
162
|
+
|
|
163
|
+
applyCouponRemainder(itemDiscountsCents, expectedTotalCents - totalDiscountCents, dp);
|
|
164
|
+
|
|
165
|
+
// Convert back from cents
|
|
166
|
+
const perItem: PerItemDiscount[] = [];
|
|
167
|
+
let totalDiscount = 0;
|
|
168
|
+
for (const { item, discountCents } of itemDiscountsCents) {
|
|
169
|
+
const discount = removeNumberPrecision(discountCents, dp);
|
|
170
|
+
perItem.push({ product_id: item.product_id, discount, lineIndex: item.lineIndex });
|
|
171
|
+
totalDiscount += discount;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return { totalDiscount: roundDiscount(totalDiscount, dp), perItem };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* WC: WC_Discounts::apply_coupon_fixed_cart
|
|
179
|
+
*
|
|
180
|
+
* Fixed cart discount: floor(amountInCents / itemCount) per item,
|
|
181
|
+
* then distribute remainder via applyCouponRemainder.
|
|
182
|
+
*/
|
|
183
|
+
function calculateFixedCartDiscount(
|
|
184
|
+
amount: number,
|
|
185
|
+
items: CouponLineItem[],
|
|
186
|
+
dp: number
|
|
187
|
+
): DiscountResult {
|
|
188
|
+
// WC filters out zero-price items before counting (apply_coupon_fixed_cart)
|
|
189
|
+
const discountableItems = items.filter((item) => item.price > 0);
|
|
190
|
+
if (discountableItems.length === 0) {
|
|
191
|
+
return { totalDiscount: 0, perItem: [] };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const cartTotalCents = discountableItems.reduce(
|
|
195
|
+
(sum, item) => sum + addNumberPrecision(item.price * item.quantity, dp),
|
|
196
|
+
0
|
|
197
|
+
);
|
|
198
|
+
if (cartTotalCents === 0) {
|
|
199
|
+
return { totalDiscount: 0, perItem: [] };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const amountCents = addNumberPrecision(
|
|
203
|
+
Math.min(amount, removeNumberPrecision(cartTotalCents, dp)),
|
|
204
|
+
dp
|
|
205
|
+
);
|
|
206
|
+
|
|
207
|
+
// Count total discountable units (WC: array_sum(wp_list_pluck($items_to_apply, 'quantity')))
|
|
208
|
+
const totalItemCount = discountableItems.reduce((sum, item) => sum + item.quantity, 0);
|
|
209
|
+
|
|
210
|
+
// Per-item discount = floor(amount in cents / total item count)
|
|
211
|
+
const perItemCents = Math.floor(amountCents / totalItemCount);
|
|
212
|
+
|
|
213
|
+
const itemDiscountsCents: { item: CouponLineItem; discountCents: number; index: number }[] = [];
|
|
214
|
+
let totalDiscountCents = 0;
|
|
215
|
+
|
|
216
|
+
for (let i = 0; i < discountableItems.length; i++) {
|
|
217
|
+
const item = discountableItems[i];
|
|
218
|
+
const itemTotalCents = addNumberPrecision(item.price * item.quantity, dp);
|
|
219
|
+
const discountCents = Math.min(perItemCents * item.quantity, itemTotalCents);
|
|
220
|
+
itemDiscountsCents.push({ item, discountCents, index: i });
|
|
221
|
+
totalDiscountCents += discountCents;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Distribute remainder
|
|
225
|
+
applyCouponRemainder(itemDiscountsCents, amountCents - totalDiscountCents, dp);
|
|
226
|
+
|
|
227
|
+
// Convert back from cents
|
|
228
|
+
const perItem: PerItemDiscount[] = [];
|
|
229
|
+
let totalDiscount = 0;
|
|
230
|
+
for (const { item, discountCents } of itemDiscountsCents) {
|
|
231
|
+
const discount = removeNumberPrecision(discountCents, dp);
|
|
232
|
+
perItem.push({ product_id: item.product_id, discount, lineIndex: item.lineIndex });
|
|
233
|
+
totalDiscount += discount;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
return { totalDiscount: roundDiscount(totalDiscount, dp), perItem };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* WC: WC_Discounts::apply_coupon_fixed_product
|
|
241
|
+
*
|
|
242
|
+
* Fixed product discount: floor(perUnitInCents * qty) per line item,
|
|
243
|
+
* then distribute remainder.
|
|
244
|
+
*/
|
|
245
|
+
function calculateFixedProductDiscount(
|
|
246
|
+
amount: number,
|
|
247
|
+
items: CouponLineItem[],
|
|
248
|
+
limitToXItems: number | null,
|
|
249
|
+
dp: number
|
|
250
|
+
): DiscountResult {
|
|
251
|
+
const targetItems = selectTopPricedUnits(items, limitToXItems);
|
|
252
|
+
|
|
253
|
+
const amountCents = addNumberPrecision(amount, dp);
|
|
254
|
+
|
|
255
|
+
const itemDiscountsCents: { item: CouponLineItem; discountCents: number }[] = [];
|
|
256
|
+
|
|
257
|
+
for (let i = 0; i < targetItems.length; i++) {
|
|
258
|
+
const item = targetItems[i];
|
|
259
|
+
const itemPriceCents = addNumberPrecision(item.price, dp);
|
|
260
|
+
const perUnitCents = Math.min(amountCents, itemPriceCents);
|
|
261
|
+
const discountCents = Math.floor(perUnitCents * item.quantity);
|
|
262
|
+
itemDiscountsCents.push({ item, discountCents });
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// Convert back from cents
|
|
266
|
+
const perItem: PerItemDiscount[] = [];
|
|
267
|
+
let totalDiscount = 0;
|
|
268
|
+
for (const { item, discountCents } of itemDiscountsCents) {
|
|
269
|
+
const discount = removeNumberPrecision(discountCents, dp);
|
|
270
|
+
perItem.push({ product_id: item.product_id, discount, lineIndex: item.lineIndex });
|
|
271
|
+
totalDiscount += discount;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
return { totalDiscount: roundDiscount(totalDiscount, dp), perItem };
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* WC: WC_Discounts::apply_coupon_remainder
|
|
279
|
+
*
|
|
280
|
+
* After floor(), total discount may be less than the intended amount.
|
|
281
|
+
* Distribute the remainder 1 cent at a time to the most expensive items first.
|
|
282
|
+
*
|
|
283
|
+
* Uses iterative redistribution: when a cheap item caps at its full price,
|
|
284
|
+
* the excess flows back to items with remaining capacity. This mirrors WC's
|
|
285
|
+
* recursive apply_coupon_fixed_cart() → apply_coupon_fixed_product() pattern.
|
|
286
|
+
*/
|
|
287
|
+
function applyCouponRemainder(
|
|
288
|
+
itemDiscounts: { item: CouponLineItem; discountCents: number; index: number }[],
|
|
289
|
+
remainderCents: number,
|
|
290
|
+
dp: number
|
|
291
|
+
): void {
|
|
292
|
+
if (remainderCents <= 0) return;
|
|
293
|
+
|
|
294
|
+
let remaining = remainderCents;
|
|
295
|
+
|
|
296
|
+
// Iterative redistribution: keep distributing until remainder = 0
|
|
297
|
+
// or no item can absorb more.
|
|
298
|
+
while (remaining > 0) {
|
|
299
|
+
// Filter to items with remaining capacity, sorted by price descending
|
|
300
|
+
const withCapacity = [...itemDiscounts]
|
|
301
|
+
.filter((entry) => {
|
|
302
|
+
const itemTotalCents = addNumberPrecision(entry.item.price * entry.item.quantity, dp);
|
|
303
|
+
return entry.discountCents < itemTotalCents;
|
|
304
|
+
})
|
|
305
|
+
.sort((a, b) => b.item.price - a.item.price);
|
|
306
|
+
|
|
307
|
+
if (withCapacity.length === 0) break;
|
|
308
|
+
|
|
309
|
+
let distributed = false;
|
|
310
|
+
|
|
311
|
+
for (const entry of withCapacity) {
|
|
312
|
+
const itemTotalCents = addNumberPrecision(entry.item.price * entry.item.quantity, dp);
|
|
313
|
+
const original = itemDiscounts.find((d) => d.index === entry.index);
|
|
314
|
+
if (!original) continue;
|
|
315
|
+
|
|
316
|
+
for (let unit = 0; unit < entry.item.quantity; unit++) {
|
|
317
|
+
if (remaining <= 0) return;
|
|
318
|
+
|
|
319
|
+
if (original.discountCents < itemTotalCents) {
|
|
320
|
+
const addCent = Math.min(1, remaining);
|
|
321
|
+
original.discountCents += addCent;
|
|
322
|
+
remaining -= addCent;
|
|
323
|
+
distributed = true;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
if (remaining <= 0) return;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// If a full pass distributed nothing, no item can absorb more
|
|
331
|
+
if (!distributed) break;
|
|
332
|
+
}
|
|
333
|
+
}
|