Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions public/locales/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,7 @@
"expense_participant": {
"gets": "{actor, select, you {<person/> get <amount/>} other {<person/> gets <amount/>}}",
"owes": "{actor, select, you {<person/> owe <amount/>} other {<person/> owes <amount/>}}",
"owes_and_gets": "{actor, select, you {<person/> owe <share/> and get back <amount/>} other {<person/> owes <share/> and gets back <amount/>}}",
"paid": "<person/> paid <amount/>",
"received": "<person/> received <amount/>"
},
Expand Down
26 changes: 22 additions & 4 deletions src/components/Expense/ExpenseDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { toast } from 'sonner';
import { useTranslationWithUtils } from '~/hooks/useTranslationWithUtils';
import { DEFAULT_CATEGORY } from '~/lib/category';
import { isCurrencyCode } from '~/lib/currency';
import { getParticipantShare, hasShareBreakdown } from '~/lib/expenseShare';
import type { ExpenseRouter } from '~/server/api/routers/expense';
import { useAddExpenseStore } from '~/store/addStore';
import { api } from '~/utils/api';
Expand Down Expand Up @@ -41,6 +42,7 @@ const ExpenseDetails: React.FC<ExpenseDetailsProps> = ({ user, expense }) => {
const { displayName, toUIDate, t, getCurrencyHelpersCached } = useTranslationWithUtils();

const { toUIString } = getCurrencyHelpersCached(expense.currency);
const showShareBreakdown = hasShareBreakdown(expense);

return (
<>
Expand Down Expand Up @@ -109,7 +111,7 @@ const ExpenseDetails: React.FC<ExpenseDetailsProps> = ({ user, expense }) => {
<div>{expense.fileKey ? <Receipt fileKey={expense.fileKey} /> : null}</div>
</div>
<Separator />
<div className="mt-10 flex items-center gap-2">
<div className="mt-10 flex flex-wrap items-center gap-x-2 gap-y-1">
<Trans
t={t}
i18nKey={
Expand Down Expand Up @@ -148,6 +150,11 @@ const ExpenseDetails: React.FC<ExpenseDetailsProps> = ({ user, expense }) => {
participant={participant}
userId={user.id}
currency={expense.currency}
payerShare={
showShareBreakdown && participant.userId === expense.paidBy
? getParticipantShare(participant, expense)
: undefined
}
/>
))}
{expense.conversionTo && (
Expand All @@ -174,19 +181,29 @@ const ExpenseParticipantEntry: React.FC<{
participant: ExpenseDetailsOutput['expenseParticipants'][number];
userId: number;
currency: string;
}> = ({ participant, userId, currency }) => {
/** The payer's own share, shown alongside what they get back. Omitted for everyone else. */
payerShare?: bigint;
}> = ({ participant, userId, currency, payerShare }) => {
const { displayName, t, getCurrencyHelpersCached } = useTranslationWithUtils();
const { toUIString } = getCurrencyHelpersCached(currency);

const isCurrentUser = userId === participant.userId;
const isPositive = participant.amount > 0n;
const amountColorClass = isPositive ? 'text-positive' : 'text-negative';
const hasPayerShare = undefined !== payerShare && 0n < payerShare;

const getI18nKey = () => {
if (hasPayerShare && isPositive) {
return 'expense_participant.owes_and_gets';
}
return isPositive ? 'expense_participant.gets' : 'expense_participant.owes';
};

return (
<div key={participant.userId} className="flex items-center gap-2 text-sm">
<div key={participant.userId} className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
<Trans
t={t}
i18nKey={isPositive ? 'expense_participant.gets' : 'expense_participant.owes'}
i18nKey={getI18nKey()}
values={{ actor: isCurrentUser ? 'you' : 'other' }}
components={{
person: (
Expand All @@ -198,6 +215,7 @@ const ExpenseParticipantEntry: React.FC<{
</Link>
),
amount: <span className={amountColorClass}>{toUIString(participant.amount)}</span>,
share: <span className="text-negative">{toUIString(payerShare ?? 0n)}</span>,
}}
/>
</div>
Expand Down
13 changes: 13 additions & 0 deletions src/lib/expenseShare.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { type SplitType } from '@prisma/client';

import { isSpendingSplitType } from '~/lib/splitTypes';

/** Whether participants can be shown as "owes X and gets back Y" instead of net amounts. */
export const hasShareBreakdown = (expense: { amount: bigint; splitType: SplitType }) =>
0n < expense.amount && isSpendingSplitType(expense.splitType);

/** A participant's share of an expense. Stored amounts are net: what they paid minus their share. */
export const getParticipantShare = (
participant: { userId: number; amount: bigint },
expense: { paidBy: number; amount: bigint },
) => (participant.userId === expense.paidBy ? expense.amount : 0n) - participant.amount;
8 changes: 0 additions & 8 deletions src/lib/groupStatistics.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,6 @@
import { SplitType } from '@prisma/client';

import { type CurrencyCode, isCurrencyCode } from '~/lib/currency';
import { BigMath, currencyConversion } from '~/utils/numbers';

// Settlements and currency conversions move money between people; they aren't spending.
export const NON_SPENDING_SPLIT_TYPES = [
SplitType.SETTLEMENT,
SplitType.CURRENCY_CONVERSION,
] as const;

export interface StatisticsExpense {
paidBy: number;
currency: string;
Expand Down
10 changes: 10 additions & 0 deletions src/lib/splitTypes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { SplitType } from '@prisma/client';

// Settlements and currency conversions move money between people; they aren't spending.
export const NON_SPENDING_SPLIT_TYPES = [
SplitType.SETTLEMENT,
SplitType.CURRENCY_CONVERSION,
] as const satisfies readonly SplitType[];

export const isSpendingSplitType = (splitType: SplitType) =>
!(NON_SPENDING_SPLIT_TYPES as readonly SplitType[]).includes(splitType);
7 changes: 2 additions & 5 deletions src/server/api/routers/group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,9 @@ import { TRPCError } from '@trpc/server';
import { nanoid } from 'nanoid';
import { z } from 'zod';

import {
NON_SPENDING_SPLIT_TYPES,
computeMemberTotals,
currenciesByUse,
} from '~/lib/groupStatistics';
import { computeMemberTotals, currenciesByUse } from '~/lib/groupStatistics';
import { simplifyDebts } from '~/lib/simplify';
import { NON_SPENDING_SPLIT_TYPES } from '~/lib/splitTypes';
import {
balanceProcedure,
createTRPCRouter,
Expand Down
60 changes: 60 additions & 0 deletions src/tests/expenseShare.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { SplitType } from '@prisma/client';

import { getParticipantShare, hasShareBreakdown } from '~/lib/expenseShare';

describe('getParticipantShare', () => {
describe('Equal split', () => {
const expense = { paidBy: 1, amount: 10000n };

it('should return the payer share from their net amount', () => {
expect(getParticipantShare({ userId: 1, amount: 7500n }, expense)).toBe(2500n);
});

it('should return the share of someone who did not pay', () => {
expect(getParticipantShare({ userId: 2, amount: -2500n }, expense)).toBe(2500n);
});
});

describe('Payer not in the split', () => {
it('should return a zero share for the payer', () => {
expect(
getParticipantShare({ userId: 1, amount: 10000n }, { paidBy: 1, amount: 10000n }),
).toBe(0n);
});
});

describe('Exact split', () => {
const expense = { paidBy: 1, amount: 10000n };

it('should return each exact share', () => {
expect(getParticipantShare({ userId: 1, amount: 9000n }, expense)).toBe(1000n);
expect(getParticipantShare({ userId: 2, amount: -6000n }, expense)).toBe(6000n);
expect(getParticipantShare({ userId: 3, amount: -3000n }, expense)).toBe(3000n);
});
});
});

describe('hasShareBreakdown', () => {
describe('Spending', () => {
it('should allow a regular expense', () => {
expect(hasShareBreakdown({ amount: 10000n, splitType: SplitType.EQUAL })).toBe(true);
});

it('should not allow a refund', () => {
expect(hasShareBreakdown({ amount: -10000n, splitType: SplitType.EQUAL })).toBe(false);
});

it('should not allow a zero amount', () => {
expect(hasShareBreakdown({ amount: 0n, splitType: SplitType.EQUAL })).toBe(false);
});
});

describe('Money moving between people', () => {
it('should not allow settlements or currency conversions', () => {
expect(hasShareBreakdown({ amount: 10000n, splitType: SplitType.SETTLEMENT })).toBe(false);
expect(hasShareBreakdown({ amount: 10000n, splitType: SplitType.CURRENCY_CONVERSION })).toBe(
false,
);
});
});
});
2 changes: 2 additions & 0 deletions tests/e2e/group-expense.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ test('records a two-member expense with exact persisted shares and debt', async
.click();
await expect(page).toHaveURL(/\/groups\/\d+\/expenses\//);
await expect(page.getByText(`${uniqueName} expense`, { exact: true })).toBeVisible();
await expect(page.getByText(/^You owe \$6\.17 and get back \$6\.17$/)).toBeVisible();
await expect(page.getByText(/^E2E Member owes \$6\.17$/)).toBeVisible();
const expense = await db.expense.findFirstOrThrow({
where: { groupId: scenario.group.id },
include: { expenseParticipants: true },
Expand Down
Loading