@tallyui/core 3.8.0 → 3.9.1
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
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// Ported from @wcpos/order-math, MIT, Copyright (c) 2021-2026 WCPOS.
|
|
2
|
+
// WooCommerce tax parity (ADR-076): keep the arithmetic as in the original; see docs/DECISIONS.md.
|
|
3
|
+
/**
|
|
4
|
+
* Known gaps (ADR-077 amendment 1), missing upstream too, not regressions:
|
|
5
|
+
* - `free_shipping` is not applied;
|
|
6
|
+
* - a coupon's `status` is not checked;
|
|
7
|
+
* - variation-level product restrictions do not match;
|
|
8
|
+
* - misc lines do not match category restrictions;
|
|
9
|
+
* - only `percent`, `fixed_cart` and `fixed_product` are supported;
|
|
10
|
+
* - usage holds are not modelled.
|
|
11
|
+
*
|
|
12
|
+
* Parity unverified (the WooCommerce lane checks each on the dev store):
|
|
13
|
+
* - the minimum and maximum spend basis on a store whose prices include tax;
|
|
14
|
+
* - the email restriction (billing email only, not the account email);
|
|
15
|
+
* - individual use (rejects the new coupon rather than replacing the others);
|
|
16
|
+
* - `fixed_cart` spreading over excluded items;
|
|
17
|
+
* - expiry (an instant against the end of day in the site's timezone);
|
|
18
|
+
* - an inclusive coupon line's `discount + discount_tax`.
|
|
19
|
+
*/
|
|
20
|
+
import { type CouponLineItem, getEligibleItems } from './helpers';
|
|
21
|
+
|
|
22
|
+
import type { CouponRejection, CouponRejectionCode } from './types';
|
|
23
|
+
|
|
24
|
+
export type { CouponRejectionCode, CouponRejection };
|
|
25
|
+
|
|
26
|
+
export interface CouponValidationContext {
|
|
27
|
+
lineItems: CouponLineItem[];
|
|
28
|
+
appliedCoupons: string[];
|
|
29
|
+
appliedCouponsWithIndividualUse?: string[];
|
|
30
|
+
cartSubtotal: number;
|
|
31
|
+
customerEmail: string;
|
|
32
|
+
customerId: number | null;
|
|
33
|
+
/** Epoch ms — the package's only clock input (SPEC §4: no Date.now() inside the engine). */
|
|
34
|
+
now: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export type ValidationResult = { valid: true } | { valid: false; rejection: CouponRejection };
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* WooCommerce sends _gmt fields as bare ISO strings without a Z suffix.
|
|
41
|
+
* JavaScript's Date constructor parses those as local time, which is wrong.
|
|
42
|
+
*/
|
|
43
|
+
function parseGmtDate(dateStr: string): Date {
|
|
44
|
+
if (!/Z|[+-]\d{2}:\d{2}$/.test(dateStr)) {
|
|
45
|
+
return new Date(dateStr + 'Z');
|
|
46
|
+
}
|
|
47
|
+
return new Date(dateStr);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Client-side coupon validation that mirrors WooCommerce's coupon checks.
|
|
52
|
+
*
|
|
53
|
+
* Validates expiry, usage limits, minimum/maximum spend, individual-use rules,
|
|
54
|
+
* email restrictions, and product/category eligibility.
|
|
55
|
+
*/
|
|
56
|
+
export function validateCoupon(coupon: any, context: CouponValidationContext): ValidationResult {
|
|
57
|
+
// 1. Already applied check (case-insensitive, since codes are stored lowercase)
|
|
58
|
+
const codeLower = coupon.code?.toLowerCase();
|
|
59
|
+
if (context.appliedCoupons.some((c: string) => c.toLowerCase() === codeLower)) {
|
|
60
|
+
return { valid: false, rejection: { code: 'already_applied' } };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// 2. Expiry check — parse as UTC since the field is _gmt
|
|
64
|
+
if (coupon.date_expires_gmt) {
|
|
65
|
+
const expiry = parseGmtDate(coupon.date_expires_gmt);
|
|
66
|
+
if (expiry.getTime() < context.now) {
|
|
67
|
+
return { valid: false, rejection: { code: 'expired' } };
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// 3. Usage limit
|
|
72
|
+
if (
|
|
73
|
+
coupon.usage_limit !== null &&
|
|
74
|
+
coupon.usage_limit > 0 &&
|
|
75
|
+
coupon.usage_count >= coupon.usage_limit
|
|
76
|
+
) {
|
|
77
|
+
return { valid: false, rejection: { code: 'usage_limit_reached' } };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// 4. Per-user usage limit
|
|
81
|
+
if (
|
|
82
|
+
coupon.usage_limit_per_user !== null &&
|
|
83
|
+
coupon.usage_limit_per_user > 0 &&
|
|
84
|
+
(context.customerId !== null || context.customerEmail)
|
|
85
|
+
) {
|
|
86
|
+
const identifier =
|
|
87
|
+
context.customerId !== null
|
|
88
|
+
? String(context.customerId)
|
|
89
|
+
: context.customerEmail.toLowerCase();
|
|
90
|
+
const userUsageCount = (coupon.used_by || []).filter(
|
|
91
|
+
(id: string | number) => String(id).toLowerCase() === identifier
|
|
92
|
+
).length;
|
|
93
|
+
if (userUsageCount >= coupon.usage_limit_per_user) {
|
|
94
|
+
return { valid: false, rejection: { code: 'usage_limit_reached_for_customer' } };
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// 5. Minimum amount
|
|
99
|
+
if (coupon.minimum_amount && parseFloat(coupon.minimum_amount) > 0) {
|
|
100
|
+
if (context.cartSubtotal < parseFloat(coupon.minimum_amount)) {
|
|
101
|
+
return {
|
|
102
|
+
valid: false,
|
|
103
|
+
rejection: { code: 'minimum_spend_not_met', params: { amount: coupon.minimum_amount } },
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// 6. Maximum amount
|
|
109
|
+
if (coupon.maximum_amount && parseFloat(coupon.maximum_amount) > 0) {
|
|
110
|
+
if (context.cartSubtotal > parseFloat(coupon.maximum_amount)) {
|
|
111
|
+
return {
|
|
112
|
+
valid: false,
|
|
113
|
+
rejection: { code: 'maximum_spend_exceeded', params: { amount: coupon.maximum_amount } },
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// 7a. Individual use — new coupon has individual_use and others already applied
|
|
119
|
+
if (coupon.individual_use && context.appliedCoupons.length > 0) {
|
|
120
|
+
return {
|
|
121
|
+
valid: false,
|
|
122
|
+
rejection: { code: 'individual_use', params: { code: coupon.code } },
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// 7b. Individual use — an already-applied coupon has individual_use
|
|
127
|
+
if (
|
|
128
|
+
context.appliedCouponsWithIndividualUse &&
|
|
129
|
+
context.appliedCouponsWithIndividualUse.length > 0
|
|
130
|
+
) {
|
|
131
|
+
return {
|
|
132
|
+
valid: false,
|
|
133
|
+
rejection: {
|
|
134
|
+
code: 'individual_use_conflict',
|
|
135
|
+
params: { code: context.appliedCouponsWithIndividualUse[0] },
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// 8. Email restrictions
|
|
141
|
+
if (coupon.email_restrictions && coupon.email_restrictions.length > 0) {
|
|
142
|
+
if (!context.customerEmail) {
|
|
143
|
+
return { valid: false, rejection: { code: 'email_required' } };
|
|
144
|
+
}
|
|
145
|
+
const emailLower = context.customerEmail.toLowerCase();
|
|
146
|
+
const matches = coupon.email_restrictions.some((pattern: string) => {
|
|
147
|
+
const patternLower = pattern.toLowerCase().trim();
|
|
148
|
+
if (patternLower.includes('*')) {
|
|
149
|
+
// Escape regex special characters, then convert \* back to .*
|
|
150
|
+
const regex = new RegExp(
|
|
151
|
+
'^' + patternLower.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\\\*/g, '.*') + '$'
|
|
152
|
+
);
|
|
153
|
+
return regex.test(emailLower);
|
|
154
|
+
}
|
|
155
|
+
return emailLower === patternLower;
|
|
156
|
+
});
|
|
157
|
+
if (!matches) {
|
|
158
|
+
return { valid: false, rejection: { code: 'email_not_allowed' } };
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// 9. Product/category restrictions — check that at least one item is eligible
|
|
163
|
+
const eligible = getEligibleItems(context.lineItems, {
|
|
164
|
+
product_ids: coupon.product_ids || [],
|
|
165
|
+
excluded_product_ids: coupon.excluded_product_ids || [],
|
|
166
|
+
product_categories: coupon.product_categories || [],
|
|
167
|
+
excluded_product_categories: coupon.excluded_product_categories || [],
|
|
168
|
+
exclude_sale_items: coupon.exclude_sale_items || false,
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
const hasRestrictions =
|
|
172
|
+
coupon.product_ids?.length > 0 ||
|
|
173
|
+
coupon.excluded_product_ids?.length > 0 ||
|
|
174
|
+
coupon.product_categories?.length > 0 ||
|
|
175
|
+
coupon.excluded_product_categories?.length > 0 ||
|
|
176
|
+
coupon.exclude_sale_items;
|
|
177
|
+
|
|
178
|
+
if (hasRestrictions && eligible.length === 0) {
|
|
179
|
+
return { valid: false, rejection: { code: 'not_applicable_to_cart' } };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// 9b. WooCommerce: fixed_cart + exclude_sale_items rejects the entire coupon
|
|
183
|
+
// when ANY sale item is in the cart, even if non-sale items exist.
|
|
184
|
+
if (
|
|
185
|
+
coupon.discount_type === 'fixed_cart' &&
|
|
186
|
+
coupon.exclude_sale_items &&
|
|
187
|
+
context.lineItems.some((item) => item.on_sale)
|
|
188
|
+
) {
|
|
189
|
+
return { valid: false, rejection: { code: 'not_applicable_to_cart' } };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
return { valid: true };
|
|
193
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -41,6 +41,8 @@ export type { StoreSettingsErrorCode, StoreSettingsChoices } from './store-setti
|
|
|
41
41
|
export type {
|
|
42
42
|
CommandType, CommandEnvelope, CommandStatus, CommandServerRefs,
|
|
43
43
|
RegisterCommandType, RegisterCommandEnvelope, AnyCommandEnvelope,
|
|
44
|
+
OrderRefundLine, OrderRefundPayload, OrderRefundEnvelope, OrderRefundResult, OrderRefundRejectionCode,
|
|
45
|
+
OrderRefundQuantityExceedsData, OrderRefundAmountMismatchData, OrderRefundOrderStateData, OrderRefundNoOpenSessionData,
|
|
44
46
|
CommandWarning, CommandError, CommandResult, OrderCreateLine,
|
|
45
47
|
PaymentMethodKind, OrderCreatePayment, OrderCreatePayload, OrderCreateEnvelope,
|
|
46
48
|
OrderCreateDisplay, OrderCreateTaxRate,
|
|
@@ -78,3 +80,4 @@ export {
|
|
|
78
80
|
} from './context/connector-context';
|
|
79
81
|
export type { ConnectorProviderProps } from './context/connector-context';
|
|
80
82
|
export * as woocommerceTax from './tax/woocommerce';
|
|
83
|
+
export * as woocommerceCoupons from './coupons/woocommerce';
|
package/src/server/batch.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { payloadBoundErrors, payloadShapeErrors } from './order-payload-shape'
|
|
|
8
8
|
export type ValidatedCommandEnvelope =
|
|
9
9
|
| (Omit<CommandEnvelope<Record<string, unknown>>, 'version'> & { type: 'order.create'; version: number })
|
|
10
10
|
| RegisterCommandEnvelope<Record<string, unknown>>
|
|
11
|
+
| (Omit<CommandEnvelope<Record<string, unknown>>, 'type' | 'version'> & { type: 'order.refund'; version: number })
|
|
11
12
|
|
|
12
13
|
/** Validates every envelope before any command is claimed. */
|
|
13
14
|
export function validateBatch(body: unknown):
|
|
@@ -30,7 +31,7 @@ export function validateBatch(body: unknown):
|
|
|
30
31
|
}
|
|
31
32
|
let field: string | undefined
|
|
32
33
|
if (typeof command.id !== 'string' || command.id.length === 0 || command.id.length > 64) field = 'id'
|
|
33
|
-
else if (!['order.create', 'register.session.open', 'register.session.transition', 'register.movement.record',
|
|
34
|
+
else if (!['order.create', 'order.refund', 'register.session.open', 'register.session.transition', 'register.movement.record',
|
|
34
35
|
'register.movement.void', 'register.closure.submit'].includes(command.type)) field = 'type'
|
|
35
36
|
else if (!Number.isSafeInteger(command.version) || command.version < 1) field = 'version'
|
|
36
37
|
else if (typeof command.payload !== 'object' || command.payload === null || Array.isArray(command.payload)) field = 'payload'
|
|
@@ -57,14 +58,24 @@ export function validateBatch(body: unknown):
|
|
|
57
58
|
*
|
|
58
59
|
* `supported` is the SERVER's own list (what its /info advertises), never core's constants, which are the
|
|
59
60
|
* till's capability (#297). The version check, the `unsupported_version` message and its `data` all use it:
|
|
60
|
-
* `precheckCommand(envelope, { orderCreate: [1, 2, 3], register: [1] })
|
|
61
|
+
* `precheckCommand(envelope, { orderCreate: [1, 2, 3], register: [1], orderRefund: [1] })` (`orderRefund` is optional).
|
|
61
62
|
*/
|
|
62
63
|
export function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCommandEnvelope, 'id' | 'type' | 'version' | 'payload'>,
|
|
63
|
-
supported: { orderCreate: readonly number[]; register: readonly number[] }): CommandResult | undefined {
|
|
64
|
+
supported: { orderCreate: readonly number[]; register: readonly number[]; orderRefund?: readonly number[] }): CommandResult | undefined {
|
|
64
65
|
// An empty list would send Math.max() of nothing (-Infinity, null in JSON) as the server's version.
|
|
65
66
|
for (const key of ['orderCreate', 'register'] as const) {
|
|
66
67
|
if (!supported[key]?.length) throw new TypeError(`precheckCommand: supported.${key} must list at least one version`)
|
|
67
68
|
}
|
|
69
|
+
if (envelope.type === 'order.refund') {
|
|
70
|
+
const versions = supported.orderRefund ?? []
|
|
71
|
+
if (!versions.includes(envelope.version)) {
|
|
72
|
+
return { id: envelope.id, status: 'rejected', error: { code: 'unsupported_version',
|
|
73
|
+
message: `order.refund version ${envelope.version} is not supported; this server ${versions.length ? `supports ${versions.join(', ')}` : 'takes no refunds'}`,
|
|
74
|
+
data: { orderRefund: versions.length ? Math.max(...versions) : 0 },
|
|
75
|
+
} }
|
|
76
|
+
}
|
|
77
|
+
return undefined
|
|
78
|
+
}
|
|
68
79
|
if (envelope.type !== 'order.create') {
|
|
69
80
|
if (!supported.register.includes(envelope.version)) {
|
|
70
81
|
return { id: envelope.id, status: 'rejected', error: { code: 'unsupported_version',
|
|
@@ -43,7 +43,33 @@ export function parseCommandResult(value: unknown): CommandResult {
|
|
|
43
43
|
if (!object(input.register)) throw new CommandResultError('Invalid register')
|
|
44
44
|
result.register = input.register as RegisterCommandResult
|
|
45
45
|
}
|
|
46
|
-
if (
|
|
46
|
+
if (input.refund !== undefined) {
|
|
47
|
+
if (!object(input.refund)) throw new CommandResultError('Invalid refund')
|
|
48
|
+
const refund = input.refund as Record<string, unknown>
|
|
49
|
+
if (!Number.isSafeInteger(refund.totalMinor) || (refund.totalMinor as number) < 0) throw new CommandResultError('Invalid refund.totalMinor')
|
|
50
|
+
if (!object(refund.byMethod)) throw new CommandResultError('Invalid refund.byMethod')
|
|
51
|
+
const byMethod = Object.fromEntries(Object.entries(refund.byMethod as Record<string, unknown>).map(([key, amount]) => {
|
|
52
|
+
if (!key.length) throw new CommandResultError('Invalid refund.byMethod')
|
|
53
|
+
if (!Number.isSafeInteger(amount) || (amount as number) < 0) throw new CommandResultError(`Invalid refund.byMethod.${key}`)
|
|
54
|
+
return [key, amount as number]
|
|
55
|
+
}))
|
|
56
|
+
if (Object.values(byMethod).reduce((sum, amount) => sum + amount, 0) !== refund.totalMinor) throw new CommandResultError('Invalid refund.byMethod')
|
|
57
|
+
if (!Array.isArray(refund.refunds) || refund.refunds.length === 0) throw new CommandResultError('Invalid refund.refunds')
|
|
58
|
+
const refunds = refund.refunds.map((value: unknown, index) => {
|
|
59
|
+
const field = `refund.refunds[${index}]`
|
|
60
|
+
if (!object(value)) throw new CommandResultError(`Invalid ${field}`)
|
|
61
|
+
const entry = value as Record<string, unknown>
|
|
62
|
+
for (const key of ['id', 'paymentId']) {
|
|
63
|
+
if (typeof entry[key] !== 'string' || entry[key].length === 0) throw new CommandResultError(`Invalid ${field}.${key}`)
|
|
64
|
+
}
|
|
65
|
+
if (!Number.isSafeInteger(entry.totalMinor) || (entry.totalMinor as number) < 0) throw new CommandResultError(`Invalid ${field}.totalMinor`)
|
|
66
|
+
if (typeof entry.state !== 'string' || entry.state.length === 0) throw new CommandResultError(`Invalid ${field}.state`)
|
|
67
|
+
return { id: entry.id as string, paymentId: entry.paymentId as string, totalMinor: entry.totalMinor as number, state: entry.state }
|
|
68
|
+
})
|
|
69
|
+
if (refunds.reduce((sum, entry) => sum + entry.totalMinor, 0) !== refund.totalMinor) throw new CommandResultError('Invalid refund.refunds')
|
|
70
|
+
result.refund = { totalMinor: refund.totalMinor as number, byMethod, refunds }
|
|
71
|
+
}
|
|
72
|
+
if (result.status === 'applied' && result.serverRefs === undefined && result.register === undefined && result.refund === undefined) {
|
|
47
73
|
throw new CommandResultError('Invalid serverRefs: required for applied')
|
|
48
74
|
}
|
|
49
75
|
if (input.warnings !== undefined) {
|
package/src/server/index.ts
CHANGED
|
@@ -3,7 +3,7 @@ export { canonicalJson, commandFingerprint } from './fingerprint'
|
|
|
3
3
|
export { payloadBoundErrors, payloadShapeErrors } from './order-payload-shape'
|
|
4
4
|
export { fiscalFiguresErrors } from './fiscal-figures'
|
|
5
5
|
export type { CommandErrorWithData, OrderCreateDisplay, OrderCreateTaxRate, OrderCreatePayloadV3 } from './fiscal-figures'
|
|
6
|
-
export { SUPPORTED_ORDER_CREATE_VERSIONS, SUPPORTED_REGISTER_VERSIONS } from './versions'
|
|
6
|
+
export { SUPPORTED_ORDER_CREATE_VERSIONS, SUPPORTED_REGISTER_VERSIONS, SUPPORTED_ORDER_REFUND_VERSIONS } from './versions'
|
|
7
7
|
export { MAX_COMMANDS_PER_BATCH } from '../commands'
|
|
8
8
|
export { validateBatch, precheckCommand } from './batch'
|
|
9
9
|
export type { ValidatedCommandEnvelope } from './batch'
|
|
@@ -14,6 +14,7 @@ export { totalWarnings } from './total-warnings'
|
|
|
14
14
|
export type { OrderRejectionCode, Rejection } from './total-warnings'
|
|
15
15
|
export { parseCommandResult, CommandResultError } from './command-result'
|
|
16
16
|
export { registerPayloadErrors } from './register-payload-shape'
|
|
17
|
+
export { refundPayloadErrors } from './refund-payload-shape'
|
|
17
18
|
export { deriveSessionFigures, deriveVariance } from './register-figures'
|
|
18
19
|
export type { RegisterConflictCode, RegisterOutcome } from './register-outcome'
|
|
19
20
|
export { platformErrorResult, internalErrorResult } from './rejection-codes'
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/** Strict shape errors per ADR-070 and ADR-080 for order.refund v1; plugins run this before any lookup. */
|
|
2
|
+
export function refundPayloadErrors(payload: unknown): string[] {
|
|
3
|
+
const errors: string[] = []
|
|
4
|
+
const object = (value: unknown): value is Record<string, unknown> =>
|
|
5
|
+
typeof value === 'object' && value !== null && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)
|
|
6
|
+
const check = (valid: boolean, field: string, expected: string) => {
|
|
7
|
+
if (!valid && errors.length < 10) errors.push(`${field}: expected ${expected}`)
|
|
8
|
+
}
|
|
9
|
+
if (!object(payload)) return ['payload: expected an object']
|
|
10
|
+
const noNul = (value: unknown, field: string) => {
|
|
11
|
+
if (typeof value === 'string') check(!value.includes('\u0000'), field, 'no NUL character')
|
|
12
|
+
}
|
|
13
|
+
const fields = ['clientRefundId', 'orderId', 'registerId', 'sessionId', 'clientOrderId', 'cashierRef',
|
|
14
|
+
'lines', 'shippingMinor', 'totalMinor', 'adjustmentMinor', 'destination', 'reason', 'createdAt']
|
|
15
|
+
for (const key of Object.keys(payload)) {
|
|
16
|
+
if (!fields.includes(key) && errors.length < 10) {
|
|
17
|
+
errors.push(`${key.includes('\u0000') ? JSON.stringify(key) : key}: unknown field for order.refund version 1`)
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
for (const field of ['clientRefundId', 'orderId', 'registerId', 'sessionId', 'clientOrderId', 'cashierRef']) {
|
|
21
|
+
const value = payload[field]
|
|
22
|
+
if (['clientOrderId', 'cashierRef'].includes(field) && value === undefined) continue
|
|
23
|
+
check(typeof value === 'string' && value.length > 0 && value.length <= 64,
|
|
24
|
+
field, 'a non-empty string of at most 64 characters')
|
|
25
|
+
noNul(value, field)
|
|
26
|
+
}
|
|
27
|
+
check(Array.isArray(payload.lines) && payload.lines.length <= 500, 'lines', 'an array of at most 500 lines')
|
|
28
|
+
const seen = new Set<string>()
|
|
29
|
+
if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
|
|
30
|
+
const path = `lines[${index}]`
|
|
31
|
+
if (!object(line)) {
|
|
32
|
+
check(false, path, 'an object')
|
|
33
|
+
return
|
|
34
|
+
}
|
|
35
|
+
for (const key of Object.keys(line)) {
|
|
36
|
+
if (!['orderLineId', 'quantity', 'restock'].includes(key) && errors.length < 10) {
|
|
37
|
+
errors.push(`${path}.${key.includes('\u0000') ? JSON.stringify(key) : key}: unknown field for order.refund version 1`)
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
check(typeof line.orderLineId === 'string' && line.orderLineId.length > 0 && line.orderLineId.length <= 64,
|
|
41
|
+
`${path}.orderLineId`, 'a non-empty string of at most 64 characters')
|
|
42
|
+
noNul(line.orderLineId, `${path}.orderLineId`)
|
|
43
|
+
if (typeof line.orderLineId === 'string') {
|
|
44
|
+
check(!seen.has(line.orderLineId), `${path}.orderLineId`, 'unique in lines')
|
|
45
|
+
seen.add(line.orderLineId)
|
|
46
|
+
}
|
|
47
|
+
check(Number.isSafeInteger(line.quantity) && (line.quantity as number) >= 1, `${path}.quantity`, 'a safe integer >= 1')
|
|
48
|
+
check(typeof line.restock === 'boolean', `${path}.restock`, 'a boolean')
|
|
49
|
+
})
|
|
50
|
+
for (const field of ['shippingMinor', 'totalMinor']) {
|
|
51
|
+
check(Number.isSafeInteger(payload[field]) && (payload[field] as number) >= 0, field, 'a safe integer >= 0')
|
|
52
|
+
}
|
|
53
|
+
check(Number.isSafeInteger(payload.adjustmentMinor), 'adjustmentMinor', 'a safe integer')
|
|
54
|
+
check(payload.destination === 'original_method' || payload.destination === 'cash', 'destination', 'original_method or cash')
|
|
55
|
+
noNul(payload.destination, 'destination')
|
|
56
|
+
check(typeof payload.reason === 'string' && payload.reason.trim().length > 0 && payload.reason.length <= 500,
|
|
57
|
+
'reason', 'a non-empty string after trim of at most 500 characters')
|
|
58
|
+
noNul(payload.reason, 'reason')
|
|
59
|
+
check(typeof payload.createdAt === 'string' && payload.createdAt.length > 0 && !Number.isNaN(Date.parse(payload.createdAt)),
|
|
60
|
+
'createdAt', 'a valid date')
|
|
61
|
+
noNul(payload.createdAt, 'createdAt')
|
|
62
|
+
return errors
|
|
63
|
+
}
|
|
@@ -2,13 +2,15 @@
|
|
|
2
2
|
* A session's expected figures per method: the counted float in cash, plus each order's payments, plus paid_in
|
|
3
3
|
* and minus paid_out movements that are not voided. The plugin chooses which orders count (for Medusa: completed,
|
|
4
4
|
* archived and cancelled POS orders, so a received sale stays counted after an admin archives or cancels it) and
|
|
5
|
-
* passes each order's recorded POS payments; this function only sums.
|
|
5
|
+
* passes each order's recorded POS payments; this function only sums. Refunds made in the session (by the refund's
|
|
6
|
+
* own sessionId, ADR-080) lower expected per method.
|
|
6
7
|
*/
|
|
7
8
|
export function deriveSessionFigures(input: {
|
|
8
9
|
countedFloatMinor: number
|
|
9
10
|
orders: { payments: { method: string; amountMinor: number }[] }[]
|
|
10
11
|
movements: { id: string; type: 'paid_in' | 'paid_out' | 'no_sale' | 'void'; amountMinor: number; voids: string | null }[]
|
|
11
|
-
|
|
12
|
+
refunds?: { byMethod: Record<string, number> }[]
|
|
13
|
+
}): { expected: Record<string, number>; salesCount: number; refundsTotalMinor?: number } {
|
|
12
14
|
const expected: Record<string, number> = Object.assign(Object.create(null), { cash: input.countedFloatMinor })
|
|
13
15
|
// tally_payments is order metadata an admin could edit, and a malformed row must never make register commands transient.
|
|
14
16
|
for (const order of input.orders) {
|
|
@@ -24,7 +26,20 @@ export function deriveSessionFigures(input: {
|
|
|
24
26
|
if (row.type === 'paid_in') expected.cash += row.amountMinor
|
|
25
27
|
if (row.type === 'paid_out') expected.cash -= row.amountMinor
|
|
26
28
|
}
|
|
27
|
-
|
|
29
|
+
let refundsTotalMinor = 0
|
|
30
|
+
for (const refund of input.refunds ?? []) {
|
|
31
|
+
if (typeof refund !== 'object' || refund === null) continue
|
|
32
|
+
const byMethod = refund.byMethod
|
|
33
|
+
if (typeof byMethod !== 'object' || byMethod === null ||
|
|
34
|
+
(Object.getPrototypeOf(byMethod) !== Object.prototype && Object.getPrototypeOf(byMethod) !== null)) continue
|
|
35
|
+
for (const [method, amount] of Object.entries(byMethod)) {
|
|
36
|
+
if (!method.length || !Number.isSafeInteger(amount) || amount < 0) continue
|
|
37
|
+
expected[method] = (expected[method] ?? 0) - amount
|
|
38
|
+
refundsTotalMinor += amount
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return { expected: { ...expected }, salesCount: input.orders.length,
|
|
42
|
+
...(input.refunds !== undefined ? { refundsTotalMinor } : {}) }
|
|
28
43
|
}
|
|
29
44
|
|
|
30
45
|
export function deriveVariance(counted: Record<string, number>, expected: Record<string, number>): Record<string, number> {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CommandResult } from '../types'
|
|
1
|
+
import type { CommandResult, OrderRefundRejectionCode } from '../types'
|
|
2
2
|
import type { OrderRejectionCode } from './total-warnings'
|
|
3
3
|
import type { RegisterConflictCode } from './register-outcome'
|
|
4
4
|
|
|
@@ -7,12 +7,12 @@ import type { RegisterConflictCode } from './register-outcome'
|
|
|
7
7
|
export type CommandRejectionCode =
|
|
8
8
|
| 'invalid_payload' | 'unsupported_version' | 'idempotency_mismatch' | 'store_configuration' | 'platform_error'
|
|
9
9
|
| 'insufficient_stock' | 'unsupported_tax_mode' | 'internal_error'
|
|
10
|
-
| OrderRejectionCode | RegisterConflictCode
|
|
10
|
+
| OrderRejectionCode | RegisterConflictCode | OrderRefundRejectionCode
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
* The rejected result for a platform-native error the plugin has judged permanent (a replay would fail
|
|
14
14
|
* the same way, e.g. a Vendure ErrorResult code) and the contract has no code for. `platform_error` is
|
|
15
|
-
* for `order.create`
|
|
15
|
+
* for `order.create` and `order.refund` (ADR-080): a rejected register command halts that register's queue until c2c,
|
|
16
16
|
* so register refusals use the ADR-068 codes.
|
|
17
17
|
*
|
|
18
18
|
* Return it only when the platform made no durable change for this command: the plugin threw so its
|
|
@@ -39,7 +39,7 @@ export function platformErrorResult(id: string, platformCode: string, platformMe
|
|
|
39
39
|
* the correlation id links it to the plugin's log.
|
|
40
40
|
*
|
|
41
41
|
* Database, network, unknown-SQLSTATE and any other unclassifiable errors stay transient (503), never
|
|
42
|
-
* `internal_error`. `order.create`
|
|
42
|
+
* `internal_error`. `order.create` and `order.refund` (ADR-080), as for `platform_error`.
|
|
43
43
|
*
|
|
44
44
|
* See ADR-038's `internal_error` amendment (needs-admin on a failed compensation; on Vendure only
|
|
45
45
|
* before the first write).
|
package/src/server/versions.ts
CHANGED
|
@@ -7,3 +7,5 @@
|
|
|
7
7
|
export const SUPPORTED_ORDER_CREATE_VERSIONS: readonly number[] = [1, 2, 3, 4]
|
|
8
8
|
/** The till's capability for the contract versions shared by all five register commands; a server passes its own. */
|
|
9
9
|
export const SUPPORTED_REGISTER_VERSIONS: readonly number[] = [1]
|
|
10
|
+
/** The till's capability for order.refund versions (ADR-080); a server passes its own. */
|
|
11
|
+
export const SUPPORTED_ORDER_REFUND_VERSIONS: readonly number[] = [1]
|
package/src/types/commands.ts
CHANGED
|
@@ -22,7 +22,37 @@ export type RegisterCommandType = 'register.session.open' | 'register.session.tr
|
|
|
22
22
|
export type RegisterCommandEnvelope<P = Record<string, unknown>> =
|
|
23
23
|
Omit<CommandEnvelope<P>, 'type' | 'version'> & { type: RegisterCommandType; version: number };
|
|
24
24
|
/** Any command a transport can carry. */
|
|
25
|
-
export type AnyCommandEnvelope = CommandEnvelope<unknown> | RegisterCommandEnvelope<unknown>;
|
|
25
|
+
export type AnyCommandEnvelope = CommandEnvelope<unknown> | RegisterCommandEnvelope<unknown> | OrderRefundEnvelope<unknown>;
|
|
26
|
+
|
|
27
|
+
/** A line's refunded quantity and restock choice (ADR-080). */
|
|
28
|
+
export interface OrderRefundLine { orderLineId: string; quantity: number; restock: boolean }
|
|
29
|
+
/** An online refund against an order, attributed to the refunding session (ADR-080). */
|
|
30
|
+
export interface OrderRefundPayload {
|
|
31
|
+
clientRefundId: string; orderId: string; clientOrderId?: string; lines: OrderRefundLine[];
|
|
32
|
+
shippingMinor: number; adjustmentMinor: number; totalMinor: number;
|
|
33
|
+
destination: 'original_method' | 'cash'; reason: string;
|
|
34
|
+
registerId: string; sessionId: string; cashierRef?: string; createdAt: string;
|
|
35
|
+
}
|
|
36
|
+
/** An order.refund v1 command with the shared idempotency envelope (ADR-080). */
|
|
37
|
+
export type OrderRefundEnvelope<P = OrderRefundPayload> =
|
|
38
|
+
Omit<CommandEnvelope<P>, 'type' | 'version'> & { type: 'order.refund'; version: 1 };
|
|
39
|
+
/** The server's refund total, tender attribution and platform refunds (ADR-080). */
|
|
40
|
+
export interface OrderRefundResult {
|
|
41
|
+
totalMinor: number;
|
|
42
|
+
byMethod: Record<string, number>;
|
|
43
|
+
refunds: Array<{ id: string; paymentId: string; totalMinor: number; state: string }>;
|
|
44
|
+
}
|
|
45
|
+
/** Per-command refund refusals (ADR-080 decision 5). */
|
|
46
|
+
export type OrderRefundRejectionCode = 'nothing_to_refund' | 'quantity_exceeds' | 'amount_mismatch'
|
|
47
|
+
| 'order_state' | 'not_till_order' | 'forbidden' | 'no_open_session';
|
|
48
|
+
/** Lines exceeding the server's refundable quantities (ADR-080). */
|
|
49
|
+
export interface OrderRefundQuantityExceedsData { lines: Array<{ orderLineId: string; quantity: number; refundableQuantity: number }> }
|
|
50
|
+
/** The till's expected refund and the server's computed amount (ADR-080). */
|
|
51
|
+
export interface OrderRefundAmountMismatchData { expectedMinor: number; serverMinor: number }
|
|
52
|
+
/** The order state preventing a refund (ADR-080). */
|
|
53
|
+
export interface OrderRefundOrderStateData { state: string }
|
|
54
|
+
/** The session that is not open on the refunding register (ADR-080). */
|
|
55
|
+
export interface OrderRefundNoOpenSessionData { sessionId: string }
|
|
26
56
|
|
|
27
57
|
/** An order.create envelope: 5 is 4 plus fees, shipping and custom lines (ADR-075), sent only for an order that has one. */
|
|
28
58
|
export type OrderCreateEnvelope = CommandEnvelope<OrderCreatePayload> & { type: 'order.create'; version: 1 | 2 | 3 | 4 | 5 };
|
|
@@ -106,6 +136,7 @@ export interface CommandResult {
|
|
|
106
136
|
warnings?: CommandWarning[];
|
|
107
137
|
error?: CommandError;
|
|
108
138
|
register?: RegisterCommandResult;
|
|
139
|
+
refund?: OrderRefundResult;
|
|
109
140
|
}
|
|
110
141
|
|
|
111
142
|
/** A register command's server figures (registers c2b applies them). */
|
package/src/types/connector.ts
CHANGED
|
@@ -41,6 +41,8 @@ export interface ServerCapabilities {
|
|
|
41
41
|
orderCreate: number;
|
|
42
42
|
/** The highest `register` contract version; absent or 0 means no register sync. */
|
|
43
43
|
register?: number;
|
|
44
|
+
/** The highest `order.refund` version; absent or 0 means the store takes no refunds and the app hides the action (ADR-080). */
|
|
45
|
+
orderRefund?: number;
|
|
44
46
|
/** How the store rounds tax (#287). Absent: an older server, per_order + half_away_from_zero. */
|
|
45
47
|
taxRounding?: TaxRounding;
|
|
46
48
|
/** Whether one order may carry several payments. Absent means it may: order.create's `payments` has always been a
|
|
@@ -52,6 +54,11 @@ export interface ServerCapabilities {
|
|
|
52
54
|
* `none` is `taxStatus: 'none'`, `classes` is a `taxClass`. Absent means neither; the UI hides what is false.
|
|
53
55
|
*/
|
|
54
56
|
lineTax?: { none: boolean; classes: boolean };
|
|
57
|
+
/**
|
|
58
|
+
* Whether the store accepts an order's coupons (ADR-077). Absent means it does not: the till refuses to apply a
|
|
59
|
+
* coupon. WooCommerce: true only when the woocommerce-pos plugin reports 1.9.0 or later.
|
|
60
|
+
*/
|
|
61
|
+
coupons?: boolean;
|
|
55
62
|
}
|
|
56
63
|
|
|
57
64
|
/** #287, ADR-071. `custom`: the till computes as when absent; that server never emits `figures_mismatch` for subtotal or tax. */
|
|
@@ -116,6 +123,7 @@ const maxVersion = (list: unknown): number | undefined => {
|
|
|
116
123
|
* Reads a 2xx body of `GET /tally/v1/info` (ADR-062): `orderCreate` is the max of
|
|
117
124
|
* `contracts["order.create"]`, or 1 when it's missing or malformed; `register` is the max of
|
|
118
125
|
* `contracts.register` when valid; `taxRounding` is the top-level sibling of `contracts` (#287); malformed `lineTax` is ignored.
|
|
126
|
+
* `orderRefund` is the max of `contracts["order.refund"]` when valid, otherwise absent (ADR-080).
|
|
119
127
|
* Absent `taxRounding` uses the default; a present malformed value is unknown, so settings wait.
|
|
120
128
|
* A non-object body is also unknown, not a statement of the store's defaults.
|
|
121
129
|
*/
|
|
@@ -126,6 +134,7 @@ export function parseInfoCapabilities(body: unknown, warn?: (reason: string) =>
|
|
|
126
134
|
}
|
|
127
135
|
const { contracts, taxRounding, lineTax } = body as { contracts?: Record<string, unknown> | null; taxRounding?: unknown; lineTax?: unknown };
|
|
128
136
|
const register = maxVersion(contracts?.register);
|
|
137
|
+
const orderRefund = maxVersion(contracts?.['order.refund']);
|
|
129
138
|
const rounding = parseTaxRounding(taxRounding);
|
|
130
139
|
if (taxRounding !== undefined && rounding === undefined) {
|
|
131
140
|
warn?.(`malformed taxRounding: rounding is unknown, so settings wait: ${JSON.stringify(taxRounding)}`);
|
|
@@ -133,6 +142,7 @@ export function parseInfoCapabilities(body: unknown, warn?: (reason: string) =>
|
|
|
133
142
|
}
|
|
134
143
|
const parsedLineTax = parseLineTax(lineTax, warn);
|
|
135
144
|
return { orderCreate: maxVersion(contracts?.['order.create']) ?? 1,
|
|
145
|
+
...(orderRefund !== undefined ? { orderRefund } : {}),
|
|
136
146
|
...(register !== undefined ? { register } : {}), ...(rounding ? { taxRounding: rounding } : {}),
|
|
137
147
|
...(parsedLineTax ? { lineTax: parsedLineTax } : {}) };
|
|
138
148
|
}
|
|
@@ -258,6 +268,12 @@ export interface TallyConnector {
|
|
|
258
268
|
calculatedPrices?: FingerprintReconcileAdapter;
|
|
259
269
|
/** The daily catalogue check (#248): refetches what differs, deletes only with proof. */
|
|
260
270
|
catalogue?: CatalogueReconcileAdapter;
|
|
271
|
+
/**
|
|
272
|
+
* The coupons' only source (ADR-077 amendment 2): a catalogue reconcile over the coupon listing, whose
|
|
273
|
+
* fingerprint carries the usage that never moves the modified time. Optional: a connector without it has no
|
|
274
|
+
* coupons, and the coupons feature is gated on it.
|
|
275
|
+
*/
|
|
276
|
+
coupons?: CatalogueReconcileAdapter;
|
|
261
277
|
};
|
|
262
278
|
|
|
263
279
|
/**
|
package/src/types/index.ts
CHANGED
|
@@ -29,6 +29,8 @@ export type { CustomerTraits } from './traits/customer';
|
|
|
29
29
|
export type {
|
|
30
30
|
CommandType, CommandEnvelope, CommandStatus, CommandServerRefs,
|
|
31
31
|
RegisterCommandType, RegisterCommandEnvelope, AnyCommandEnvelope,
|
|
32
|
+
OrderRefundLine, OrderRefundPayload, OrderRefundEnvelope, OrderRefundResult, OrderRefundRejectionCode,
|
|
33
|
+
OrderRefundQuantityExceedsData, OrderRefundAmountMismatchData, OrderRefundOrderStateData, OrderRefundNoOpenSessionData,
|
|
32
34
|
CommandWarning, CommandError, CommandResult, OrderCreateLine,
|
|
33
35
|
PaymentMethodKind, OrderCreatePayment, OrderCreatePayload, OrderCreateEnvelope,
|
|
34
36
|
OrderCreateDisplay, OrderCreateTaxRate,
|
|
@@ -13,6 +13,8 @@ export interface StoreSettings {
|
|
|
13
13
|
/** WooCommerce rates already filtered to the store's tax address; the empty class uses `standard`. */
|
|
14
14
|
taxRates?: Record<string, { id: number; code: string; label: string; rate: string; priority: number; compound: boolean; shipping: boolean }[]>;
|
|
15
15
|
taxRoundAtSubtotal?: boolean;
|
|
16
|
+
/** WooCommerce's calculate coupon discounts sequentially setting. */
|
|
17
|
+
calcDiscountsSequentially?: boolean;
|
|
16
18
|
shippingTaxClass?: string;
|
|
17
19
|
taxClassSlugs?: string[];
|
|
18
20
|
/** Connector-specific and opaque to the app: what the connector needs to price documents. The app passes it back to the connector unchanged, and never logs it. */
|