mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 07:30:04 +00:00
refactor(budget): money arithmetic lives in shared and the settlement uses it
toMinor, sumMinor, splitEqualShares and currencyDecimals move to shared/src/money. The budget service and its MCP tools call them instead of private copies, and the share table both sides were pinned to becomes the spec of the shared function. Stored values and every computed figure stay the same.
This commit is contained in:
@@ -108,3 +108,6 @@ export * from './roadtrip/google-import.schema';
|
||||
export * from './roadtrip/charging.schema';
|
||||
|
||||
export * from './vacay/school-holiday-catalog.schema';
|
||||
|
||||
// Money arithmetic in whole hundredths (sums, equal splits, currency precision).
|
||||
export * from './money/money';
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { currencyDecimals, splitEqualShares, sumMinor, toMinor } from './money';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
describe('currencyDecimals', () => {
|
||||
it.each([
|
||||
['EUR', 2],
|
||||
['usd', 2],
|
||||
['JPY', 0],
|
||||
['huf', 0],
|
||||
['XPF', 0],
|
||||
['KWD', 3],
|
||||
['tnd', 3],
|
||||
['ZZZ', 2],
|
||||
])('%s has %i decimals', (code, decimals) => {
|
||||
expect(currencyDecimals(code)).toBe(decimals);
|
||||
});
|
||||
});
|
||||
|
||||
describe('toMinor / sumMinor', () => {
|
||||
it('rounds a float amount to whole hundredths', () => {
|
||||
expect(toMinor(81.61)).toBe(8161);
|
||||
expect(toMinor(0.1 + 0.2)).toBe(30);
|
||||
expect(toMinor(-30)).toBe(-3000);
|
||||
});
|
||||
|
||||
it('sums each amount rounded, so the two halves of 163.21 add back exactly (#1964)', () => {
|
||||
expect(81.61 + 81.6).not.toBe(163.21);
|
||||
expect(sumMinor([81.61, 81.6])).toBe(16321);
|
||||
expect(sumMinor([])).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
// The share table the server's settlement and the client's preview were both
|
||||
// pinned to (#2176). It is the contract of the shared function now.
|
||||
const SHARE_PARITY_FIXTURE: {
|
||||
totalCents: number;
|
||||
users: number[];
|
||||
itemId: number;
|
||||
expected: Record<number, number>;
|
||||
}[] = [
|
||||
{ totalCents: 10000, users: [1, 2, 3], itemId: 0, expected: { 1: 3334, 2: 3333, 3: 3333 } },
|
||||
{ totalCents: 10000, users: [1, 2, 3], itemId: 1, expected: { 1: 3333, 2: 3334, 3: 3333 } },
|
||||
{ totalCents: -10000, users: [1, 2, 3], itemId: 0, expected: { 1: -3333, 2: -3333, 3: -3334 } },
|
||||
{ totalCents: -10000, users: [1, 2, 3], itemId: 1, expected: { 1: -3334, 2: -3333, 3: -3333 } },
|
||||
{ totalCents: -101, users: [1, 2], itemId: 0, expected: { 1: -50, 2: -51 } },
|
||||
{ totalCents: -101, users: [1, 2], itemId: 1, expected: { 1: -51, 2: -50 } },
|
||||
{ totalCents: -1, users: [1, 2, 3], itemId: 0, expected: { 1: 0, 2: 0, 3: -1 } },
|
||||
];
|
||||
|
||||
describe('splitEqualShares', () => {
|
||||
it.each(SHARE_PARITY_FIXTURE)(
|
||||
'splits $totalCents across $users.length members (item $itemId)',
|
||||
({ totalCents, users, itemId, expected }) => {
|
||||
const shares = splitEqualShares(
|
||||
totalCents,
|
||||
users.map((user_id) => ({ user_id })),
|
||||
itemId,
|
||||
);
|
||||
expect(shares).toEqual(expected);
|
||||
expect(Object.values(shares).reduce((a, b) => a + b, 0)).toBe(totalCents);
|
||||
},
|
||||
);
|
||||
|
||||
it('orders members by user id whatever order they arrive in', () => {
|
||||
expect(splitEqualShares(100, [{ user_id: 9 }, { user_id: 2 }, { user_id: 5 }], 0)).toEqual({ 2: 34, 5: 33, 9: 33 });
|
||||
});
|
||||
|
||||
it('answers an empty map for nobody', () => {
|
||||
expect(splitEqualShares(500, [], 3)).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* Money arithmetic both sides need to agree on to the cent.
|
||||
*
|
||||
* The ledger is netted in whole hundredths of the currency ("minor units" here
|
||||
* always means hundredths, whatever the currency's display precision: a yen
|
||||
* amount is held as yen × 100 like every other one). Floats are only the
|
||||
* storage format; every sum, split and comparison happens on these integers.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Currencies whose display precision is not two decimals. HUF is kept
|
||||
* zero-decimal by app convention even though ISO lists two.
|
||||
*/
|
||||
const ZERO_DECIMAL_CURRENCIES: ReadonlySet<string> = new Set([
|
||||
'JPY',
|
||||
'KRW',
|
||||
'VND',
|
||||
'CLP',
|
||||
'ISK',
|
||||
'HUF',
|
||||
'BIF',
|
||||
'DJF',
|
||||
'GNF',
|
||||
'KMF',
|
||||
'PYG',
|
||||
'RWF',
|
||||
'UGX',
|
||||
'VUV',
|
||||
'XAF',
|
||||
'XOF',
|
||||
'XPF',
|
||||
]);
|
||||
const THREE_DECIMAL_CURRENCIES: ReadonlySet<string> = new Set(['BHD', 'IQD', 'JOD', 'KWD', 'LYD', 'OMR', 'TND']);
|
||||
|
||||
/** How many decimals a currency is shown with (0, 2 or 3). Case-insensitive; unknown codes get 2. */
|
||||
export function currencyDecimals(currency: string): number {
|
||||
const cur = currency.toUpperCase();
|
||||
if (ZERO_DECIMAL_CURRENCIES.has(cur)) return 0;
|
||||
if (THREE_DECIMAL_CURRENCIES.has(cur)) return 3;
|
||||
return 2;
|
||||
}
|
||||
|
||||
/** An amount in whole hundredths, rounded half away from zero the way `Math.round` does for positives. */
|
||||
export function toMinor(amount: number): number {
|
||||
return Math.round(amount * 100);
|
||||
}
|
||||
|
||||
/** The sum of several amounts in whole hundredths: each one is rounded first, so float noise never adds up. */
|
||||
export function sumMinor(amounts: readonly number[]): number {
|
||||
return amounts.reduce((sum, amount) => sum + toMinor(amount), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Split `totalMinor` equally across `members`, in whole hundredths, keyed by
|
||||
* user id.
|
||||
*
|
||||
* Largest remainder by rotation: the leftover hundredths go to consecutive
|
||||
* members starting at `itemId % n` (members ordered by user id), so across
|
||||
* several expenses the rounding evens out instead of always favouring the same
|
||||
* person. The remainder is `total - base * n` with a floored base, never `%`,
|
||||
* so a negative total (a refund, #2176) still yields a remainder in [0, n) and
|
||||
* the shares always sum back to the total exactly.
|
||||
*/
|
||||
export function splitEqualShares(
|
||||
totalMinor: number,
|
||||
members: readonly { user_id: number }[],
|
||||
itemId: number,
|
||||
): Record<number, number> {
|
||||
const n = members.length;
|
||||
if (n === 0) return {};
|
||||
|
||||
const base = Math.floor(totalMinor / n);
|
||||
const remainder = totalMinor - base * n;
|
||||
const sorted = [...members].sort((a, b) => a.user_id - b.user_id);
|
||||
const startIndex = itemId % n;
|
||||
|
||||
const shares: Record<number, number> = {};
|
||||
sorted.forEach((member, i) => {
|
||||
const hasExtra = (i - startIndex + n) % n < remainder;
|
||||
shares[member.user_id] = base + (hasExtra ? 1 : 0);
|
||||
});
|
||||
return shares;
|
||||
}
|
||||
Reference in New Issue
Block a user