The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
feat(costs): split a custom expense by shares (#1165)
Maurice10d5f3ed460f
diff --git a/client/src/components/Budget/CostsPanel.tsx b/client/src/components/Budget/CostsPanel.tsxindex c6c968d43..6b482c956 100644--- a/client/src/components/Budget/CostsPanel.tsx+++ b/client/src/components/Budget/CostsPanel.tsx@@ -23,7 +23,7 @@ import {import { useCostsLedger } from './useCostsLedger'import { useExpenseLinks } from './useExpenseLinks'import { useSettlementForm } from './useSettlementForm'-import { usePercentSplit, type CustomSplitUnit } from './usePercentSplit'+import type { CustomSplitUnit } from './usePercentSplit'import { useExpenseForm } from './useExpenseForm'import { ReceiptPreviewModal } from './ReceiptPreviewModal'import { useExpenseDeleteConfirm } from './useExpenseDeleteConfirm'@@ -1132,14 +1132,14 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClohandleRemoveReceipt, handleToggleItemParticipant, handleUpdateItemName, handleUpdateItemPrice, isTicketMode,multiPayer, name, nameOf, note, onPayerAmountChange, onTotalChange, participants, payerAmounts, payerId, payerIds,payersOk, pendingReceiptFiles, placeholderShares, previewReceipts: modalPreviewReceipts, receipts, save, saving,- currencyChoices, setCat, setCurrency, setCustomAmounts, setDay, setName, setNote, setPayerId,+ currencyChoices, setCat, setCurrency, setDay, setName, setNote, setPayerId, splitUnits: units,setPreviewReceipts: setModalPreviewReceipts, setSplitMode, splitMode, splitShortfall, splitSum, sym, ticketInfo,ticketItems, toggleParticipant, togglePayer, total, totalNum, tripCur, uploadingReceipt, valid,} = useExpenseForm({ tripId, base, people, me, editing, prefill, onSaved })- // The custom split typed as percentages instead of amounts (#1709).- const pct = usePercentSplit({ total: totalNum, participants, customAmounts, setCustomAmounts, currency })- const inPercent = splitMode === 'custom' && pct.unit === 'percent'+ // A custom split typed as percentages (#1709) or shares (#1165), each field showing its amount.+ const inUnits = splitMode === 'custom' && units.unit !== 'amount'+ const inPercent = inUnits && units.unit === 'percent'const catInfo = catMeta(cat)const money = (v: number) => formatMoney(v, currency, locale)@@ -1164,7 +1164,6 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onCloconst personName = (p: TripMember, on: boolean) => (<span className={`truncate font-medium ${on ? 'text-content' : 'text-content-faint'}`} style={fs(13.5, 'body')}>{nameOf(p)}</span>)- const excludedNote = <span />const modeHint = (text: string) => <p className="m-0 mb-2.5 text-content-faint" style={fs(12, 'body')}>{text}</p>// Figures sit in badges, so an amount never reads as part of the sentence beside it.const BADGE = 'inline-flex items-center gap-1.5 whitespace-nowrap rounded-full px-2.5 py-[3px] font-geist font-semibold tabular-nums'@@ -1234,7 +1233,7 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onCloonValueChange={v => onPayerAmountChange(p.id, v)}className={AMOUNT_INPUT} style={fs(13.5, 'body')} /></div>- ) : excludedNote}+ ) : <span />}</div>)})}@@ -1266,14 +1265,15 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo>{splitMode === 'custom' ? (<div className="mb-2.5 flex items-center justify-between gap-3">- <p className="m-0 min-w-0 text-content-faint" style={fs(12, 'body')}>{t(inPercent ? 'costs.splitHint.percent' : 'costs.splitHint.custom')}</p>+ <p className="m-0 min-w-0 text-content-faint" style={fs(12, 'body')}>{t(inPercent ? 'costs.splitHint.percent' : inUnits ? 'costs.splitHint.shares' : 'costs.splitHint.custom')}</p><Segmented<CustomSplitUnit>label={t('costs.splitUnit')}- value={pct.unit}- onChange={pct.setUnit}+ value={units.unit}+ onChange={units.setUnit}options={[{ value: 'amount', label: sym(currency) },{ value: 'percent', label: '%' },+ { value: 'shares', label: t('costs.splitUnitShares') },]}/></div>@@ -1361,15 +1361,16 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo{personName(p, on)}{p.is_guest && <GuestBadge size="xs" customTooltip />}</button>- {!on ? excludedNote : splitMode === 'equally' ? (+ {!on ? <span /> : splitMode === 'equally' ? (<span className="text-end">{badge(money(equalShares[p.id] || 0))}</span>- ) : inPercent ? (+ ) : inUnits ? (<div className="flex flex-col items-end gap-0.5"><div className={`${AMOUNT_BOX} w-full`}>- <input type="text" inputMode="decimal" aria-label={`${nameOf(p)} %`} placeholder={pct.placeholderPercent} value={pct.percents[p.id] ?? ''}- onChange={e => pct.onPercentChange(p.id, e.target.value)}+ <input type="text" inputMode="decimal" placeholder={units.placeholder}+ aria-label={inPercent ? `${nameOf(p)} %` : t('costs.splitSharesOf', { name: nameOf(p) })}+ value={units.entries[p.id] ?? ''} onChange={e => units.onEntryChange(p.id, e.target.value)}className={AMOUNT_INPUT} style={fs(13.5, 'body')} />- <span className="text-content-faint" style={fs(13, 'body')}>%</span>+ {inPercent && <span className="text-content-faint" style={fs(13, 'body')}>%</span>}</div>{customAmounts[p.id] && <span className="font-geist tabular-nums text-content-faint" style={fs(10.5)}>{money(Number.parseFloat(customAmounts[p.id]) || 0)}</span>}</div>@@ -1393,8 +1394,8 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo</>) : customBalanced ? (badge(<><Check size={12} strokeWidth={3} />{t('costs.splitBalanced')}</>, 'success')- ) : inPercent ? (- badge(<><AlertCircle size={12} strokeWidth={2.4} />{t('costs.splitPercentOff', { sum: String(Math.round(pct.percentSum * 100) / 100) })}</>, 'danger')+ ) : inUnits ? (+ badge(<><AlertCircle size={12} strokeWidth={2.4} />{inPercent ? t('costs.splitPercentOff', { sum: String(Math.round(units.percentSum * 100) / 100) }) : t('costs.splitSharesNone')}</>, 'danger')) : (badge(<><AlertCircle size={12} strokeWidth={2.4} />{t(splitShortfall > 0 ? 'costs.splitSumUnder' : 'costs.splitSumOver', {sum: money(splitSum),diff --git a/client/src/components/Budget/ExpenseModal.split.test.tsx b/client/src/components/Budget/ExpenseModal.split.test.tsxnew file mode 100644index 000000000..bf80f3411--- /dev/null+++ b/client/src/components/Budget/ExpenseModal.split.test.tsx@@ -0,0 +1,72 @@+// FE-COSTS-EXPSPLIT-001 to FE-COSTS-EXPSPLIT-002+import userEvent from '@testing-library/user-event';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { buildBudgetItem, buildTrip, buildUser } from '../../../tests/helpers/factories';+import { render, screen, waitFor } from '../../../tests/helpers/render';+import { resetAllStores, seedStore } from '../../../tests/helpers/store';+import { useAuthStore } from '../../store/authStore';+import { useTripStore, type TripStoreState } from '../../store/tripStore';+import { ExpenseModal } from './CostsPanel';++const people = [+ { id: 1, username: 'alice', avatar_url: null },+ { id: 2, username: 'bob', avatar_url: null },+];++let addBudgetItem: ReturnType<typeof vi.fn>;++beforeEach(() => {+ resetAllStores();+ seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true });+ addBudgetItem = vi.fn(async () => buildBudgetItem({ id: 9 }));+ useTripStore.setState({+ trip: buildTrip({ id: 1, currency: 'EUR' }),+ addBudgetItem,+ } as unknown as Partial<TripStoreState>);+});++async function startCustomSplit(total: string) {+ const user = userEvent.setup();+ render(+ <ExpenseModal tripId={1} base="EUR" people={people} me={1} editing={null} onClose={vi.fn()} onSaved={vi.fn()} />+ );+ await user.type(screen.getByPlaceholderText('e.g. Dinner, souvenirs, gas…'), 'Apartment');+ await user.type(screen.getAllByPlaceholderText('0,00')[0], total);+ await user.click(screen.getByRole('button', { name: 'Custom' }));+ await user.click(screen.getByRole('button', { name: 'Shares' }));+ return user;+}++describe('ExpenseModal: a custom split by shares (#1165)', () => {+ it('FE-COSTS-EXPSPLIT-001: five nights against four save the stay split 5/9 to 4/9', async () => {+ const user = await startCustomSplit('390');+ // Shares start even, one each, so the split balances before anything is typed.+ expect(screen.getByText('Split matches total')).toBeInTheDocument();++ await user.type(screen.getByRole('textbox', { name: 'Shares for You' }), '5');+ await user.type(screen.getByRole('textbox', { name: 'Shares for bob' }), '4');+ expect(screen.getByText('216,67 €')).toBeInTheDocument();+ expect(screen.getByText('173,33 €')).toBeInTheDocument();++ const submits = screen.getAllByRole('button', { name: 'Add expense' });+ await user.click(submits[submits.length - 1]);+ await waitFor(() => expect(addBudgetItem).toHaveBeenCalledTimes(1));+ expect(addBudgetItem.mock.calls[0][1]).toMatchObject({+ total_price: 390,+ members: [+ { user_id: 1, amount: 216.67 },+ { user_id: 2, amount: 173.33 },+ ],+ });+ });++ it('FE-COSTS-EXPSPLIT-002: nobody holding a share leaves the split open and the save blocked', async () => {+ const user = await startCustomSplit('90');+ await user.type(screen.getByRole('textbox', { name: 'Shares for You' }), '0');+ await user.type(screen.getByRole('textbox', { name: 'Shares for bob' }), '0');+ expect(screen.getByText('Give at least one person a share')).toBeInTheDocument();+ const submits = screen.getAllByRole('button', { name: 'Add expense' });+ expect(submits[submits.length - 1]).toBeDisabled();+ });+});diff --git a/client/src/components/Budget/useExpenseForm.ts b/client/src/components/Budget/useExpenseForm.tsindex c7b5212c8..131e4114f 100644--- a/client/src/components/Budget/useExpenseForm.ts+++ b/client/src/components/Budget/useExpenseForm.ts@@ -29,6 +29,7 @@ import { catMeta } from './costsCategories';import { currencyOptions } from './costsModel';import { useExpenseFx } from './expenseFx';import { saveWithReceipts } from './receiptUploads';+import { usePercentSplit } from './usePercentSplit';export type ExpenseSplitMode = 'equally' | 'custom' | 'ticket';@@ -38,7 +39,7 @@ let ticketItemSeq = 0;/*** The expense editor behind the desktop ExpenseModal and the phone MCostSheet:* name, category, amount and currency, payers, the Equally / Custom / Ticket- * splits, the note and the receipts, what makes the entry valid, and the save+ * splits (a custom one typed as amounts, percentages or shares), the note and the receipts, what makes the entry valid, and the save* through the trip store. Both surfaces lay it out their own way.** Where the two save differently today, the surface says which way:@@ -182,6 +183,8 @@ export function useExpenseForm({const totalNum = isTicketMode ? ticketInfo.total : Number.parseFloat(total) || 0;const fx = preview(totalNum, currency);+ // The custom split typed as percentages (#1709) or shares (#1165) instead of amounts.+ const splitUnits = usePercentSplit({ total: totalNum, participants, customAmounts, setCustomAmounts, currency });const splitSum = [...participants].reduce((sum, id) => sum + (Number.parseFloat(customAmounts[id]) || 0), 0);const customBalanced = Math.round(splitSum * 100) === Math.round(totalNum * 100);// How much is still to be handed out, read on the total's own side: on a refund@@ -468,8 +471,8 @@ export function useExpenseForm({handleRemoveItem,handleToggleItemParticipant,customAmounts,- setCustomAmounts,handleCustomAmountChange,+ splitUnits,splitSum,customBalanced,splitShortfall,diff --git a/client/src/components/Budget/usePercentSplit.test.ts b/client/src/components/Budget/usePercentSplit.test.tsindex 301787e7e..09d277e0f 100644--- a/client/src/components/Budget/usePercentSplit.test.ts+++ b/client/src/components/Budget/usePercentSplit.test.ts@@ -1,8 +1,8 @@-// FE-BUDGET-PCT-001 to FE-BUDGET-PCT-006+// FE-BUDGET-PCT-001 to FE-BUDGET-PCT-009import { describe, it, expect } from 'vitest'import { useState } from 'react'import { act, renderHook } from '@testing-library/react'-import { amountsToPercents, percentsToAmounts, percentString, usePercentSplit } from './usePercentSplit'+import { amountsToPercents, percentsToAmounts, percentString, sharesToAmounts, shareWeight, usePercentSplit } from './usePercentSplit'describe('percent split maths (#1709)', () => {it('FE-BUDGET-PCT-001: thirds add up to the total exactly', () => {@@ -31,7 +31,29 @@ describe('percent split maths (#1709)', () => {})})-describe('usePercentSplit (#1709)', () => {+describe('share split maths (#1165)', () => {+ it('FE-BUDGET-PCT-007: five nights against four split the stay 5/9 to 4/9, to the cent', () => {+ expect(sharesToAmounts(390, { 1: '5', 2: '4' }, [1, 2], 'EUR')).toEqual({ 1: 216.67, 2: 173.33 })+ const thirds = sharesToAmounts(100, { 1: '1', 2: '1', 3: '1' }, [1, 2, 3], 'EUR')+ expect(Math.round(Object.values(thirds).reduce((s, v) => s + v, 0) * 100)).toBe(10000)+ // A refund runs negative and still adds up; a won amount stays whole.+ const refund = sharesToAmounts(-10, { 1: '2', 2: '1' }, [1, 2], 'EUR')+ expect(Math.round((refund[1] + refund[2]) * 100)).toBe(-1000)+ expect(sharesToAmounts(1000, { 1: '1', 2: '2' }, [1, 2], 'KRW')).toEqual({ 1: 333, 2: 667 })+ })++ it('FE-BUDGET-PCT-008: an empty field is one share, zero is none, and nobody holding one gives no amounts', () => {+ expect(shareWeight(undefined)).toBe(1)+ expect(shareWeight('')).toBe(1)+ expect(shareWeight('0')).toBe(0)+ expect(shareWeight('2.5')).toBe(2.5)+ expect(sharesToAmounts(90, { 1: '2' }, [1, 2], 'EUR')).toEqual({ 1: 60, 2: 30 })+ expect(sharesToAmounts(90, { 1: '0', 2: '3' }, [1, 2], 'EUR')).toEqual({ 1: 0, 2: 90 })+ expect(sharesToAmounts(90, { 1: '0', 2: '0' }, [1, 2], 'EUR')).toEqual({})+ })+})++describe('usePercentSplit (#1709, #1165)', () => {function setup(total = 90) {return renderHook(({ t }) => {const [amounts, setAmounts] = useState<Record<number, string>>({ 1: '30', 2: '60' })@@ -43,24 +65,38 @@ describe('usePercentSplit (#1709)', () => {it('FE-BUDGET-PCT-005: switching to % carries the typed amounts over, and typing writes amounts back', () => {const { result } = setup()act(() => result.current.pct.setUnit('percent'))- expect(result.current.pct.percents).toEqual({ 1: '33.33', 2: '66.67' })- act(() => result.current.pct.onPercentChange(1, '50'))- act(() => result.current.pct.onPercentChange(2, '25'))- act(() => result.current.pct.onPercentChange(3, '25'))+ expect(result.current.pct.entries).toEqual({ 1: '33.33', 2: '66.67' })+ act(() => result.current.pct.onEntryChange(1, '50'))+ act(() => result.current.pct.onEntryChange(2, '25'))+ act(() => result.current.pct.onEntryChange(3, '25'))expect(result.current.amounts).toEqual({ 1: '45.00', 2: '22.50', 3: '22.50' })expect(result.current.pct.percentSum).toBe(100)// Not a percentage: ignored.- act(() => result.current.pct.onPercentChange(3, 'abc'))- expect(result.current.pct.percents[3]).toBe('25')+ act(() => result.current.pct.onEntryChange(3, 'abc'))+ expect(result.current.pct.entries[3]).toBe('25')})it('FE-BUDGET-PCT-006: a changed total moves the amounts, the placeholder offers the rest', () => {const { result, rerender } = setup()act(() => result.current.pct.setUnit('percent'))- act(() => result.current.pct.onPercentChange(1, '50'))- act(() => result.current.pct.onPercentChange(2, ''))- expect(result.current.pct.placeholderPercent).toBe('25')+ act(() => result.current.pct.onEntryChange(1, '50'))+ act(() => result.current.pct.onEntryChange(2, ''))+ expect(result.current.pct.placeholder).toBe('25')rerender({ t: 200 })expect(result.current.amounts).toEqual({ 1: '100.00' })})++ it('FE-BUDGET-PCT-009: shares start even, one each, and typed shares write the amounts back', () => {+ const { result, rerender } = setup()+ act(() => result.current.pct.setUnit('shares'))+ expect(result.current.pct.entries).toEqual({})+ expect(result.current.pct.placeholder).toBe('1')+ expect(result.current.amounts).toEqual({ 1: '30.00', 2: '30.00', 3: '30.00' })+ act(() => result.current.pct.onEntryChange(1, '5'))+ act(() => result.current.pct.onEntryChange(2, '4'))+ act(() => result.current.pct.onEntryChange(3, '0'))+ expect(result.current.amounts).toEqual({ 1: '50.00', 2: '40.00', 3: '0.00' })+ rerender({ t: 390 })+ expect(result.current.amounts).toEqual({ 1: '216.67', 2: '173.33', 3: '0.00' })+ })})diff --git a/client/src/components/Budget/usePercentSplit.ts b/client/src/components/Budget/usePercentSplit.tsindex b92f389ca..6ea0d0944 100644--- a/client/src/components/Budget/usePercentSplit.ts+++ b/client/src/components/Budget/usePercentSplit.ts@@ -1,21 +1,39 @@import { useEffect, useState } from 'react'import { amountToInputString, currencyDecimals } from '../../utils/formatters'-export type CustomSplitUnit = 'amount' | 'percent'+export type CustomSplitUnit = 'amount' | 'percent' | 'shares'-const PERCENT_INPUT = /^\d{0,3}(\.\d{0,2})?$/+/** What a percent or a share field takes: up to 999, with two decimals at most. */+const UNIT_INPUT = /^\d{0,3}(\.\d{0,2})?$//** A percent as typed back into the field: at most two decimals, no trailing zeros. */export function percentString(value: number): string {return String(Math.round(value * 100) / 100)}+/**+ * Whole minor units for each id from its exact (fractional) part of `totalUnits`.+ * The parts must add up to `totalUnits`; the units a plain rounding would lose go+ * to the largest remainders, the same way splitEqualShares hands out an+ * indivisible cent, so the result adds up to the total exactly.+ */+function largestRemainder(totalUnits: number, parts: { id: number; exact: number }[]): Record<number, number> {+ const floors = parts.map(p => ({ id: p.id, units: Math.floor(p.exact), rest: p.exact - Math.floor(p.exact) }))+ let left = totalUnits - floors.reduce((s, f) => s + f.units, 0)+ // On a refund the total is negative, so the remainder runs the other way.+ const order = [...floors].sort((a, b) => (left >= 0 ? b.rest - a.rest : a.rest - b.rest) || a.id - b.id)+ for (const f of order) {+ if (left === 0) break+ f.units += Math.sign(left)+ left -= Math.sign(left)+ }+ return Object.fromEntries(floors.map(f => [f.id, f.units]))+}+/*** Amounts from percentages of `total` (#1709), in whole minor units. When the- * percentages add up to 100 the shares add up to the total exactly: the units a- * plain rounding would lose go to the largest remainders, the same way- * splitEqualShares hands out an indivisible cent. Ids without a percentage get- * no amount.+ * percentages add up to 100 the shares add up to the total exactly (see+ * largestRemainder). Ids without a percentage get no amount.*/export function percentsToAmounts(total: number, percents: Record<number, string>, ids: number[], currency: string): Record<number, number> {const factor = 10 ** currencyDecimals(currency)@@ -27,22 +45,35 @@ export function percentsToAmounts(total: number, percents: Record<number, stringconst out: Record<number, number> = {}const pctSum = entered.reduce((s, e) => s + e.pct, 0)if (Math.abs(pctSum - 100) < 1e-9) {- const floors = raw.map(r => ({ id: r.id, units: Math.floor(r.exact), rest: r.exact - Math.floor(r.exact) }))- let left = totalUnits - floors.reduce((s, f) => s + f.units, 0)- // On a refund the total is negative, so the remainder runs the other way.- const order = [...floors].sort((a, b) => (left >= 0 ? b.rest - a.rest : a.rest - b.rest) || a.id - b.id)- for (const f of order) {- if (left === 0) break- f.units += Math.sign(left)- left -= Math.sign(left)- }- for (const f of floors) out[f.id] = f.units / factor+ for (const [id, units] of Object.entries(largestRemainder(totalUnits, raw))) out[Number(id)] = units / factor} else {for (const r of raw) out[r.id] = Math.round(r.exact) / factor}return out}+/** A person's number of shares; a field left empty counts as one, the equal split. */+export function shareWeight(raw: string | undefined): number {+ const n = Number.parseFloat(raw ?? '')+ return Number.isFinite(n) ? n : 1+}++/**+ * Amounts from shares of `total` (#1165): five nights against four split a+ * stay 5/9 to 4/9. The shares always add up to the whole, so the amounts add+ * up to the total exactly (see largestRemainder). No amounts while nobody holds+ * a share, which leaves the split unbalanced instead of dividing by zero.+ */+export function sharesToAmounts(total: number, shares: Record<number, string>, ids: number[], currency: string): Record<number, number> {+ const factor = 10 ** currencyDecimals(currency)+ const totalUnits = Math.round(total * factor)+ const weights = ids.map(id => ({ id, weight: shareWeight(shares[id]) }))+ const weightSum = weights.reduce((s, w) => s + w.weight, 0)+ if (weightSum <= 0) return {}+ const units = largestRemainder(totalUnits, weights.map(w => ({ id: w.id, exact: (totalUnits * w.weight) / weightSum })))+ return Object.fromEntries(Object.entries(units).map(([id, u]) => [Number(id), u / factor]))+}+/** The percentages the typed amounts make of `total`; an empty or unparsable amount stays empty. */export function amountsToPercents(total: number, amounts: Record<number, string>, ids: number[]): Record<number, string> {const out: Record<number, string> = {}@@ -65,46 +96,50 @@ interface Args {}/**- * The "%" side of a custom split (#1709). Percentages are only an input aid:- * every change is turned straight into the amounts the custom split already- * keeps, so what is saved, validated and settled is unchanged.+ * The "%" (#1709) and "shares" (#1165) sides of a custom split. Both are only+ * an input aid: every change is turned straight into the amounts the custom+ * split already keeps, so what is saved, validated and settled is unchanged.+ * `entries` holds what the person typed in the current unit, percentages or+ * shares; the amount unit types the amounts themselves.*/export function usePercentSplit({ total, participants, customAmounts, setCustomAmounts, currency, initialUnit = 'amount' }: Args) {const [unit, setUnitState] = useState<CustomSplitUnit>(initialUnit)- const [percents, setPercents] = useState<Record<number, string>>({})+ const [entries, setEntries] = useState<Record<number, string>>({})const ids = [...participants]+ // Percentages carry the typed amounts over; shares start even, one each.const setUnit = (next: CustomSplitUnit) => {if (next === unit) return- if (next === 'percent') setPercents(amountsToPercents(total, customAmounts, ids))+ setEntries(next === 'percent' ? amountsToPercents(total, customAmounts, ids) : {})setUnitState(next)}- const onPercentChange = (id: number, raw: string) => {+ const onEntryChange = (id: number, raw: string) => {const val = raw.replace(',', '.')- if (val !== '' && !PERCENT_INPUT.test(val)) return- setPercents(prev => {+ if (val !== '' && !UNIT_INPUT.test(val)) return+ setEntries(prev => {const next = { ...prev, [id]: val }if (val === '') delete next[id]return next})}- // The amounts follow the percentages: on every percentage typed, and when the- // total changes or somebody leaves the split.+ // The amounts follow the entries: on every one typed, and when the total+ // changes or somebody leaves the split.const idsKey = ids.join(',')useEffect(() => {- if (unit !== 'percent') return+ if (unit === 'amount') returnconst idList = idsKey ? idsKey.split(',').map(Number) : []- const amounts = percentsToAmounts(total, percents, idList, currency)+ const amounts = (unit === 'percent' ? percentsToAmounts : sharesToAmounts)(total, entries, idList, currency)const strings: Record<number, string> = {}for (const [id, amount] of Object.entries(amounts)) strings[Number(id)] = amountToInputString(amount, currency)setCustomAmounts(strings)- }, [unit, percents, total, idsKey, currency, setCustomAmounts])+ }, [unit, entries, total, idsKey, currency, setCustomAmounts])- const percentSum = ids.reduce((s, id) => s + (Number.parseFloat(percents[id]) || 0), 0)- const empty = ids.filter(id => !percents[id])- const placeholderPercent = empty.length > 0 ? percentString(Math.max(0, 100 - percentSum) / empty.length) : '0'+ const percentSum = ids.reduce((s, id) => s + (Number.parseFloat(entries[id]) || 0), 0)+ const empty = ids.filter(id => !entries[id])+ // The percent left over spread across the empty fields; a share field reads one.+ const placeholder = unit === 'shares' ? '1' : empty.length > 0 ? percentString(Math.max(0, 100 - percentSum) / empty.length) : '0'- return { unit, setUnit, percents, onPercentChange, percentSum, placeholderPercent }+ return { unit, setUnit, entries, onEntryChange, percentSum, placeholder }}diff --git a/client/src/mobile/screens/trip/sheets/MCostSheet.tsx b/client/src/mobile/screens/trip/sheets/MCostSheet.tsxindex 578b22240..bd30243d0 100644--- a/client/src/mobile/screens/trip/sheets/MCostSheet.tsx+++ b/client/src/mobile/screens/trip/sheets/MCostSheet.tsx@@ -15,6 +15,7 @@ import { COST_CATEGORY_LIST, catMeta } from '../../../../components/Budget/costsimport { NOTE_MAX } from '../../../../components/Budget/CostsPanel.helpers'import type { ExpensePrefill } from '../../../../components/Budget/CostsPanel'import { useExpenseForm } from '../../../../components/Budget/useExpenseForm'+import type { CustomSplitUnit } from '../../../../components/Budget/usePercentSplit'import GuestBadge from '../../../../components/shared/GuestBadge'import type { TripMember } from '../../../../components/Budget/BudgetPanelMemberChips'import { ReceiptPreviewModal } from '../../../../components/Budget/ReceiptPreviewModal'@@ -63,7 +64,7 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,totalNum, fx, participants, toggleParticipant, payerId, setPayerId, multiPayer, enableMultiPayer, disableMultiPayer,payerIds, payerAmounts, togglePayer, onPayerAmountChange, payersOk, splitMode, setSplitMode, isTicketMode, ticketItems,ticketInfo, handleAddEmptyItem, handleUpdateItemName, handleUpdateItemPrice, handleRemoveItem, handleToggleItemParticipant,- customAmounts, handleCustomAmountChange, splitSum, customBalanced, each, equalShares, placeholderShares,+ customAmounts, handleCustomAmountChange, splitUnits, splitSum, customBalanced, each, equalShares, placeholderShares,receipts, pendingReceiptFiles, uploadingReceipt, handleReceiptFileSelect, handleRemoveReceipt, handleRemovePendingReceipt,previewReceipts, setPreviewReceipts, valid, saving, save,} = useExpenseForm({ tripId, base, people, me, editing, prefill, onSaved, oneSaveAtATime: true, keepSavingOnSuccess: true })@@ -117,6 +118,14 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,)const submitLabel = saving ? t('common.saving') : editing ? t('common.save') : t('common.add')+ // A custom split typed as amounts, percentages (#1709) or shares (#1165).+ const inUnits = splitMode === 'custom' && splitUnits.unit !== 'amount'+ const inPercent = inUnits && splitUnits.unit === 'percent'+ const unitOptions: { id: CustomSplitUnit; label: string }[] = [+ { id: 'amount', label: sym(currency).trim() },+ { id: 'percent', label: '%' },+ { id: 'shares', label: t('costs.splitUnitShares') },+ ]return (<MSheet@@ -315,6 +324,28 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,))}</div>+ {splitMode === 'custom' && (+ <>+ <div role="radiogroup" aria-label={t('costs.splitUnit')} className="mt-2 flex rounded-full bg-[color:var(--m-ic)] p-[3px]">+ {unitOptions.map(u => (+ <button+ key={u.id}+ type="button"+ role="radio"+ aria-checked={splitUnits.unit === u.id}+ onClick={() => splitUnits.setUnit(u.id)}+ className={`min-w-0 flex-1 truncate rounded-full px-2 py-[6px] text-caption font-semibold ${splitUnits.unit === u.id ? 'bg-m-act text-m-actfg' : 'text-m-muted'}`}+ >+ {u.label}+ </button>+ ))}+ </div>+ <p className="mt-[6px] text-caption text-m-faint">+ {t(inPercent ? 'costs.splitHint.percent' : inUnits ? 'costs.splitHint.shares' : 'costs.splitHint.custom')}+ </p>+ </>+ )}+{isTicketMode ? (<div className="mt-2 flex flex-col gap-2">{ticketItems.map(item => (@@ -403,6 +434,26 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,) : (<span className="flex-none pe-1 text-[0.6875rem] text-m-faint">{t('costs.tapToInclude')}</span>)+ ) : on && inUnits ? (+ <div className="flex w-[120px] flex-none flex-col items-end gap-[2px]">+ <div className={`${MINI_INPUT_WRAP} w-full`}>+ <input+ type="text"+ inputMode="decimal"+ aria-label={inPercent ? `${nameOf(p)} %` : t('costs.splitSharesOf', { name: nameOf(p) })}+ placeholder={splitUnits.placeholder}+ value={splitUnits.entries[p.id] ?? ''}+ onChange={e => splitUnits.onEntryChange(p.id, e.target.value)}+ className="w-full border-0 bg-transparent py-[7px] text-end text-body font-semibold text-m-ink outline-none placeholder:font-normal placeholder:text-m-faint"+ />+ {inPercent && <span className="text-caption text-m-faint">%</span>}+ </div>+ {customAmounts[p.id] && (+ <span className="text-caption text-m-faint [font-variant-numeric:tabular-nums]">+ {formatMoney(Number.parseFloat(customAmounts[p.id]) || 0, currency, locale)}+ </span>+ )}+ </div>) : on ? (<div className={`${MINI_INPUT_WRAP} w-[120px] flex-none`}><span className="text-[0.75rem] text-m-faint">{sym(currency)}</span>@@ -431,8 +482,9 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,</span>) : (<span className={`font-semibold ${customBalanced ? 'text-[color:var(--m-st-confirmed)]' : 'text-[color:var(--m-st-danger)]'}`}>+ {/* An uneven split has no one share to print "each" with. */}{customBalanced- ? t('costs.splitSummary', { count: participants.size, amount: splitShareLabel(each, currency, fx, participants.size, base, locale) })+ ? t('costs.splitBalanced'): `${formatMoney(splitSum, currency, locale)} / ${formatMoney(totalNum, currency, locale)}`}</span>)}diff --git a/client/tests/unit/mobile/trip/MCostSheet.test.tsx b/client/tests/unit/mobile/trip/MCostSheet.test.tsxindex ceec72c91..bb5969950 100644--- a/client/tests/unit/mobile/trip/MCostSheet.test.tsx+++ b/client/tests/unit/mobile/trip/MCostSheet.test.tsx@@ -10,7 +10,7 @@ import { localToday } from '../../../../src/components/Planner/today'import { resetAllStores } from '../../../helpers/store'import { act, fireEvent, render, screen, waitFor } from '../../../helpers/render'-// FE-MOB-COSTSH-001 to FE-MOB-COSTSH-038+// FE-MOB-COSTSH-001 to FE-MOB-COSTSH-040// The sheet reads its copy from useTranslation(), so assertions are English.// EUR formats de-DE style: displayed amounts and inputs use a comma.@@ -353,7 +353,7 @@ describe('MCostSheet', () => {// The remaining share now suggests what is left of the total.fireEvent.change(screen.getByPlaceholderText('70,00'), { target: { value: '70' } })- expect(screen.getByText('Split 2 ways · 50,00 € each')).toBeInTheDocument()+ expect(screen.getByText('Split matches total')).toBeInTheDocument()fireEvent.click(submit())await waitFor(() => expect(addBudgetItem).toHaveBeenCalledWith(1, expect.objectContaining({@@ -744,4 +744,35 @@ describe('MCostSheet', () => {fireEvent.change(shares[0], { target: { value: '10000' } })expect(screen.getByText('₩10,000 / ₩60,000')).toBeInTheDocument()})++ it('FE-MOB-COSTSH-039: a custom split by shares saves the stay split by nights (#1165)', async () => {+ renderSheet()+ fillBasics('Apartment', '390')+ fireEvent.click(screen.getByRole('button', { name: 'Custom' }))+ fireEvent.click(screen.getByRole('radio', { name: 'Shares' }))+ // One share each until something is typed: the split already balances.+ expect(screen.getByRole('textbox', { name: 'Shares for You' })).toHaveAttribute('placeholder', '1')+ fireEvent.change(screen.getByRole('textbox', { name: 'Shares for You' }), { target: { value: '5' } })+ fireEvent.change(screen.getByRole('textbox', { name: 'Shares for bob' }), { target: { value: '4' } })+ expect(screen.getByText('216,67 €')).toBeInTheDocument()+ expect(screen.getByText('173,33 €')).toBeInTheDocument()++ fireEvent.click(submit())+ await waitFor(() => expect(addBudgetItem).toHaveBeenCalledTimes(1))+ expect(addBudgetItem.mock.calls[0][1]).toMatchObject({+ members: [{ user_id: 1, amount: 216.67 }, { user_id: 2, amount: 173.33 }],+ })+ })++ it('FE-MOB-COSTSH-040: the custom split also takes percentages, the amount shown beside each', () => {+ renderSheet()+ fillBasics('Bag storage', '30')+ fireEvent.click(screen.getByRole('button', { name: 'Custom' }))+ fireEvent.click(screen.getByRole('radio', { name: '%' }))+ expect(screen.getByText("Type each person's share in percent; together they have to make 100 %.")).toBeInTheDocument()+ fireEvent.change(screen.getByRole('textbox', { name: 'You %' }), { target: { value: '60' } })+ fireEvent.change(screen.getByRole('textbox', { name: 'bob %' }), { target: { value: '40' } })+ expect(screen.getByText('18,00 €')).toBeInTheDocument()+ expect(submit()).toBeEnabled()+ })})diff --git a/shared/src/i18n/ar/budget.ts b/shared/src/i18n/ar/budget.tsindex 33b463b5b..c47da2231 100644--- a/shared/src/i18n/ar/budget.ts+++ b/shared/src/i18n/ar/budget.ts@@ -197,6 +197,11 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'أدخل حصة كل شخص بالنسبة المئوية؛ يجب أن يكون مجموعها 100 %.','costs.splitUnit': 'إدخال الحصص كـ','costs.splitPercentOff': 'تم توزيع {sum} % من 100 %',+ 'costs.splitUnitShares': 'الحصص',+ 'costs.splitHint.shares':+ 'أعطِ كل شخص عددًا من الحصص، مثل عدد الليالي التي أقامها؛ ويُقسَّم المبلغ الإجمالي بهذه النسبة.',+ 'costs.splitSharesOf': 'حصص {name}',+ 'costs.splitSharesNone': 'أعطِ حصة لشخص واحد على الأقل','costs.splitHint.ticket': 'اكتب ما ورد في الإيصال وحدّد من أخذ كل عنصر.','costs.filter.allCategories': 'كل الفئات','costs.filter.allDays': 'كل الأيام',diff --git a/shared/src/i18n/az/budget.ts b/shared/src/i18n/az/budget.tsindex 06383ad9a..a12c453a2 100644--- a/shared/src/i18n/az/budget.ts+++ b/shared/src/i18n/az/budget.ts@@ -159,6 +159,11 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Hər kəsin payını faizlə yazın; cəmi 100 % olmalıdır.','costs.splitUnit': 'Payları belə daxil et','costs.splitPercentOff': '100 %-dən {sum} % bölüşdürülüb',+ 'costs.splitUnitShares': 'Paylar',+ 'costs.splitHint.shares':+ 'Hər kəsə pay sayı verin, məsələn qaldığı gecələrin sayı; ümumi məbləğ bu nisbətdə bölünür.',+ 'costs.splitSharesOf': '{name} üçün paylar',+ 'costs.splitSharesNone': 'Ən azı bir nəfərə pay verin','costs.splitHint.ticket': 'Qəbzdə olanları sadalayın və hər elementi kimin götürdüyünü işarələyin.','costs.pickSomeone': 'Bölüşdürmək üçün ən azı bir nəfər seçin.','costs.splitSummary': '{count} nəfər arasında bölünüb · hərəsinə {amount}',diff --git a/shared/src/i18n/br/budget.ts b/shared/src/i18n/br/budget.tsindex ed66b67fb..30c5284f6 100644--- a/shared/src/i18n/br/budget.ts+++ b/shared/src/i18n/br/budget.ts@@ -169,6 +169,11 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Digite a parte de cada pessoa em porcentagem; juntas devem somar 100 %.','costs.splitUnit': 'Inserir partes como','costs.splitPercentOff': '{sum} % de 100 % distribuídos',+ 'costs.splitUnitShares': 'Cotas',+ 'costs.splitHint.shares':+ 'Dê a cada pessoa um número de cotas, como as noites em que ficou; o total é dividido nessa proporção.',+ 'costs.splitSharesOf': 'Cotas de {name}',+ 'costs.splitSharesNone': 'Dê uma cota a pelo menos uma pessoa','costs.splitHint.ticket': 'Liste o que estava no comprovante e marque quem consumiu cada item.','costs.filter.allCategories': 'Todas as categorias','costs.filter.allDays': 'Todos os dias',diff --git a/shared/src/i18n/ca/budget.ts b/shared/src/i18n/ca/budget.tsindex ca5cce968..f191dc21a 100644--- a/shared/src/i18n/ca/budget.ts+++ b/shared/src/i18n/ca/budget.ts@@ -134,6 +134,11 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Escriu la part de cada persona en percentatge; juntes han de sumar el 100 %.','costs.splitUnit': 'Introdueix les parts com a','costs.splitPercentOff': '{sum} % de 100 % repartit',+ 'costs.splitUnitShares': 'Parts',+ 'costs.splitHint.shares':+ 'Dona a cada persona un nombre de parts, com ara les nits que s’hi ha allotjat; el total es reparteix en aquesta proporció.',+ 'costs.splitSharesOf': 'Parts de {name}',+ 'costs.splitSharesNone': 'Dona una part a almenys una persona','costs.splitHint.ticket': 'Llista el que hi havia al rebut i marca qui ha pres cada article.','costs.pickSomeone': 'Tria almenys una persona amb qui dividir-ho.','costs.splitSummary': 'Dividit entre {count} persones · {amount} cadascú',diff --git a/shared/src/i18n/cs/budget.ts b/shared/src/i18n/cs/budget.tsindex 9a70a07e0..e5aeb8b09 100644--- a/shared/src/i18n/cs/budget.ts+++ b/shared/src/i18n/cs/budget.ts@@ -176,6 +176,11 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Zadejte podíl každé osoby v procentech; dohromady musí dát 100 %.','costs.splitUnit': 'Zadávat podíly jako','costs.splitPercentOff': 'Rozděleno {sum} % ze 100 %',+ 'costs.splitUnitShares': 'Podíly',+ 'costs.splitHint.shares':+ 'Dejte každé osobě počet podílů, třeba podle počtu nocí; celková částka se rozdělí v tomto poměru.',+ 'costs.splitSharesOf': 'Podíly pro {name}',+ 'costs.splitSharesNone': 'Dejte podíl alespoň jedné osobě','costs.splitHint.ticket': 'Vypište, co bylo na účtence, a zaškrtněte, kdo měl kterou položku.','costs.filter.allCategories': 'Všechny kategorie','costs.filter.allDays': 'Všechny dny',diff --git a/shared/src/i18n/de/budget.ts b/shared/src/i18n/de/budget.tsindex ed455ccfc..b485a16eb 100644--- a/shared/src/i18n/de/budget.ts+++ b/shared/src/i18n/de/budget.ts@@ -173,6 +173,11 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Gib den Anteil jeder Person in Prozent ein; zusammen müssen es 100 % sein.','costs.splitUnit': 'Anteile eingeben als','costs.splitPercentOff': '{sum} % von 100 % verteilt',+ 'costs.splitUnitShares': 'Anteile',+ 'costs.splitHint.shares':+ 'Gib jeder Person eine Zahl von Anteilen, etwa die Nächte, die sie geblieben ist; der Betrag wird in diesem Verhältnis aufgeteilt.',+ 'costs.splitSharesOf': 'Anteile von {name}',+ 'costs.splitSharesNone': 'Gib mindestens einer Person einen Anteil','costs.splitHint.ticket': 'Liste auf, was auf dem Beleg steht, und hak ab, wer was hatte.','costs.ticketItemName': 'Artikelname','costs.ticketSplitting': 'Aufteilen auf:',diff --git a/shared/src/i18n/en/budget.ts b/shared/src/i18n/en/budget.tsindex 4bc664664..f627c5b9c 100644--- a/shared/src/i18n/en/budget.ts+++ b/shared/src/i18n/en/budget.ts@@ -143,6 +143,11 @@ const budget: TranslationStrings = {'costs.splitHint.percent': "Type each person's share in percent; together they have to make 100 %.",'costs.splitUnit': 'Enter shares as','costs.splitPercentOff': '{sum} % of 100 % assigned',+ 'costs.splitUnitShares': 'Shares',+ 'costs.splitHint.shares':+ 'Give each person a number of shares, such as the nights they stayed; the total is split in that ratio.',+ 'costs.splitSharesOf': 'Shares for {name}',+ 'costs.splitSharesNone': 'Give at least one person a share','costs.splitHint.ticket': 'List what was on the receipt and tick who had each item.','costs.pickSomeone': 'Pick at least one person to split with.','costs.splitSummary': 'Split {count} ways · {amount} each',diff --git a/shared/src/i18n/es/budget.ts b/shared/src/i18n/es/budget.tsindex 027c04c94..265493535 100644--- a/shared/src/i18n/es/budget.ts+++ b/shared/src/i18n/es/budget.ts@@ -169,6 +169,11 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Escribe la parte de cada persona en porcentaje; juntas deben sumar el 100 %.','costs.splitUnit': 'Introducir partes como','costs.splitPercentOff': '{sum} % de 100 % asignado',+ 'costs.splitUnitShares': 'Partes',+ 'costs.splitHint.shares':+ 'Da a cada persona un número de partes, como las noches que se alojó; el total se reparte en esa proporción.',+ 'costs.splitSharesOf': 'Partes de {name}',+ 'costs.splitSharesNone': 'Da una parte al menos a una persona','costs.splitHint.ticket': 'Enumera lo que había en el recibo y marca quién tomó cada artículo.','costs.filter.allCategories': 'Todas las categorías','costs.filter.allDays': 'Todos los días',diff --git a/shared/src/i18n/et/budget.ts b/shared/src/i18n/et/budget.tsindex f52831b91..b69c6a3e5 100644--- a/shared/src/i18n/et/budget.ts+++ b/shared/src/i18n/et/budget.ts@@ -143,6 +143,11 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Sisesta iga inimese osa protsentides; kokku peab tulema 100 %.','costs.splitUnit': 'Sisesta osad kui','costs.splitPercentOff': 'Jaotatud {sum} % 100 %-st',+ 'costs.splitUnitShares': 'Osad',+ 'costs.splitHint.shares':+ 'Anna igale inimesele osade arv, näiteks ööbitud ööde arv; summa jagatakse selles vahekorras.',+ 'costs.splitSharesOf': '{name} osad',+ 'costs.splitSharesNone': 'Anna vähemalt ühele inimesele osa','costs.splitHint.ticket': 'Loetle, mis tšekil oli, ja märgi iga kirje juurde, kellele see kuulus.','costs.pickSomeone': 'Vali jagamiseks vähemalt üks inimene.','costs.splitSummary': 'Jaotatud {count} osaks · igaühele {amount}',diff --git a/shared/src/i18n/fr/budget.ts b/shared/src/i18n/fr/budget.tsindex a35d5cb64..bcefbd517 100644--- a/shared/src/i18n/fr/budget.ts+++ b/shared/src/i18n/fr/budget.ts@@ -170,6 +170,11 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Saisissez la part de chacun en pourcentage ; ensemble elles doivent faire 100 %.','costs.splitUnit': 'Saisir les parts en','costs.splitPercentOff': '{sum} % sur 100 % répartis',+ 'costs.splitUnitShares': 'Parts',+ 'costs.splitHint.shares':+ 'Donnez à chaque personne un nombre de parts, par exemple ses nuits sur place ; le total est réparti dans cette proportion.',+ 'costs.splitSharesOf': 'Parts de {name}',+ 'costs.splitSharesNone': 'Donnez une part à au moins une personne','costs.splitHint.ticket': 'Listez ce qui figurait sur le reçu et cochez qui a pris chaque article.','costs.filter.allCategories': 'Toutes les catégories','costs.filter.allDays': 'Tous les jours',diff --git a/shared/src/i18n/gr/budget.ts b/shared/src/i18n/gr/budget.tsindex 39785dcec..14e4c6fa4 100644--- a/shared/src/i18n/gr/budget.ts+++ b/shared/src/i18n/gr/budget.ts@@ -171,6 +171,11 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Πληκτρολογήστε το μερίδιο κάθε ατόμου σε ποσοστό· μαζί πρέπει να κάνουν 100 %.','costs.splitUnit': 'Εισαγωγή μεριδίων ως','costs.splitPercentOff': 'Κατανεμήθηκε {sum} % από 100 %',+ 'costs.splitUnitShares': 'Μερίδια',+ 'costs.splitHint.shares':+ 'Δώστε σε κάθε άτομο έναν αριθμό μεριδίων, όπως τις νύχτες που έμεινε· το σύνολο μοιράζεται με αυτή την αναλογία.',+ 'costs.splitSharesOf': 'Μερίδια για {name}',+ 'costs.splitSharesNone': 'Δώστε μερίδιο σε τουλάχιστον ένα άτομο','costs.splitHint.ticket': 'Καταγράψτε τι είχε η απόδειξη και σημειώστε ποιος πήρε κάθε είδος.','costs.filter.allCategories': 'Όλες οι κατηγορίες','costs.filter.allDays': 'Όλες οι ημέρες',diff --git a/shared/src/i18n/he/budget.ts b/shared/src/i18n/he/budget.tsindex 17f863df4..d66e2b1cf 100644--- a/shared/src/i18n/he/budget.ts+++ b/shared/src/i18n/he/budget.ts@@ -148,6 +148,10 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'הקלידו את החלק של כל אדם באחוזים; ביחד הם צריכים להגיע ל-100%.','costs.splitUnit': 'הזנת חלקים כ-','costs.splitPercentOff': '{sum}% מתוך 100% חולקו',+ 'costs.splitUnitShares': 'חלקים',+ 'costs.splitHint.shares': 'תנו לכל אדם מספר חלקים, למשל מספר הלילות שנשאר; הסכום הכולל מתחלק ביחס הזה.',+ 'costs.splitSharesOf': 'החלקים של {name}',+ 'costs.splitSharesNone': 'תנו חלק לאדם אחד לפחות','costs.splitHint.ticket': 'רשמו מה היה בקבלה וסמנו מי לקח כל פריט.','costs.pickSomeone': 'בחרו לפחות אדם אחד לחלוקה.','costs.splitSummary': 'חלוקה ל-{count} · {amount} לכל אחד',diff --git a/shared/src/i18n/hu/budget.ts b/shared/src/i18n/hu/budget.tsindex d121ad967..b5ce34af3 100644--- a/shared/src/i18n/hu/budget.ts+++ b/shared/src/i18n/hu/budget.ts@@ -171,6 +171,11 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Add meg mindenki részét százalékban; együtt 100 %-ot kell kiadniuk.','costs.splitUnit': 'Részek megadása mint','costs.splitPercentOff': '100 %-ból {sum} % kiosztva',+ 'costs.splitUnitShares': 'Részek',+ 'costs.splitHint.shares':+ 'Adj mindenkinek egy részszámot, például az eltöltött éjszakák számát; a végösszeg ebben az arányban oszlik meg.',+ 'costs.splitSharesOf': '{name} részei',+ 'costs.splitSharesNone': 'Adj részt legalább egy személynek','costs.splitHint.ticket': 'Sorold fel, mi szerepelt a nyugtán, és minden tételnél jelöld be, kié volt.','costs.filter.allCategories': 'Összes kategória','costs.filter.allDays': 'Összes nap',diff --git a/shared/src/i18n/id/budget.ts b/shared/src/i18n/id/budget.tsindex 339897b34..f21c5744e 100644--- a/shared/src/i18n/id/budget.ts+++ b/shared/src/i18n/id/budget.ts@@ -162,6 +162,11 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Ketik bagian tiap orang dalam persen; jumlahnya harus 100 %.','costs.splitUnit': 'Masukkan bagian sebagai','costs.splitPercentOff': '{sum} % dari 100 % terbagi',+ 'costs.splitUnitShares': 'Bagian',+ 'costs.splitHint.shares':+ 'Beri setiap orang sejumlah bagian, misalnya jumlah malam menginap; total dibagi menurut perbandingan itu.',+ 'costs.splitSharesOf': 'Bagian untuk {name}',+ 'costs.splitSharesNone': 'Beri bagian kepada setidaknya satu orang','costs.splitHint.ticket': 'Tuliskan isi kuitansi dan centang siapa yang mengambil tiap item.','costs.filter.allCategories': 'Semua kategori','costs.filter.allDays': 'Semua hari',diff --git a/shared/src/i18n/it/budget.ts b/shared/src/i18n/it/budget.tsindex 77d2cbf9e..601f8f3bc 100644--- a/shared/src/i18n/it/budget.ts+++ b/shared/src/i18n/it/budget.ts@@ -169,6 +169,11 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Inserisci la quota di ciascuno in percentuale; insieme devono fare 100 %.','costs.splitUnit': 'Inserisci le quote come','costs.splitPercentOff': '{sum} % di 100 % assegnato',+ 'costs.splitUnitShares': 'Quote',+ 'costs.splitHint.shares':+ 'Assegna a ogni persona un numero di quote, ad esempio le notti in cui è rimasta; il totale viene diviso in questa proporzione.',+ 'costs.splitSharesOf': 'Quote di {name}',+ 'costs.splitSharesNone': 'Assegna una quota ad almeno una persona','costs.splitHint.ticket': "Elenca cosa c'era sulla ricevuta e spunta chi ha preso ciascun articolo.",'costs.filter.allCategories': 'Tutte le categorie','costs.filter.allDays': 'Tutti i giorni',diff --git a/shared/src/i18n/ja/budget.ts b/shared/src/i18n/ja/budget.tsindex 179b2114b..2991492d6 100644--- a/shared/src/i18n/ja/budget.ts+++ b/shared/src/i18n/ja/budget.ts@@ -162,6 +162,10 @@ const budget: TranslationStrings = {'costs.splitHint.percent': '各人の負担をパーセントで入力してください。合計で 100 % になる必要があります。','costs.splitUnit': '負担の入力方法','costs.splitPercentOff': '100 % のうち {sum} % を割り当て済み',+ 'costs.splitUnitShares': '口数',+ 'costs.splitHint.shares': '泊数など、各メンバーに口数を指定してください。合計金額はその比率で分けられます。',+ 'costs.splitSharesOf': '{name}の口数',+ 'costs.splitSharesNone': '少なくとも1人に口数を指定してください','costs.splitHint.ticket': 'レシートの品目を書き出し、それぞれ誰の分かにチェックを入れます。','costs.filter.allCategories': 'すべてのカテゴリー','costs.filter.allDays': 'すべての日',diff --git a/shared/src/i18n/ko/budget.ts b/shared/src/i18n/ko/budget.tsindex 0a83f7ea0..4df7929af 100644--- a/shared/src/i18n/ko/budget.ts+++ b/shared/src/i18n/ko/budget.ts@@ -162,6 +162,10 @@ const budget: TranslationStrings = {'costs.splitHint.percent': '각자의 몫을 퍼센트로 입력하세요. 합계가 100 %가 되어야 합니다.','costs.splitUnit': '몫 입력 방식','costs.splitPercentOff': '100 % 중 {sum} % 배분됨',+ 'costs.splitUnitShares': '지분',+ 'costs.splitHint.shares': '머문 박 수처럼 각자에게 지분 수를 정하세요. 총액이 그 비율로 나뉩니다.',+ 'costs.splitSharesOf': '{name}의 지분',+ 'costs.splitSharesNone': '최소 한 명에게 지분을 정하세요','costs.splitHint.ticket': '영수증에 있던 항목을 적고, 항목마다 누구 몫인지 체크하세요.','costs.filter.allCategories': '모든 카테고리','costs.filter.allDays': '모든 날짜',diff --git a/shared/src/i18n/nl/budget.ts b/shared/src/i18n/nl/budget.tsindex 464375b33..56e025c57 100644--- a/shared/src/i18n/nl/budget.ts+++ b/shared/src/i18n/nl/budget.ts@@ -170,6 +170,11 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Vul ieders aandeel in procenten in; samen moet het 100 % zijn.','costs.splitUnit': 'Aandelen invoeren als','costs.splitPercentOff': '{sum} % van 100 % verdeeld',+ 'costs.splitUnitShares': 'Delen',+ 'costs.splitHint.shares':+ 'Geef iedereen een aantal delen, zoals het aantal overnachtingen; het totaal wordt in die verhouding verdeeld.',+ 'costs.splitSharesOf': 'Delen voor {name}',+ 'costs.splitSharesNone': 'Geef ten minste één persoon een deel','costs.splitHint.ticket': 'Zet op een rij wat er op de bon stond en vink aan wie welk item had.','costs.filter.allCategories': 'Alle categorieën','costs.filter.allDays': 'Alle dagen',diff --git a/shared/src/i18n/pl/budget.ts b/shared/src/i18n/pl/budget.tsindex db8a780d0..2951fe741 100644--- a/shared/src/i18n/pl/budget.ts+++ b/shared/src/i18n/pl/budget.ts@@ -183,6 +183,11 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Wpisz udział każdej osoby w procentach; razem musi to dać 100 %.','costs.splitUnit': 'Wpisuj udziały jako','costs.splitPercentOff': 'Przydzielono {sum} % ze 100 %',+ 'costs.splitUnitShares': 'Udziały',+ 'costs.splitHint.shares':+ 'Przypisz każdej osobie liczbę udziałów, np. liczbę nocy; kwota zostanie podzielona w tej proporcji.',+ 'costs.splitSharesOf': 'Udziały: {name}',+ 'costs.splitSharesNone': 'Przypisz udział co najmniej jednej osobie','costs.splitHint.ticket': 'Wypisz, co było na paragonie, i zaznacz, kto miał którą pozycję.','costs.filter.allCategories': 'Wszystkie kategorie','costs.filter.allDays': 'Wszystkie dni',diff --git a/shared/src/i18n/ru/budget.ts b/shared/src/i18n/ru/budget.tsindex c569c05bb..eb741f011 100644--- a/shared/src/i18n/ru/budget.ts+++ b/shared/src/i18n/ru/budget.ts@@ -183,6 +183,10 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Введите долю каждого в процентах; вместе должно получиться 100 %.','costs.splitUnit': 'Вводить доли как','costs.splitPercentOff': 'Распределено {sum} % из 100 %',+ 'costs.splitUnitShares': 'Доли',+ 'costs.splitHint.shares': 'Укажите каждому число долей, например число ночей; сумма делится в этой пропорции.',+ 'costs.splitSharesOf': 'Доли: {name}',+ 'costs.splitSharesNone': 'Укажите долю хотя бы одному человеку','costs.splitHint.ticket': 'Перечислите, что было в чеке, и отметьте, кто что брал.','costs.filter.allCategories': 'Все категории','costs.filter.allDays': 'Все дни',diff --git a/shared/src/i18n/sk/budget.ts b/shared/src/i18n/sk/budget.tsindex dad424480..6c44099ec 100644--- a/shared/src/i18n/sk/budget.ts+++ b/shared/src/i18n/sk/budget.ts@@ -148,6 +148,11 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Zadajte podiel každej osoby v percentách; spolu musia dať 100 %.','costs.splitUnit': 'Zadávať podiely ako','costs.splitPercentOff': 'Rozdelené {sum} % zo 100 %',+ 'costs.splitUnitShares': 'Podiely',+ 'costs.splitHint.shares':+ 'Dajte každej osobe počet podielov, napríklad podľa počtu nocí; celková suma sa rozdelí v tomto pomere.',+ 'costs.splitSharesOf': 'Podiely pre {name}',+ 'costs.splitSharesNone': 'Dajte podiel aspoň jednej osobe','costs.splitHint.ticket': 'Vypíšte, čo bolo na účtenke, a označte, kto mal ktorú položku.','costs.pickSomeone': 'Vyberte aspoň jednu osobu na rozdelenie.','costs.splitSummary': 'Rozdelené na {count} dielov · {amount} na osobu',diff --git a/shared/src/i18n/sv/budget.ts b/shared/src/i18n/sv/budget.tsindex 0b195d0b0..59a8cf7c3 100644--- a/shared/src/i18n/sv/budget.ts+++ b/shared/src/i18n/sv/budget.ts@@ -169,6 +169,11 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Skriv varje persons andel i procent; tillsammans ska det bli 100 %.','costs.splitUnit': 'Ange andelar som','costs.splitPercentOff': '{sum} % av 100 % fördelat',+ 'costs.splitUnitShares': 'Andelar',+ 'costs.splitHint.shares':+ 'Ge varje person ett antal andelar, till exempel antal nätter; summan delas i den proportionen.',+ 'costs.splitSharesOf': 'Andelar för {name}',+ 'costs.splitSharesNone': 'Ge minst en person en andel','costs.splitHint.ticket': 'Lista det som stod på kvittot och bocka för vem som hade varje artikel.','costs.filter.allCategories': 'Alla kategorier','costs.filter.allDays': 'Alla dagar',diff --git a/shared/src/i18n/th/budget.ts b/shared/src/i18n/th/budget.tsindex d7f7e4af1..55cf08b57 100644--- a/shared/src/i18n/th/budget.ts+++ b/shared/src/i18n/th/budget.ts@@ -134,6 +134,10 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'ใส่ส่วนแบ่งของแต่ละคนเป็นเปอร์เซ็นต์ รวมกันต้องได้ 100 %','costs.splitUnit': 'ใส่ส่วนแบ่งเป็น','costs.splitPercentOff': 'แบ่งแล้ว {sum} % จาก 100 %',+ 'costs.splitUnitShares': 'ส่วนแบ่ง',+ 'costs.splitHint.shares': 'กำหนดจำนวนส่วนแบ่งให้แต่ละคน เช่น จำนวนคืนที่พัก แล้วยอดรวมจะถูกแบ่งตามสัดส่วนนั้น',+ 'costs.splitSharesOf': 'ส่วนแบ่งของ {name}',+ 'costs.splitSharesNone': 'กำหนดส่วนแบ่งให้อย่างน้อยหนึ่งคน','costs.splitHint.ticket': 'ใส่รายการที่อยู่ในใบเสร็จ แล้วติ๊กว่าใครสั่งรายการไหน','costs.pickSomeone': 'เลือกอย่างน้อยหนึ่งคนที่จะแยกด้วย','costs.splitSummary': '{count} คน · คนละ {amount}',diff --git a/shared/src/i18n/tr/budget.ts b/shared/src/i18n/tr/budget.tsindex 900f03bd5..8447b5fbc 100644--- a/shared/src/i18n/tr/budget.ts+++ b/shared/src/i18n/tr/budget.ts@@ -170,6 +170,10 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Herkesin payını yüzde olarak yazın; toplam %100 olmalı.','costs.splitUnit': 'Payları şu şekilde gir','costs.splitPercentOff': "%100'ün %{sum} kadarı dağıtıldı",+ 'costs.splitUnitShares': 'Paylar',+ 'costs.splitHint.shares': 'Herkese bir pay sayısı verin, örneğin kaldığı gece sayısı; toplam bu oranda bölünür.',+ 'costs.splitSharesOf': '{name} payları',+ 'costs.splitSharesNone': 'En az bir kişiye pay verin','costs.splitHint.ticket': 'Fişte neler olduğunu listeleyin ve her kalemi kimin aldığını işaretleyin.','costs.filter.allCategories': 'Tüm kategoriler','costs.filter.allDays': 'Tüm günler',diff --git a/shared/src/i18n/uk/budget.ts b/shared/src/i18n/uk/budget.tsindex b5b9a25b8..62ade0c09 100644--- a/shared/src/i18n/uk/budget.ts+++ b/shared/src/i18n/uk/budget.ts@@ -183,6 +183,11 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Введіть частку кожного у відсотках; разом має бути 100 %.','costs.splitUnit': 'Вводити частки як','costs.splitPercentOff': 'Розподілено {sum} % зі 100 %',+ 'costs.splitUnitShares': 'Частки',+ 'costs.splitHint.shares':+ 'Вкажіть кожному кількість часток, наприклад кількість ночей; сума ділиться в цій пропорції.',+ 'costs.splitSharesOf': 'Частки: {name}',+ 'costs.splitSharesNone': 'Вкажіть частку хоча б одній людині','costs.splitHint.ticket': 'Перелічіть, що було в чеку, і позначте, хто брав кожну позицію.','costs.filter.allCategories': 'Усі категорії','costs.filter.allDays': 'Усі дні',diff --git a/shared/src/i18n/vi/budget.ts b/shared/src/i18n/vi/budget.tsindex 8c485453f..83f470949 100644--- a/shared/src/i18n/vi/budget.ts+++ b/shared/src/i18n/vi/budget.ts@@ -162,6 +162,10 @@ const budget: TranslationStrings = {'costs.splitHint.percent': 'Nhập phần của mỗi người theo phần trăm; tổng cộng phải là 100 %.','costs.splitUnit': 'Nhập phần theo','costs.splitPercentOff': 'Đã chia {sum} % trên 100 %',+ 'costs.splitUnitShares': 'Phần',+ 'costs.splitHint.shares': 'Đặt cho mỗi người một số phần, ví dụ số đêm đã ở; tổng tiền được chia theo tỷ lệ đó.',+ 'costs.splitSharesOf': 'Số phần của {name}',+ 'costs.splitSharesNone': 'Hãy đặt phần cho ít nhất một người','costs.splitHint.ticket': 'Liệt kê các món trên hóa đơn và đánh dấu ai đã dùng từng món.','costs.filter.allCategories': 'Tất cả danh mục','costs.filter.allDays': 'Tất cả các ngày',diff --git a/shared/src/i18n/zh-TW/budget.ts b/shared/src/i18n/zh-TW/budget.tsindex 4a29df568..8eb587eb0 100644--- a/shared/src/i18n/zh-TW/budget.ts+++ b/shared/src/i18n/zh-TW/budget.ts@@ -161,6 +161,10 @@ const budget: TranslationStrings = {'costs.splitHint.percent': '以百分比輸入每個人的份額,合計必須為 100 %。','costs.splitUnit': '份額輸入方式','costs.splitPercentOff': '已分配 {sum} %(共 100 %)',+ 'costs.splitUnitShares': '份數',+ 'costs.splitHint.shares': '為每個人設定份數,例如住了幾晚;總額按此比例分攤。',+ 'costs.splitSharesOf': '{name} 的份數',+ 'costs.splitSharesNone': '請至少為一人設定份數','costs.splitHint.ticket': '列出收據上的項目,並勾選每一項是誰的。','costs.filter.allCategories': '所有類別','costs.filter.allDays': '所有日期',diff --git a/shared/src/i18n/zh/budget.ts b/shared/src/i18n/zh/budget.tsindex 5026a19d3..a8da96b9f 100644--- a/shared/src/i18n/zh/budget.ts+++ b/shared/src/i18n/zh/budget.ts@@ -161,6 +161,10 @@ const budget: TranslationStrings = {'costs.splitHint.percent': '以百分比输入每个人的份额,合计必须为 100 %。','costs.splitUnit': '份额输入方式','costs.splitPercentOff': '已分配 {sum} %(共 100 %)',+ 'costs.splitUnitShares': '份数',+ 'costs.splitHint.shares': '为每个人设定份数,例如住了几晚;总额按此比例分摊。',+ 'costs.splitSharesOf': '{name} 的份数',+ 'costs.splitSharesNone': '请至少为一人设定份数','costs.splitHint.ticket': '列出收据上的项目,并勾选每一项是谁的。','costs.filter.allCategories': '所有类别','costs.filter.allDays': '所有日期',diff --git a/wiki/Budget-Tracking.md b/wiki/Budget-Tracking.mdindex c3e08dd31..114d9da12 100644--- a/wiki/Budget-Tracking.md+++ b/wiki/Budget-Tracking.md@@ -137,7 +137,7 @@ An expense with no payer is flagged **Unfinished** on its row and counted into t**Split** decides who owes for the expense. The switch beside the heading has three modes, and a line under it says what the current one does. Every member is listed with a box to tick; an unticked member owes nothing.- **Equally**: everyone ticked pays the same share, shown beside each name, with the head count and *{amount} per person* under the list. Remainder cents from rounding are handed out deterministically and rotated by the expense, so over a trip nobody is always the one who pays the extra cent.-- **Custom**: type each person's share. Together they have to make the total: under the list, a green *Split matches total* or a red *Sum of splits: … (under by …)* / *(over by …)* says where you stand, and the dialog will not save until it matches. A small switch next to the hint (**Enter shares as**) picks between the currency symbol and **%**. In percent, each person gets a percentage instead, they have to add up to 100 % (a red *… % of 100 % assigned* says when they do not), and TREK turns them into amounts that add up to the total exactly.+- **Custom**: type each person's share. Together they have to make the total: under the list, a green *Split matches total* or a red *Sum of splits: … (under by …)* / *(over by …)* says where you stand, and the dialog will not save until it matches. A small switch next to the hint (**Enter shares as**) picks between the currency symbol, **%** and **Shares**. In percent, each person gets a percentage instead, they have to add up to 100 % (a red *… % of 100 % assigned* says when they do not), and TREK turns them into amounts that add up to the total exactly. With **Shares**, each person gets a number of shares, such as the nights they stayed: everyone starts at one, and an apartment of 390 € for five nights against four comes to 216,67 € and 173,33 €. A person on zero shares owes nothing, and with nobody on a share the dialog says *Give at least one person a share*. What is saved is the amounts, so the expense reopens with them. The phone sheet has the same switch under the split modes.- **Ticket**: list what was on the receipt. Each line has an **Item name**, a price and, under *Splitting:*, a chip per member to tick who had it. **Add item** adds a line, the bin removes one. The total is summed from the lines, **Individual shares** shows what each person comes to, cent-exact, and the lines are kept, so the list is still there the next time you open the expense.## Settlement calculator