@tallyui/core 4.2.0 → 5.0.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/{chunk-XF3RD6GX.js → chunk-RPBSJ3FB.js} +62 -2
- package/dist/index.d.ts +10 -4
- package/dist/index.js +25 -7
- package/dist/{tax-rate-DCJhfJbZ.d.ts → refund-share-BZ_Ff9Zk.d.ts} +145 -3
- package/dist/server/index.cjs +96 -2
- package/dist/server/index.d.cts +105 -3
- package/dist/server/index.d.ts +21 -4
- package/dist/server/index.js +40 -3
- package/package.json +4 -1
- package/src/commands.ts +2 -0
- package/src/index.ts +8 -3
- package/src/order-filters.ts +14 -6
- package/src/server/batch-outcome.ts +7 -0
- package/src/server/batch.ts +6 -1
- package/src/server/command-result.ts +3 -1
- package/src/server/fiscal-figures.ts +13 -0
- package/src/server/index.ts +4 -2
- package/src/server/order-payload-shape.ts +12 -0
- package/src/server/refund-share.ts +92 -0
- package/src/server/round-ratio.ts +10 -0
- package/src/server/versions.ts +6 -2
- package/src/types/commands.ts +4 -1
- package/src/types/connector.ts +10 -1
- package/src/types/orders.ts +69 -2
package/src/order-filters.ts
CHANGED
|
@@ -2,7 +2,7 @@ import type { ListOrdersQuery, OrderFilterField } from './types/orders';
|
|
|
2
2
|
|
|
3
3
|
/** Every ListOrdersQuery filter field, in the order refusals name them. */
|
|
4
4
|
export const ORDER_FILTER_FIELDS: readonly OrderFilterField[] = [
|
|
5
|
-
'status', 'customerId', 'cashierId', 'registerId', 'paymentMethod', 'storeId', 'createdVia', 'dateRange',
|
|
5
|
+
'status', 'customerId', 'cashierId', 'registerId', 'paymentMethod', 'storeId', 'createdVia', 'dateRange', 'modifiedAfter',
|
|
6
6
|
];
|
|
7
7
|
|
|
8
8
|
/** listOrders was asked to filter by fields the connector does not support (`TallyConnector.orderFilters`). */
|
|
@@ -16,6 +16,12 @@ export class UnsupportedOrderFilterError extends Error {
|
|
|
16
16
|
}
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
+
/** listRefunds cannot read this store's refunds (for example, a plugin too old to serve them). The app treats it as an absent listRefunds. */
|
|
20
|
+
export class StoreRefundsUnsupportedError extends Error {
|
|
21
|
+
readonly code = 'store_refunds_unsupported';
|
|
22
|
+
constructor(message: string) { super(message); this.name = 'StoreRefundsUnsupportedError'; }
|
|
23
|
+
}
|
|
24
|
+
|
|
19
25
|
/** The filter fields a query sets (a field counts when its value is not undefined; dateRange counts when after or before is set). */
|
|
20
26
|
export function orderFilterFields(query: ListOrdersQuery | undefined): OrderFilterField[] {
|
|
21
27
|
if (!query) return [];
|
|
@@ -28,20 +34,22 @@ export function orderFilterFields(query: ListOrdersQuery | undefined): OrderFilt
|
|
|
28
34
|
/**
|
|
29
35
|
* Throws UnsupportedOrderFilterError naming every set field not in `supported`, in OrderFilterField order. A connector
|
|
30
36
|
* calls this first in listOrders. An empty string is a set value, so it is refused too. When `dateRange` is set and
|
|
31
|
-
* supported, it is checked with `assertOrderDateRange
|
|
37
|
+
* supported, it is checked with `assertOrderDateRange`; a set and supported `modifiedAfter` must be a UTC instant
|
|
38
|
+
* ending in Z, as a `dateRange` end must.
|
|
32
39
|
*/
|
|
33
40
|
export function assertOrderFiltersSupported(query: ListOrdersQuery | undefined, supported: readonly OrderFilterField[] | undefined): void {
|
|
34
41
|
const set = orderFilterFields(query);
|
|
35
42
|
const missing = set.filter((field) => !supported?.includes(field));
|
|
36
43
|
if (missing.length > 0) throw new UnsupportedOrderFilterError(missing);
|
|
37
44
|
if (set.includes('dateRange')) assertOrderDateRange(query?.dateRange);
|
|
45
|
+
if (set.includes('modifiedAfter')) instantMs('modifiedAfter', query?.modifiedAfter);
|
|
38
46
|
}
|
|
39
47
|
|
|
40
48
|
const UTC_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?Z$/;
|
|
41
49
|
|
|
42
|
-
function instantMs(
|
|
50
|
+
function instantMs(label: 'dateRange.after' | 'dateRange.before' | 'modifiedAfter', value: unknown): number {
|
|
43
51
|
const ms = typeof value === 'string' && UTC_INSTANT.test(value) ? Date.parse(value) : Number.NaN;
|
|
44
|
-
if (Number.isNaN(ms)) throw new TypeError(
|
|
52
|
+
if (Number.isNaN(ms)) throw new TypeError(`${label} must be an ISO 8601 UTC instant ending in Z: ${String(value)}`);
|
|
45
53
|
return ms;
|
|
46
54
|
}
|
|
47
55
|
|
|
@@ -50,8 +58,8 @@ function instantMs(end: 'after' | 'before', value: unknown): number {
|
|
|
50
58
|
* to `before` passes: an empty range is the caller's business.
|
|
51
59
|
*/
|
|
52
60
|
export function assertOrderDateRange(range: ListOrdersQuery['dateRange']): void {
|
|
53
|
-
const after = range?.after === undefined ? undefined : instantMs('after', range.after);
|
|
54
|
-
const before = range?.before === undefined ? undefined : instantMs('before', range.before);
|
|
61
|
+
const after = range?.after === undefined ? undefined : instantMs('dateRange.after', range.after);
|
|
62
|
+
const before = range?.before === undefined ? undefined : instantMs('dateRange.before', range.before);
|
|
55
63
|
if (after !== undefined && before !== undefined && after > before) {
|
|
56
64
|
throw new TypeError(`dateRange.after (${range?.after}) is later than dateRange.before (${range?.before})`);
|
|
57
65
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { CommandBatchResponse } from '../types'
|
|
2
|
+
import { NEEDS_ADMIN_MESSAGE_MAX } from '../commands'
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* A plugin's batch handler stops at the first in-progress or transient command and returns that
|
|
@@ -7,12 +8,18 @@ import type { CommandBatchResponse } from '../types'
|
|
|
7
8
|
export type BatchOutcome =
|
|
8
9
|
| { status: 200; body: CommandBatchResponse }
|
|
9
10
|
| { status: 409; body: { code: 'in_progress'; id: string } }
|
|
11
|
+
| { status: 409; body: { code: 'needs_admin'; id: string; reason: string; message: string } }
|
|
10
12
|
| { status: 503; body: { code: 'transient'; id: string; message: 'Temporary failure, retry later.' } }
|
|
11
13
|
|
|
12
14
|
export function inProgressOutcome(id: string): BatchOutcome {
|
|
13
15
|
return { status: 409, body: { code: 'in_progress', id } }
|
|
14
16
|
}
|
|
15
17
|
|
|
18
|
+
/** A command an admin must finish (TallyUI #1280). `reason` is snake_case; `message` is cut to NEEDS_ADMIN_MESSAGE_MAX. */
|
|
19
|
+
export function needsAdminOutcome(id: string, reason: string, message: string): BatchOutcome {
|
|
20
|
+
return { status: 409, body: { code: 'needs_admin', id, reason, message: message.slice(0, NEEDS_ADMIN_MESSAGE_MAX) } }
|
|
21
|
+
}
|
|
22
|
+
|
|
16
23
|
/** The message is fixed so a server never leaks its internal error (log that separately). */
|
|
17
24
|
export function transientOutcome(id: string): BatchOutcome {
|
|
18
25
|
return { status: 503, body: { code: 'transient', id, message: 'Temporary failure, retry later.' } }
|
package/src/server/batch.ts
CHANGED
|
@@ -80,9 +80,11 @@ function unsupportedOptional(envelope: { id: string; type: string; version: numb
|
|
|
80
80
|
* `supported` is the SERVER's own list (what its /info advertises), never core's constants, which are the
|
|
81
81
|
* till's capability (#297). The version check, the `unsupported_version` message and its `data` all use it:
|
|
82
82
|
* `precheckCommand(envelope, { orderCreate: [1, 2, 3], register: [1], orderRefund: [1], orderReopen: [1], orderUpdate: [1] })` (`orderRefund`, `orderReopen` and `orderUpdate` are optional).
|
|
83
|
+
* `cashRounding` is the server's own word too (ADR-094): without `true`, an order.create (or an order.update's create part)
|
|
84
|
+
* carrying `cashRoundings` is refused as `invalid_payload`, never sent on with the field dropped, which would be a wrong total.
|
|
83
85
|
*/
|
|
84
86
|
export function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCommandEnvelope, 'id' | 'type' | 'version' | 'payload'>,
|
|
85
|
-
supported: { orderCreate: readonly number[]; register: readonly number[]; orderRefund?: readonly number[]; orderReopen?: readonly number[]; orderUpdate?: readonly number[] }): CommandResult | undefined {
|
|
87
|
+
supported: { orderCreate: readonly number[]; register: readonly number[]; orderRefund?: readonly number[]; orderReopen?: readonly number[]; orderUpdate?: readonly number[]; cashRounding?: boolean }): CommandResult | undefined {
|
|
86
88
|
// An empty list would send Math.max() of nothing (-Infinity, null in JSON) as the server's version.
|
|
87
89
|
for (const key of ['orderCreate', 'register'] as const) {
|
|
88
90
|
if (!supported[key]?.length) throw new TypeError(`precheckCommand: supported.${key} must list at least one version`)
|
|
@@ -113,6 +115,9 @@ export function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCom
|
|
|
113
115
|
`order.create version ${command.version} is not supported; this server supports ${supported.orderCreate.join(', ')}`,
|
|
114
116
|
{ orderCreate: Math.max(...supported.orderCreate) })
|
|
115
117
|
}
|
|
118
|
+
if ((command.payload as { cashRoundings?: unknown }).cashRoundings !== undefined && supported.cashRounding !== true) {
|
|
119
|
+
return rejected(command.id, 'invalid_payload', 'cashRoundings requires the cashRounding capability, which this server does not declare')
|
|
120
|
+
}
|
|
116
121
|
// ADR-062 sends version 2 exactly when there is a discount, so version 1 can never create adjustments.
|
|
117
122
|
const { lines, discountMinor } = command.payload as { lines?: unknown; discountMinor?: unknown }
|
|
118
123
|
const discounted = discountMinor !== undefined
|
|
@@ -54,7 +54,9 @@ export function parseCommandResult(value: unknown): CommandResult {
|
|
|
54
54
|
return [key, amount as number]
|
|
55
55
|
}))
|
|
56
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)
|
|
57
|
+
if (!Array.isArray(refund.refunds)) throw new CommandResultError('Invalid refund.refunds')
|
|
58
|
+
// ADR-080, #1330: a stock-only return moves no money and creates no platform refund, so refunds is empty exactly then.
|
|
59
|
+
if (refund.refunds.length === 0 && (refund.totalMinor !== 0 || Object.keys(byMethod).length > 0)) throw new CommandResultError('Invalid refund.refunds')
|
|
58
60
|
const refunds = refund.refunds.map((value: unknown, index) => {
|
|
59
61
|
const field = `refund.refunds[${index}]`
|
|
60
62
|
if (!object(value)) throw new CommandResultError(`Invalid ${field}`)
|
|
@@ -94,6 +94,19 @@ export function fiscalFiguresErrors(payload: OrderCreatePayload): string[] {
|
|
|
94
94
|
check(!seen.has(line.clientLineId), `display.lines[${index}].clientLineId`, 'no duplicate clientLineId')
|
|
95
95
|
seen.add(line.clientLineId)
|
|
96
96
|
})
|
|
97
|
+
if (!errors.length) {
|
|
98
|
+
// ADR-063 I1–I3 (#1256): display's own figures add up. taxByRate gross is not tied to totalMinor (zero-rated lines and
|
|
99
|
+
// tax-none charges may be absent from it, and cash roundings are tax-none); display.subtotalMinor is not tied to
|
|
100
|
+
// payload.subtotalMinor (display is in the display tax mode, and in store mode the payload subtotal is net of coupons).
|
|
101
|
+
const sum = (rows: ReadonlyArray<{ amountMinor: number }> | undefined) => (rows ?? []).reduce((total, row) => total + BigInt(row.amountMinor), 0n)
|
|
102
|
+
const roundings = (payload.cashRoundings ?? []).reduce((total, entry) => total + BigInt(entry.minor), 0n)
|
|
103
|
+
check(BigInt(display.subtotalMinor) - BigInt(display.discountMinor) + sum(display.fees) + sum(display.shipping)
|
|
104
|
+
+ (display.taxInclusive ? 0n : BigInt(display.taxMinor)) + roundings === BigInt(display.totalMinor),
|
|
105
|
+
'display.totalMinor', 'subtotalMinor − discountMinor + fees + shipping (+ taxMinor when exclusive) + cashRoundings')
|
|
106
|
+
check(sum(display.lines) === BigInt(display.subtotalMinor), 'display.subtotalMinor', 'the sum of display.lines[].amountMinor')
|
|
107
|
+
check(BigInt(display.discountMinor) === BigInt(display.orderDiscountMinor) + display.lines.reduce((total, line) => total + sum(line.discounts), 0n)
|
|
108
|
+
+ sum(display.coupons), 'display.discountMinor', 'orderDiscountMinor + the line discount rows + the coupon rows')
|
|
109
|
+
}
|
|
97
110
|
try {
|
|
98
111
|
check(display.exponent === currencyDecimals(payload.currency), 'display.exponent', 'the currency decimals')
|
|
99
112
|
} catch {
|
package/src/server/index.ts
CHANGED
|
@@ -6,11 +6,11 @@ export { payloadBoundErrors, payloadShapeErrors } from './order-payload-shape'
|
|
|
6
6
|
export { fiscalFiguresErrors } from './fiscal-figures'
|
|
7
7
|
export type { CommandErrorWithData, OrderCreateDisplay, OrderCreateTaxRate, OrderCreatePayloadV3 } from './fiscal-figures'
|
|
8
8
|
export { SUPPORTED_ORDER_CREATE_VERSIONS, SUPPORTED_REGISTER_VERSIONS, SUPPORTED_ORDER_REFUND_VERSIONS, SUPPORTED_ORDER_REOPEN_VERSIONS, SUPPORTED_ORDER_UPDATE_VERSIONS } from './versions'
|
|
9
|
-
export { MAX_COMMANDS_PER_BATCH, ORDER_NOTE_MAX } from '../commands'
|
|
9
|
+
export { MAX_COMMANDS_PER_BATCH, ORDER_NOTE_MAX, NEEDS_ADMIN_MESSAGE_MAX } from '../commands'
|
|
10
10
|
export { validateBatch, precheckCommand } from './batch'
|
|
11
11
|
export type { ValidatedCommandEnvelope } from './batch'
|
|
12
12
|
export type { BatchTooLargeBody } from '../types'
|
|
13
|
-
export { inProgressOutcome, transientOutcome } from './batch-outcome'
|
|
13
|
+
export { inProgressOutcome, needsAdminOutcome, transientOutcome } from './batch-outcome'
|
|
14
14
|
export type { BatchOutcome } from './batch-outcome'
|
|
15
15
|
export { totalWarnings } from './total-warnings'
|
|
16
16
|
export type { OrderRejectionCode, Rejection } from './total-warnings'
|
|
@@ -25,3 +25,5 @@ export { platformErrorResult, internalErrorResult } from './rejection-codes'
|
|
|
25
25
|
export type { CommandRejectionCode } from './rejection-codes'
|
|
26
26
|
export { createMemoryDisplaySignalling, displaySignallingContract } from './display-signalling'
|
|
27
27
|
export type { DisplaySignallingHarness } from './display-signalling'
|
|
28
|
+
export { roundRatio, type RoundingMode } from './round-ratio'
|
|
29
|
+
export { refundableLines, priceRefund, type RefundableOrderLine, type EarlierRefund, type RefundableLine, type PricedRefundLine, type PricedRefund } from './refund-share'
|
|
@@ -62,6 +62,18 @@ export function payloadShapeErrors(payload: unknown): string[] {
|
|
|
62
62
|
.reduce((sum: bigint, line, index) => sum + (object(line) ? discount(line.discountMinor, `lines[${index}].discountMinor`) : 0n), 0n)
|
|
63
63
|
const orderDiscount = discount(payload.discountMinor, 'discountMinor')
|
|
64
64
|
if (errors.length === 0) check(orderDiscount === lineDiscounts, 'discountMinor', 'the sum of lines[].discountMinor')
|
|
65
|
+
// ADR-094: signed cash roundings, at any version, at most 16 entries.
|
|
66
|
+
if (payload.cashRoundings !== undefined) {
|
|
67
|
+
const entries = payload.cashRoundings
|
|
68
|
+
check(Array.isArray(entries) && entries.length <= 16, 'cashRoundings', 'an array of at most 16 entries')
|
|
69
|
+
if (Array.isArray(entries) && entries.length <= 16) for (const [index, entry] of entries.entries()) {
|
|
70
|
+
const path = `cashRoundings[${index}]`
|
|
71
|
+
check(object(entry), path, 'an object')
|
|
72
|
+
if (!object(entry)) continue
|
|
73
|
+
check(typeof entry.paymentId === 'string' && entry.paymentId.length > 0, `${path}.paymentId`, 'a non-empty string')
|
|
74
|
+
check(Number.isSafeInteger(entry.minor), `${path}.minor`, 'a safe integer')
|
|
75
|
+
}
|
|
76
|
+
}
|
|
65
77
|
if (payload.customer !== undefined && payload.customer !== null) {
|
|
66
78
|
check(object(payload.customer), 'customer', 'an object')
|
|
67
79
|
if (object(payload.customer) && payload.customer.email !== undefined) {
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ports v2 calculate-refund.ts (calculateLineItemRefund, computeRemainingRefundQuantity).
|
|
3
|
+
* Amounts follow ADR-080 amendment 2's cumulative-share rule.
|
|
4
|
+
*/
|
|
5
|
+
import type { OrderRefundLine } from '../types'
|
|
6
|
+
import type { StoreOrderLine } from '../types/orders'
|
|
7
|
+
import { roundRatio } from './round-ratio'
|
|
8
|
+
|
|
9
|
+
/** The fields of an order line this needs; a StoreOrderLine fits. */
|
|
10
|
+
export type RefundableOrderLine = Pick<StoreOrderLine, 'id' | 'quantity' | 'totalMinor' | 'taxMinor'>;
|
|
11
|
+
/** Earlier refund lines; negative quantities count by magnitude. */
|
|
12
|
+
export interface EarlierRefund { lines: ReadonlyArray<Pick<OrderRefundLine, 'orderLineId' | 'quantity'>> }
|
|
13
|
+
|
|
14
|
+
/** Remaining quantities and amounts, with earlier refund magnitudes capped at the line quantity. */
|
|
15
|
+
export interface RefundableLine {
|
|
16
|
+
orderLineId: string;
|
|
17
|
+
refundedQuantity: number;
|
|
18
|
+
refundableQuantity: number;
|
|
19
|
+
netMinor: number;
|
|
20
|
+
taxMinor: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A selected quantity's cumulative shares of net and tax, and their sum. */
|
|
24
|
+
export interface PricedRefundLine {
|
|
25
|
+
orderLineId: string; quantity: number; netMinor: number; taxMinor: number;
|
|
26
|
+
totalMinor: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Payload-ready lines and their amounts; the caller adds shipping and adjustment to totalMinor. */
|
|
30
|
+
export interface PricedRefund {
|
|
31
|
+
/** Exactly orderLineId, quantity (>= 1), and restock. */
|
|
32
|
+
lines: OrderRefundLine[];
|
|
33
|
+
/** Amounts in the same order as lines. */
|
|
34
|
+
priced: PricedRefundLine[];
|
|
35
|
+
/** Requests cut to availability, including unknown lines cut to zero. */
|
|
36
|
+
clamped: Array<{ orderLineId: string; requestedQuantity: number; quantity: number }>;
|
|
37
|
+
netMinor: number; taxMinor: number; totalMinor: number;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Returns the quantities and amounts still refundable, in order-line order. */
|
|
41
|
+
export function refundableLines(
|
|
42
|
+
lines: readonly RefundableOrderLine[], refunds: readonly EarlierRefund[],
|
|
43
|
+
): RefundableLine[] {
|
|
44
|
+
const earlier = refunds.flatMap((refund) => refund.lines);
|
|
45
|
+
for (const refund of earlier) {
|
|
46
|
+
if (!Number.isSafeInteger(refund.quantity)) throw new RangeError('Earlier refund quantity must be a safe integer');
|
|
47
|
+
}
|
|
48
|
+
return lines.map((line) => {
|
|
49
|
+
if (!Number.isSafeInteger(line.quantity) || line.quantity < 0
|
|
50
|
+
|| !Number.isSafeInteger(line.totalMinor) || !Number.isSafeInteger(line.taxMinor)) {
|
|
51
|
+
throw new RangeError('Order line values must be safe integers and quantity non-negative');
|
|
52
|
+
}
|
|
53
|
+
const refundedQuantity = earlier.reduce((sum, refund) => refund.orderLineId === line.id
|
|
54
|
+
? Math.min(line.quantity, sum + Math.abs(refund.quantity)) : sum, 0);
|
|
55
|
+
const [netMinor, taxMinor] = [line.totalMinor, line.taxMinor].map((total) => line.quantity === 0 ? 0
|
|
56
|
+
: total - Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), 'half_up')));
|
|
57
|
+
return {
|
|
58
|
+
orderLineId: line.id, refundedQuantity, refundableQuantity: line.quantity - refundedQuantity, netMinor, taxMinor,
|
|
59
|
+
};
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Prices requested quantities with cumulative shares, clamping them to what remains refundable. */
|
|
64
|
+
export function priceRefund(
|
|
65
|
+
lines: readonly RefundableOrderLine[], refunds: readonly EarlierRefund[], request: readonly OrderRefundLine[],
|
|
66
|
+
): PricedRefund {
|
|
67
|
+
const available = refundableLines(lines, refunds);
|
|
68
|
+
const seen = new Set<string>();
|
|
69
|
+
const result: PricedRefund = { lines: [], priced: [], clamped: [], netMinor: 0, taxMinor: 0, totalMinor: 0 };
|
|
70
|
+
for (const { orderLineId, quantity: requestedQuantity, restock } of request) {
|
|
71
|
+
if (!Number.isSafeInteger(requestedQuantity) || requestedQuantity < 0 || seen.has(orderLineId)) {
|
|
72
|
+
throw new RangeError('Request quantities must be non-negative safe integers and line ids unique');
|
|
73
|
+
}
|
|
74
|
+
seen.add(orderLineId);
|
|
75
|
+
const index = lines.findIndex((line) => line.id === orderLineId);
|
|
76
|
+
const quantity = Math.min(requestedQuantity, available[index]?.refundableQuantity ?? 0);
|
|
77
|
+
if (quantity < requestedQuantity) result.clamped.push({ orderLineId, requestedQuantity, quantity });
|
|
78
|
+
if (quantity < 1) continue;
|
|
79
|
+
const line = lines[index];
|
|
80
|
+
const refundedQuantity = available[index].refundedQuantity;
|
|
81
|
+
const [netMinor, taxMinor] = [line.totalMinor, line.taxMinor].map((total) =>
|
|
82
|
+
Number(roundRatio(BigInt(refundedQuantity + quantity) * BigInt(total), BigInt(line.quantity), 'half_up'))
|
|
83
|
+
- Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), 'half_up')));
|
|
84
|
+
const totalMinor = netMinor + taxMinor;
|
|
85
|
+
result.lines.push({ orderLineId, quantity, restock });
|
|
86
|
+
result.priced.push({ orderLineId, quantity, netMinor, taxMinor, totalMinor });
|
|
87
|
+
result.netMinor += netMinor;
|
|
88
|
+
result.taxMinor += taxMinor;
|
|
89
|
+
result.totalMinor += totalMinor;
|
|
90
|
+
}
|
|
91
|
+
return result;
|
|
92
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Moved from @tallyui/pos tax/exact.ts (arch 1a): the till's and the servers' exact rounding.
|
|
2
|
+
/** #287: `half_up` is Math.round's rule, Vendure's DefaultMoneyStrategy (default-money-strategy.js:19-21). */
|
|
3
|
+
export type RoundingMode = 'half_away_from_zero' | 'half_up';
|
|
4
|
+
|
|
5
|
+
/** `n / d` (d > 0) rounded to an integer in `mode`, exactly; the modes differ only on exact negative halves. */
|
|
6
|
+
export function roundRatio(n: bigint, d: bigint, mode: RoundingMode = 'half_away_from_zero'): bigint {
|
|
7
|
+
if (mode === 'half_away_from_zero' && n < 0n) return -roundRatio(-n, d, mode);
|
|
8
|
+
const a = 2n * n + d, b = 2n * d; // floor(n / d + 1/2)
|
|
9
|
+
return a / b - (a < 0n && a % b !== 0n ? 1n : 0n);
|
|
10
|
+
}
|
package/src/server/versions.ts
CHANGED
|
@@ -11,8 +11,12 @@
|
|
|
11
11
|
* 12 is 11 plus the customer's tax ids, a catalogue line's edited SKU and order meta, as informational fields (ADR-092).
|
|
12
12
|
*/
|
|
13
13
|
export const SUPPORTED_ORDER_CREATE_VERSIONS: readonly number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
|
|
14
|
-
/**
|
|
15
|
-
|
|
14
|
+
/**
|
|
15
|
+
* The till's capability for the contract versions shared by all five register commands; a server passes its own.
|
|
16
|
+
* The till builds 1 (every command), 2 (session.open, contract ≥ 2) and 3 (session.open and closure.submit,
|
|
17
|
+
* contract ≥ 3; ADR-082).
|
|
18
|
+
*/
|
|
19
|
+
export const SUPPORTED_REGISTER_VERSIONS: readonly number[] = [1, 2, 3]
|
|
16
20
|
/** The till's capability for order.refund versions (ADR-080); a server passes its own. */
|
|
17
21
|
export const SUPPORTED_ORDER_REFUND_VERSIONS: readonly number[] = [1]
|
|
18
22
|
/** The till's capability for order.reopen versions (ADR-090); a server passes its own. */
|
package/src/types/commands.ts
CHANGED
|
@@ -46,6 +46,7 @@ export type OrderRefundEnvelope<P = OrderRefundPayload> =
|
|
|
46
46
|
export interface OrderRefundResult {
|
|
47
47
|
totalMinor: number;
|
|
48
48
|
byMethod: Record<string, number>;
|
|
49
|
+
/** The platform refunds created, summing to totalMinor. Empty only for a stock-only return: totalMinor 0 and byMethod {} (ADR-080, #1330). */
|
|
49
50
|
refunds: Array<{ id: string; paymentId: string; totalMinor: number; state: string }>;
|
|
50
51
|
}
|
|
51
52
|
/** Per-command refund refusals (ADR-080 decision 5). */
|
|
@@ -229,7 +230,7 @@ export interface RegisterCommandResult {
|
|
|
229
230
|
resumed?: { fromSessionId: string };
|
|
230
231
|
/** The session this open took over (register v2). */
|
|
231
232
|
superseded?: { sessionId: string; openedAt?: string; deviceId?: string; deviceName?: string };
|
|
232
|
-
/** The register's counters: a floor for the till's own, never lowered. */
|
|
233
|
+
/** The register's counters: a floor for the till's own, never lowered, with two exceptions for perpetual refunds. The till raises refunds only from answers at the highest closure number among the store's answers, and sets them to the largest store figure at its newest applied closure once nothing of its own is unsent (@tallyui/pos settleStoreRefunds). A closure refused for its number resets the counters outright (@tallyui/pos renumberClosures). */
|
|
233
234
|
counters?: { lastClosureNumber: number; perpetualSalesTotalMinor: number; perpetualRefundsTotalMinor: number };
|
|
234
235
|
/** `register.closure.submit` only. */
|
|
235
236
|
closure?: { serverClosureId: string; number: number; expected?: Record<string, number>; variance?: Record<string, number> };
|
|
@@ -455,6 +456,8 @@ export interface OrderCreatePayload {
|
|
|
455
456
|
taxMinor: number;
|
|
456
457
|
totalMinor: number;
|
|
457
458
|
payments: OrderCreatePayment[];
|
|
459
|
+
/** ADR-094: each cash leg's signed rounding, in minor units, already summed into `totalMinor`; sent at the order's content version, only for an order that has one, and only to a store whose connector declares `cashRounding` (a server without it refuses the field). */
|
|
460
|
+
cashRoundings?: Array<{ paymentId: string; minor: number }>;
|
|
458
461
|
/** Version 3+; both or neither. */
|
|
459
462
|
display?: OrderCreateDisplay;
|
|
460
463
|
/** Version 3+; both or neither. */
|
package/src/types/connector.ts
CHANGED
|
@@ -6,7 +6,7 @@ import type { ReplicationAdapter } from './replication';
|
|
|
6
6
|
import type { CatalogueReconcileAdapter, FingerprintReconcileAdapter, IdReconcileAdapter, StockReconcileAdapter } from './reconcile';
|
|
7
7
|
import type { StoreSettings, StoreSettingsChoice } from './store-settings';
|
|
8
8
|
import type { Customer, CustomerInput, CustomerPage, CustomerPatch } from './customers';
|
|
9
|
-
import type { ListOrdersQuery, OrderFilterField, StoreOrder, StoreOrderPage } from './orders';
|
|
9
|
+
import type { ListOrdersQuery, ListRefundsQuery, OrderFilterField, StoreOrder, StoreOrderPage, StoreRefundPage } from './orders';
|
|
10
10
|
import type { PaymentMethodDescriptor } from './payment-methods';
|
|
11
11
|
import type { ReceiptTemplate, ReceiptTemplateKind } from './receipt-templates';
|
|
12
12
|
import type { RegisterInfo } from './registers';
|
|
@@ -89,6 +89,8 @@ export interface ServerCapabilities {
|
|
|
89
89
|
receiptEmail?: number;
|
|
90
90
|
/** The platform plugin's own contract version, from `/tally/v1/info`'s top-level `pluginContract` (#1114). Absent when not sent or malformed; each connector says what a version adds. */
|
|
91
91
|
pluginContract?: number;
|
|
92
|
+
/** True only when the store's connector carries order.create's `cashRoundings` (ADR-094). Absent: the till never rounds a cash leg, and finalize refuses an order with entries. */
|
|
93
|
+
cashRounding?: boolean;
|
|
92
94
|
}
|
|
93
95
|
|
|
94
96
|
/** #287, ADR-071. `custom`: the till computes as when absent; that server never emits `figures_mismatch` for subtotal or tax. */
|
|
@@ -422,6 +424,13 @@ export interface TallyConnector {
|
|
|
422
424
|
* read-only; rejects as `listOrders`. `undefined` when the connector has no order history.
|
|
423
425
|
*/
|
|
424
426
|
getOrders?: (context: SyncContext, ids: readonly string[]) => Promise<StoreOrder[]>;
|
|
427
|
+
/**
|
|
428
|
+
* The store's refunds, newest first, one page per call, dated by when each was made (ADR-081 decision 7): online only,
|
|
429
|
+
* read-only. Rejects as `listOrders` does; a `dateRange` end that is not a UTC instant ending in Z is a TypeError
|
|
430
|
+
* (`assertOrderDateRange`); a store that cannot serve dated refunds rejects with `StoreRefundsUnsupportedError`.
|
|
431
|
+
* `undefined` when the connector has no dated refunds: the app keeps counting refunds on their order's day.
|
|
432
|
+
*/
|
|
433
|
+
listRefunds?: (context: SyncContext, query?: ListRefundsQuery) => Promise<StoreRefundPage>;
|
|
425
434
|
/**
|
|
426
435
|
* The store's register directory (v2 parity A4): online only, read-only. Rejects with `ConnectorUnauthorizedError`
|
|
427
436
|
* for credentials; a connector's own errors otherwise. `undefined` when the connector has no register directory.
|
package/src/types/orders.ts
CHANGED
|
@@ -50,8 +50,15 @@ export interface StoreOrderPayment {
|
|
|
50
50
|
amountMinor: number;
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
+
/** One order line a store refund paid back (#1324). Integers; `netMinor + taxMinor` is the line's gross refund. Shipping and adjustments are never lines. */
|
|
54
|
+
export interface StoreOrderRefundLine { /** A `StoreOrderLine.id` of the same order. */ orderLineId: string; /** > 0. */ quantity: number; netMinor: number; taxMinor: number }
|
|
55
|
+
|
|
53
56
|
/** A refund the store already recorded against the order. */
|
|
54
|
-
export interface StoreOrderRefund {
|
|
57
|
+
export interface StoreOrderRefund {
|
|
58
|
+
id: string; /** Positive. */ amountMinor: number; reason?: string;
|
|
59
|
+
/** The lines this refund paid back, when the store records them; absent when it cannot say (#1324). A line is on the store refund that paid it back and never repeated on another: a till refund split over tenders is one store refund. When an order's refunds together name more of a line than was ordered, none of them carry lines. */
|
|
60
|
+
lines?: StoreOrderRefundLine[];
|
|
61
|
+
}
|
|
55
62
|
|
|
56
63
|
/** An order as the store holds it, read online (ADR-081); never stored by the till. */
|
|
57
64
|
export interface StoreOrder {
|
|
@@ -61,12 +68,23 @@ export interface StoreOrder {
|
|
|
61
68
|
reference: string;
|
|
62
69
|
/** The till's `PosOrder.id` when a till created the order; absent otherwise. It is also what an `order.reopen` sends as `clientOrderId`. */
|
|
63
70
|
clientOrderId?: string;
|
|
71
|
+
/** The cashier the store records for the order, as `ListOrdersQuery.cashierId` filters it (WooCommerce: the WordPress user id in `_pos_user`); absent when the store records none. */
|
|
72
|
+
cashierId?: string;
|
|
73
|
+
/** The store (outlet) the order was rung at, as `ListOrdersQuery.storeId` filters it (WooCommerce: `_pos_store`); absent when the store records none, as a single-store install does. */
|
|
74
|
+
storeId?: string;
|
|
75
|
+
/**
|
|
76
|
+
* The register the store itself records for the order, as `ListOrdersQuery.registerId` filters it (WooCommerce: `_wcpos_register`,
|
|
77
|
+
* which only WCPOS writes). It is neither the till's drawer nor its device id, and it is absent on every order TallyUI rings (ADR-090 decision 6).
|
|
78
|
+
*/
|
|
79
|
+
registerId?: string;
|
|
64
80
|
/** The store's current revision of the order, which `OrderReopenPayload.baseRevision` and `OrderUpdatePayload.baseRevision` carry; absent when the store has none. */
|
|
65
81
|
revision?: string;
|
|
66
82
|
/** The platform's own status word (WooCommerce: `completed`, `refunded`, …); the app labels it. */
|
|
67
83
|
status: string;
|
|
68
84
|
/** ISO 8601, UTC. */
|
|
69
85
|
placedAt: string;
|
|
86
|
+
/** When the store recorded the order as paid (WooCommerce: `date_paid_gmt`); absent while unpaid, or when the store records none. ISO 8601, UTC. */
|
|
87
|
+
paidAt?: string;
|
|
70
88
|
currency: string;
|
|
71
89
|
pricesIncludeTax: boolean;
|
|
72
90
|
customer: { id?: string; name?: string; email?: string } | null;
|
|
@@ -86,12 +104,16 @@ export interface StoreOrder {
|
|
|
86
104
|
* (WooCommerce: a WCPOS payment ledger of another schema); `payments` is then the order's paid-state
|
|
87
105
|
* fallback, and a reopen must refuse the order. Absent otherwise. */
|
|
88
106
|
paymentRecordUnreadable?: true;
|
|
107
|
+
/** The store says the order still owes money (WooCommerce: `needs_payment`); absent when the store does not say. */
|
|
108
|
+
needsPayment?: boolean;
|
|
109
|
+
/** Where the order was created, in the platform's own words, as `ListOrdersQuery.createdVia` filters it (WooCommerce: `woocommerce-pos`, `checkout`, `admin`); absent when the store records none. */
|
|
110
|
+
createdVia?: string;
|
|
89
111
|
refunds: StoreOrderRefund[];
|
|
90
112
|
}
|
|
91
113
|
|
|
92
114
|
/** The filter fields a connector may support on listOrders. */
|
|
93
115
|
export type OrderFilterField =
|
|
94
|
-
| 'status' | 'customerId' | 'cashierId' | 'registerId' | 'paymentMethod' | 'storeId' | 'createdVia' | 'dateRange';
|
|
116
|
+
| 'status' | 'customerId' | 'cashierId' | 'registerId' | 'paymentMethod' | 'storeId' | 'createdVia' | 'dateRange' | 'modifiedAfter';
|
|
95
117
|
|
|
96
118
|
/**
|
|
97
119
|
* One page of order history, filtered on the server (#721). A connector maps each filter field its own way; a field the
|
|
@@ -119,6 +141,11 @@ export interface ListOrdersQuery {
|
|
|
119
141
|
createdVia?: string;
|
|
120
142
|
/** Created at or after `after` and before `before`: ISO 8601 instants in UTC with a `Z` (`2026-11-11T00:00:00.000Z`). Either end may be absent. */
|
|
121
143
|
dateRange?: { after?: string; before?: string };
|
|
144
|
+
/**
|
|
145
|
+
* Changed at or after this instant: ISO 8601 UTC with a `Z`, as `dateRange` takes. It widens a read to orders created
|
|
146
|
+
* earlier and changed since, such as one paid in a report's range (WooCommerce: `modified_after`).
|
|
147
|
+
*/
|
|
148
|
+
modifiedAfter?: string;
|
|
122
149
|
}
|
|
123
150
|
|
|
124
151
|
/** One page of an order list: its orders, whether more follow, and how many the whole query matches when the store says. */
|
|
@@ -130,3 +157,43 @@ export interface StoreOrderPage {
|
|
|
130
157
|
/** Every order the query matches across all pages; undefined when the store gives no count. It still counts orders left out as `unreadable`. */
|
|
131
158
|
total?: number;
|
|
132
159
|
}
|
|
160
|
+
|
|
161
|
+
/** A refund the store recorded, dated by when it was made (ADR-081 decision 7). */
|
|
162
|
+
export interface StoreRefund {
|
|
163
|
+
id: string;
|
|
164
|
+
/** The refunded order's `StoreOrder.id`. */
|
|
165
|
+
orderId: string;
|
|
166
|
+
/** When the refund was made: ISO 8601, UTC, with a `Z`. */
|
|
167
|
+
refundedAt: string;
|
|
168
|
+
/** The refunded order's currency. A store's refund row carries none, so the connector reads it from the order. */
|
|
169
|
+
currency: string;
|
|
170
|
+
/** Zero or more. Gross: the refunded total, tax included (WooCommerce: the refund's `amount`). It comes off a tax-inclusive sales figure only, never a net-of-tax one. */
|
|
171
|
+
amountMinor: number;
|
|
172
|
+
reason?: string;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** A refund whose order the store did not return: no currency, so no amount. Never counted, never dropped. */
|
|
176
|
+
export interface StoreRefundOrphan { id: string; orderId: string; refundedAt: string }
|
|
177
|
+
|
|
178
|
+
export interface ListRefundsQuery {
|
|
179
|
+
/** 1-based; default 1. */
|
|
180
|
+
page?: number;
|
|
181
|
+
/** 1..100; default 25. */
|
|
182
|
+
perPage?: number;
|
|
183
|
+
/** Made at or after `after` and before `before`: ISO 8601 instants in UTC with a `Z`. Selects by when the refund was made, not when its order was placed. Either end may be absent. */
|
|
184
|
+
dateRange?: { after?: string; before?: string };
|
|
185
|
+
/** Only the refunds of this order (`StoreOrder.id`). */
|
|
186
|
+
orderId?: string;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** One page of refunds, newest first. */
|
|
190
|
+
export interface StoreRefundPage {
|
|
191
|
+
refunds: StoreRefund[];
|
|
192
|
+
/** Refunds on this page whose order the store did not return. */
|
|
193
|
+
orphans: StoreRefundOrphan[];
|
|
194
|
+
hasMore: boolean;
|
|
195
|
+
/** Rows on this page the connector could not read and left out; absent when every row read. */
|
|
196
|
+
unreadable?: number;
|
|
197
|
+
/** Every refund the query matches across all pages, orphans and unreadable rows included; undefined when the store gives no count. */
|
|
198
|
+
total?: number;
|
|
199
|
+
}
|