mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-21 11:36:05 +00:00
fix(budget): a custom split in a foreign currency adds up to what was paid
Each member's amount was converted and rounded to a cent on its own, so four 34,000 ISK quarters of a 136,000 ISK bill came to 997.52 EUR against the 997.51 the payer was credited. The balances ended a few cents off zero and settle-up had no payment for them. A split whose amounts match the payers in the bill's own currency is now converted as one set by largest remainder, in the settlement and in the per-person summary alike.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { sumMinor } from '@trek/shared';
|
||||
import { splitEqualShares, sumMinor, toMinor } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* Re-denominate whole trip-currency cents into whole display-currency cents
|
||||
@@ -54,6 +54,65 @@ export function allocateDisplayCents(cents: number[], factor: number, total?: nu
|
||||
return unit === 1 ? out : out.map((v) => v * unit);
|
||||
}
|
||||
|
||||
/**
|
||||
* A custom split's member amounts as trip cents that add up to what the payers were
|
||||
* credited. Converting each amount on its own rounds each one to a cent, so four
|
||||
* quarters of a 136,000 ISK bill came to 4 x 249.38 = 997.52 EUR against the 997.51
|
||||
* the payer was credited: every such bill left the balances a cent off zero, a cent
|
||||
* the settle-up list then had no payment for. When the amounts add up to the payers'
|
||||
* total in the bill's own currency, as the write path insists, they are allocated
|
||||
* against `creditCents` by largest remainder, ties to the lower user id. A split that
|
||||
* does not add up (rows from before that check) still converts member by member.
|
||||
*/
|
||||
export function customSplitCents(
|
||||
members: readonly { user_id: number; amount?: number | null }[],
|
||||
convert: (amount: number) => number,
|
||||
creditCents: number,
|
||||
paidMinor: number,
|
||||
): Record<number, number> {
|
||||
const shares: Record<number, number> = {};
|
||||
const own = members.map((m) => m.amount ?? 0);
|
||||
if (members.length === 0) return shares;
|
||||
if (sumMinor(own) !== paidMinor) {
|
||||
members.forEach((m, i) => (shares[m.user_id] = toMinor(convert(own[i]))));
|
||||
return shares;
|
||||
}
|
||||
const exact = own.map((amount) => convert(amount) * 100);
|
||||
const cents = exact.map((v) => Math.floor(v));
|
||||
let drift = creditCents - cents.reduce((a, c) => a + c, 0);
|
||||
const rows = members.map((m, i) => ({ i, userId: m.user_id, frac: exact[i] - cents[i] }));
|
||||
const up = [...rows].sort((a, b) => b.frac - a.frac || a.userId - b.userId);
|
||||
const down = [...rows].sort((a, b) => a.frac - b.frac || a.userId - b.userId);
|
||||
for (let k = 0; drift > 0; k++, drift--) cents[up[k % up.length].i] += 1;
|
||||
for (let k = 0; drift < 0; k++, drift++) cents[down[k % down.length].i] -= 1;
|
||||
members.forEach((m, i) => (shares[m.user_id] = cents[i]));
|
||||
return shares;
|
||||
}
|
||||
|
||||
/**
|
||||
* Each member's part of one expense for the per-person summary, in trip cents. A
|
||||
* member with an amount of their own owes exactly that, the rest split the total
|
||||
* evenly, as the query this replaced did. When every member has an amount, the
|
||||
* amounts are converted as one set (customSplitCents) the way the settlement
|
||||
* converts them, so the parts add up to the bill.
|
||||
*/
|
||||
export function summaryShareCents(
|
||||
members: readonly { user_id: number; amount?: number | null }[],
|
||||
convert: (amount: number) => number,
|
||||
totalPrice: number,
|
||||
itemId: number,
|
||||
): Record<number, number> {
|
||||
const totalCents = toMinor(convert(totalPrice));
|
||||
const hasAmount = (m: { amount?: number | null }) => m.amount !== null && m.amount !== undefined;
|
||||
if (members.length > 0 && members.every(hasAmount)) {
|
||||
return customSplitCents(members, convert, totalCents, toMinor(totalPrice));
|
||||
}
|
||||
const equal = splitEqualShares(totalCents, members, itemId);
|
||||
return Object.fromEntries(
|
||||
members.map((m) => [m.user_id, hasAmount(m) ? toMinor(convert(m.amount as number)) : equal[m.user_id] || 0]),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* What `exchange_rate` holds on a row whose rate was never frozen. The column is
|
||||
* `REAL NOT NULL DEFAULT 1`, so without a migration 1 is the only way to store "no
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import type { BudgetFallbackFx, BudgetParticipantFinal, BudgetUnconverted, TrekWsPayload, TrekWsTripEventName } from '@trek/shared';
|
||||
import { currencyDecimals, splitEqualShares, toMinor } from '@trek/shared';
|
||||
import { currencyDecimals, splitEqualShares, sumMinor, toMinor } from '@trek/shared';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { avatarUrl } from '../common/avatarUrl';
|
||||
@@ -31,7 +31,7 @@ import { BUDGET_ITEM_TICKET, RESERVATION_METADATA } from '../../db/json-columns'
|
||||
import { decodeJson, decodeJsonResult, encodeJson } from '../../utils/json-column';
|
||||
import { DomainError } from '../common/domain-error';
|
||||
import { GUEST_HAS_PAYMENTS, shareAfterLeaving } from './budget-departure.helpers';
|
||||
import { allocateDisplayCents, isFrozenRate, NOT_FROZEN_RATE, quoteRatio, sumMoney, tripConverter } from './budget-money.helpers';
|
||||
import { allocateDisplayCents, customSplitCents, isFrozenRate, NOT_FROZEN_RATE, quoteRatio, summaryShareCents, sumMoney, tripConverter } from './budget-money.helpers';
|
||||
|
||||
type Trip = TripAccess;
|
||||
|
||||
@@ -992,12 +992,9 @@ export class BudgetService {
|
||||
// A foreign row nothing can convert counts for nobody, as in the settlement.
|
||||
const convert = tripConverter(item.currency, item.exchange_rate, tripCurrency, rates);
|
||||
if (!convert) continue;
|
||||
const toTripCents = (amount: number) => toMinor(convert(amount));
|
||||
// A member with an amount of their own owes exactly that; the rest split the
|
||||
// total evenly, as the query this replaces did.
|
||||
const equal = splitEqualShares(toTripCents(item.total_price || 0), own, item.id);
|
||||
const shares = summaryShareCents(own, convert, item.total_price || 0, item.id);
|
||||
for (const m of own) {
|
||||
const share = m.amount !== null && m.amount !== undefined ? toTripCents(m.amount) : (equal[m.user_id] || 0);
|
||||
const share = shares[m.user_id] || 0;
|
||||
let p = people.get(m.user_id);
|
||||
if (!p) {
|
||||
p = { user_id: m.user_id, username: m.username, avatar: m.avatar, assigned: 0, paid: 0, items_count: 0 };
|
||||
@@ -1184,7 +1181,6 @@ export class BudgetService {
|
||||
unconvertedCurrencies.add((item.currency || '').toUpperCase());
|
||||
continue;
|
||||
}
|
||||
const toTripCents = (amount: number): number => toMinor(convert(amount));
|
||||
const members = allMembers.filter(m => m.budget_item_id === item.id);
|
||||
const payers = allPayers.filter(p => p.budget_item_id === item.id);
|
||||
if (members.length === 0) continue; // planning-only entry → doesn't affect balances
|
||||
@@ -1231,12 +1227,11 @@ export class BudgetService {
|
||||
// here since #2225. An item whose payers net to exactly zero still does, and
|
||||
// divides zero, which is what it is worth.
|
||||
const hasCustomSplit = members.some(m => m.amount !== null && m.amount !== undefined);
|
||||
const equalShares = !hasCustomSplit ? splitEqualShares(creditCents, members, item.id) : {};
|
||||
const shares = hasCustomSplit
|
||||
? customSplitCents(members, convert, creditCents, sumMinor(payers.map(p => p.amount)))
|
||||
: splitEqualShares(creditCents, members, item.id);
|
||||
for (const m of members) {
|
||||
const memberShare = hasCustomSplit && m.amount !== null && m.amount !== undefined
|
||||
? toTripCents(m.amount)
|
||||
: (equalShares[m.user_id] || 0);
|
||||
ensure(m.user_id, m).cents -= memberShare;
|
||||
ensure(m.user_id, m).cents -= shares[m.user_id] || 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user