diff --git a/frontend/src/api/splitwiseImport.ts b/frontend/src/api/splitwiseImport.ts new file mode 100644 index 0000000..d3cf089 --- /dev/null +++ b/frontend/src/api/splitwiseImport.ts @@ -0,0 +1,27 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query' +import { apiRequest } from './client' +import { invalidateAfterChange } from './ledger' +import type { SplitwiseImportPreview, SplitwiseImportSummary } from './types' + +function importPath(userId: number) { + return `/api/contacts/${userId}/import/splitwise` +} + +export function useSplitwiseImportPreview(userId: number) { + return useMutation({ + mutationFn: (csv: string) => + apiRequest(`${importPath(userId)}/preview`, { + method: 'POST', + body: { csv }, + }), + }) +} + +export function useSplitwiseImport(userId: number) { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (input: { csv: string; ownColumn: 0 | 1 }) => + apiRequest(importPath(userId), { method: 'POST', body: input }), + onSuccess: () => invalidateAfterChange(queryClient), + }) +} diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index 27a54ef..7589b17 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -184,6 +184,23 @@ export type ContactListResponse = { items: ContactListItem[] } +export type SplitwiseImportSummary = { + expenses: number + transfers: number + skipped: number + /** The pair's PLN balance after the import; positive = the contact owes the user. */ + balance: string +} + +export type SplitwiseImportPreview = { + /** The file's two people, in column order. */ + names: [string, string] + /** How far the file's PLN rows are off its own PLN total; null when they agree. */ + mismatch: string | null + /** What importing does if the user is the first or the second person in the file. */ + options: [SplitwiseImportSummary, SplitwiseImportSummary] +} + export type ApiViolation = { propertyPath: string title: string diff --git a/frontend/src/features/contacts/EditContactPage.tsx b/frontend/src/features/contacts/EditContactPage.tsx index 74fcfe3..0f699b7 100644 --- a/frontend/src/features/contacts/EditContactPage.tsx +++ b/frontend/src/features/contacts/EditContactPage.tsx @@ -22,6 +22,7 @@ import { useGoBack } from '@/lib/useGoBack' import { cn } from '@/lib/utils' import { ContactNotFound } from './ContactNotFound' import { parseIdParam } from '@/lib/parseIdParam' +import { SplitwiseImport } from './SplitwiseImport' const editContactSchema = z.object({ nickname: z @@ -178,6 +179,10 @@ function EditContactForm({ contact }: { contact: ContactListItem }) { Save + +
+ +
) } diff --git a/frontend/src/features/contacts/SplitwiseImport.test.tsx b/frontend/src/features/contacts/SplitwiseImport.test.tsx new file mode 100644 index 0000000..1ad7ebf --- /dev/null +++ b/frontend/src/features/contacts/SplitwiseImport.test.tsx @@ -0,0 +1,158 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import type { ContactListItem, SplitwiseImportPreview } from '@/api/types' +import { jsonResponse, renderRoutes } from '@/test/utils' +import { EditContactPage } from './EditContactPage' + +const ania: ContactListItem = { + person: { id: 2, displayName: 'Ania', email: 'anna@example.com' }, + nickname: 'Ania', + name: 'Anna Kowalska', + isRegistered: true, + balances: [], + lastActivityAt: '2026-10-20T12:00:00+00:00', +} + +const preview: SplitwiseImportPreview = { + names: ['Ame Nowak', 'Anna Kowalska'], + mismatch: null, + options: [ + { expenses: 137, transfers: 44, skipped: 6, balance: '9642.18' }, + { expenses: 3, transfers: 0, skipped: 184, balance: '-9642.18' }, + ], +} + +type Reply = { status: number; body: unknown } + +function stubApi( + previewReply: Reply = { status: 200, body: preview }, + importReply: Reply = { status: 200, body: preview.options[0] }, +) { + const fetchMock = vi.fn((input: string, init?: RequestInit) => { + if (init?.method === 'POST' && input.endsWith('/preview')) { + return Promise.resolve(jsonResponse(previewReply.status, previewReply.body)) + } + if (init?.method === 'POST') { + return Promise.resolve(jsonResponse(importReply.status, importReply.body)) + } + return Promise.resolve(jsonResponse(200, { totals: [], items: [ania] })) + }) + vi.stubGlobal('fetch', fetchMock) + return fetchMock +} + +function importCalls(fetchMock: ReturnType) { + return fetchMock.mock.calls + .filter(([input, init]) => init?.method === 'POST' && !input.endsWith('/preview')) + .map(([input, init]) => [input, JSON.parse(String(init?.body))]) +} + +async function chooseFile(content = 'csv text') { + renderRoutes( + [{ path: '/contacts/:userId/edit', element: }], + '/contacts/2/edit', + ) + await screen.findByRole('button', { name: 'Import from Splitwise' }) + await userEvent.upload( + screen.getByTestId('splitwise-file'), + new File([content], 'export.csv', { type: 'text/csv' }), + ) +} + +afterEach(() => { + vi.unstubAllGlobals() +}) + +describe('Splitwise import', () => { + it('waits for the user to pick their name, then imports as that person', async () => { + const fetchMock = stubApi() + await chooseFile() + + expect(await screen.findByText('Which one are you?')).toBeInTheDocument() + expect(screen.queryByRole('button', { name: 'Import' })).not.toBeInTheDocument() + + await userEvent.click(screen.getByLabelText('Ame Nowak')) + + expect( + screen.getByText(/137 expenses and 44 payments between Ame Nowak and Anna Kowalska\./), + ).toHaveTextContent(/6 skipped\. After import, Ania owes you/) + + await userEvent.click(screen.getByRole('button', { name: 'Import' })) + + expect(await screen.findByText('Imported 137 expenses and 44 payments')).toBeInTheDocument() + expect(importCalls(fetchMock)).toEqual([ + ['/api/contacts/2/import/splitwise', { csv: 'csv text', ownColumn: 0 }], + ]) + }) + + it('switching the name switches the summary', async () => { + stubApi() + await chooseFile() + + await userEvent.click(await screen.findByLabelText('Anna Kowalska')) + + expect(screen.getByText(/3 expenses and 0 payments/)).toHaveTextContent(/you owe Ania/) + }) + + it('clears a failed import when the other name is picked', async () => { + stubApi(undefined, { status: 500, body: {} }) + await chooseFile() + + await userEvent.click(await screen.findByLabelText('Ame Nowak')) + await userEvent.click(screen.getByRole('button', { name: 'Import' })) + expect(await screen.findByText('Couldn’t import. Nothing was added.')).toBeInTheDocument() + + await userEvent.click(screen.getByLabelText('Anna Kowalska')) + + expect(screen.queryByText('Couldn’t import. Nothing was added.')).not.toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Import' })).toBeInTheDocument() + }) + + it('offers Import anyway when the rows do not add up', async () => { + stubApi({ + status: 200, + body: { ...preview, mismatch: '-192.92' }, + }) + await chooseFile() + + await userEvent.click(await screen.findByLabelText('Ame Nowak')) + + expect(screen.getByText(/off by .*192\.92/)).toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Import anyway' })).toBeInTheDocument() + }) + + it('has no import button when everything is already imported', async () => { + stubApi({ + status: 200, + body: { + ...preview, + options: [preview.options[0], { expenses: 0, transfers: 0, skipped: 187, balance: '0.00' }], + }, + }) + await chooseFile() + + await userEvent.click(await screen.findByLabelText('Anna Kowalska')) + + expect(screen.getByText('Nothing new to import.')).toBeInTheDocument() + expect(screen.queryByRole('button', { name: /Import/ })).not.toBeInTheDocument() + }) + + it('says once when the file is not a Splitwise export', async () => { + stubApi({ status: 422, body: { status: 422, title: 'Unprocessable Entity' } }) + await chooseFile() + + expect( + await screen.findByText('This file isn’t a supported Splitwise export.'), + ).toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Choose another file' })).toBeInTheDocument() + }) + + it('offers a retry when the check request fails', async () => { + stubApi({ status: 500, body: {} }) + await chooseFile() + + expect(await screen.findByText('Couldn’t check the file.')).toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Try again' })).toBeInTheDocument() + }) +}) diff --git a/frontend/src/features/contacts/SplitwiseImport.tsx b/frontend/src/features/contacts/SplitwiseImport.tsx new file mode 100644 index 0000000..9388df0 --- /dev/null +++ b/frontend/src/features/contacts/SplitwiseImport.tsx @@ -0,0 +1,332 @@ +import { useRef, useState, type ChangeEvent, type ReactNode } from 'react' +import { plural, t as translate } from '@lingui/core/macro' +import { Trans, useLingui } from '@lingui/react/macro' +import { ChevronRight } from 'lucide-react' +import { toast } from 'sonner' +import { ApiError } from '@/api/client' +import { useSplitwiseImport, useSplitwiseImportPreview } from '@/api/splitwiseImport' +import type { ContactListItem, SplitwiseImportPreview, SplitwiseImportSummary } from '@/api/types' +import { PrimaryButton } from '@/components/PrimaryButton' +import { Spinner } from '@/components/Spinner' +import { Button } from '@/components/ui/button' +import { + Sheet, + SheetContent, + SheetDescription, + SheetFooter, + SheetHeader, + SheetTitle, +} from '@/components/ui/sheet' +import { balanceDirection, formatPln } from '@/lib/money' +import { getShortName } from '@/lib/person' +import { cn } from '@/lib/utils' + +// Matches the server's limit on the CSV text. +const MAX_FILE_BYTES = 1_048_576 + +type OwnColumn = 0 | 1 + +export function SplitwiseImport({ contact }: { contact: ContactListItem }) { + const { t } = useLingui() + const userId = contact.person.id + const inputRef = useRef(null) + const [open, setOpen] = useState(false) + const [csv, setCsv] = useState(null) + const [tooLarge, setTooLarge] = useState(false) + const [ownColumn, setOwnColumn] = useState(null) + const previewMutation = useSplitwiseImportPreview(userId) + const importMutation = useSplitwiseImport(userId) + + const chooseFile = () => inputRef.current?.click() + + const onFileChange = async (event: ChangeEvent) => { + const file = event.target.files?.[0] + event.target.value = '' + if (!file) { + return + } + + setOwnColumn(null) + previewMutation.reset() + importMutation.reset() + setOpen(true) + + if (file.size > MAX_FILE_BYTES) { + setCsv(null) + setTooLarge(true) + return + } + + setTooLarge(false) + const text = await file.text() + setCsv(text) + previewMutation.mutate(text) + } + + const runImport = () => { + if (csv === null || ownColumn === null) { + return + } + importMutation.mutate( + { csv, ownColumn }, + { + onSuccess: (summary) => { + const counts = countsText(summary) + toast.success(t`Imported ${counts}`) + setOpen(false) + }, + }, + ) + } + + const onOpenChange = (next: boolean) => { + if (!importMutation.isPending) { + setOpen(next) + } + } + + return ( + <> + + + + + + + + Import from Splitwise + + + {tooLarge ? ( + + + + ) : previewMutation.data ? ( + { + setOwnColumn(column) + importMutation.reset() + }} + importing={importMutation.isPending} + importFailed={importMutation.isError} + onImport={runImport} + onClose={() => setOpen(false)} + /> + ) : previewMutation.isError ? ( + isWrongFile(previewMutation.error) ? ( + + + + ) : ( + + csv !== null && previewMutation.mutate(csv)}> + Try again + + + ) + ) : ( + <> + + Checking the file + + + + )} + + + + ) +} + +function isWrongFile(error: Error) { + return error instanceof ApiError && (error.status === 422 || error.status === 400) +} + +function countsText(summary: SplitwiseImportSummary) { + const expenseCount = summary.expenses + const paymentCount = summary.transfers + const expenses = plural(expenseCount, { one: '# expense', other: '# expenses' }) + const payments = plural(paymentCount, { one: '# payment', other: '# payments' }) + return translate`${expenses} and ${payments}` +} + +function StatusBody({ message, children }: { message: string; children: ReactNode }) { + return ( + <> +
+ {message} +
+ {children} + + ) +} + +function ChooseAnotherButton({ onClick }: { onClick: () => void }) { + return ( + + Choose another file + + ) +} + +type SummaryBodyProps = { + contact: ContactListItem + preview: SplitwiseImportPreview + ownColumn: OwnColumn | null + onOwnColumnChange: (column: OwnColumn) => void + importing: boolean + importFailed: boolean + onImport: () => void + onClose: () => void +} + +function SummaryBody({ + contact, + preview, + ownColumn, + onOwnColumnChange, + importing, + importFailed, + onImport, + onClose, +}: SummaryBodyProps) { + const { t } = useLingui() + const summary = ownColumn === null ? null : preview.options[ownColumn] + const hasMismatch = preview.mismatch !== null + const offBy = preview.mismatch === null ? '' : formatPln(preview.mismatch) + + return ( + <> +
+ + Which one are you? + +
+ {preview.names.map((name, index) => ( + + ))} +
+
+ + {summary === null || ownColumn === null ? ( + + Choose which person in the file is you. + + ) : summary.expenses + summary.transfers === 0 ? ( + <> +
+ + Nothing new to import. + +
+ + + + + ) : ( + <> +
+ + + +
+ + {importFailed ? ( +

+ Couldn’t import. Nothing was added. +

+ ) : ( + hasMismatch && ( +

+ {t`The file’s rows don’t add up to its total (off by ${offBy}).`} +

+ ) + )} + + {importFailed ? ( + Try again + ) : hasMismatch ? ( + Import anyway + ) : ( + Import + )} + +
+ + )} + + ) +} + +function SummaryText({ + summary, + ownName, + otherName, + contactName, +}: { + summary: SplitwiseImportSummary + ownName: string + otherName: string + contactName: string +}) { + const { t } = useLingui() + const counts = countsText(summary) + const skippedCount = summary.skipped + const amount = formatPln(summary.balance) + const direction = balanceDirection(summary.balance) + const balanceText = + direction === 'owed' + ? t`After import, ${contactName} owes you ${amount}.` + : direction === 'owe' + ? t`After import, you owe ${contactName} ${amount}.` + : t`After import, you’re settled up.` + + return ( + <> + {t`${counts} between ${ownName} and ${otherName}.`}{' '} + {skippedCount > 0 && <>{plural(skippedCount, { other: '# skipped.' })} } + {balanceText} + + ) +} diff --git a/frontend/src/locales/en.po b/frontend/src/locales/en.po index e3d68f1..625156a 100644 --- a/frontend/src/locales/en.po +++ b/frontend/src/locales/en.po @@ -23,6 +23,10 @@ msgstr "{assignedNumber} of {totalAmount}" msgid "{assignedPercent}% of 100%" msgstr "{assignedPercent}% of 100%" +#: src/features/contacts/SplitwiseImport.tsx +msgid "{counts} between {ownName} and {otherName}." +msgstr "{counts} between {ownName} and {otherName}." + #: src/features/activity/ActivityRows.tsx msgid "{date} · {subline}" msgstr "{date} · {subline}" @@ -63,6 +67,14 @@ msgstr "{displayName} added to your contacts" msgid "{each} each" msgstr "{each} each" +#: src/features/contacts/SplitwiseImport.tsx +msgid "{expenseCount, plural, one {# expense} other {# expenses}}" +msgstr "{expenseCount, plural, one {# expense} other {# expenses}}" + +#: src/features/contacts/SplitwiseImport.tsx +msgid "{expenses} and {payments}" +msgstr "{expenses} and {payments}" + #: src/features/add/DateSheet.tsx msgid "{futureDate} is in the future. It still counts towards your balances straight away." msgstr "{futureDate} is in the future. It still counts towards your balances straight away." @@ -119,6 +131,10 @@ msgstr "{payerName} paid {payeeName}" msgid "{payerName} paid you" msgstr "{payerName} paid you" +#: src/features/contacts/SplitwiseImport.tsx +msgid "{paymentCount, plural, one {# payment} other {# payments}}" +msgstr "{paymentCount, plural, one {# payment} other {# payments}}" + #: src/features/add/SplitEditorSheet.tsx msgid "{peopleCount, plural, one {{sharing} of # person sharing} other {{sharing} of # people sharing}}" msgstr "{peopleCount, plural, one {{sharing} of # person sharing} other {{sharing} of # people sharing}}" @@ -169,6 +185,10 @@ msgstr "{shareCount, plural, one {{personName}: # share} other {{personName}: # msgid "{shareCount, plural, one {# share} other {# shares}}" msgstr "{shareCount, plural, one {# share} other {# shares}}" +#: src/features/contacts/SplitwiseImport.tsx +msgid "{skippedCount, plural, other {# skipped.}}" +msgstr "{skippedCount, plural, other {# skipped.}}" + #: src/features/add/ExpenseForm.tsx msgid "{title} added." msgstr "{title} added." @@ -300,6 +320,18 @@ msgstr "Adds up to {assigned}%, not 100%. Tap to fix." msgid "Adds up to {totalLabel}" msgstr "Adds up to {totalLabel}" +#: src/features/contacts/SplitwiseImport.tsx +msgid "After import, {contactName} owes you {amount}." +msgstr "After import, {contactName} owes you {amount}." + +#: src/features/contacts/SplitwiseImport.tsx +msgid "After import, you owe {contactName} {amount}." +msgstr "After import, you owe {contactName} {amount}." + +#: src/features/contacts/SplitwiseImport.tsx +msgid "After import, you’re settled up." +msgstr "After import, you’re settled up." + #: src/features/add/SplitEditorSheet.tsx msgid "All of it assigned" msgstr "All of it assigned" @@ -402,6 +434,10 @@ msgstr "Check the split" msgid "Check your connection and try again." msgstr "Check your connection and try again." +#: src/features/contacts/SplitwiseImport.tsx +msgid "Checking the file" +msgstr "Checking the file" + #: src/features/add/PaymentForm.tsx msgid "Choose" msgstr "Choose" @@ -410,6 +446,14 @@ msgstr "Choose" msgid "Choose a person" msgstr "Choose a person" +#: src/features/contacts/SplitwiseImport.tsx +msgid "Choose another file" +msgstr "Choose another file" + +#: src/features/contacts/SplitwiseImport.tsx +msgid "Choose which person in the file is you." +msgstr "Choose which person in the file is you." + #: src/features/add/SplitEditorSheet.tsx msgid "Choose who paid and how the cost is shared." msgstr "Choose who paid and how the cost is shared." @@ -424,6 +468,7 @@ msgstr "Choose who you paid" #: src/features/add/ScreenFrame.tsx #: src/features/add/SplitEditorSheet.tsx +#: src/features/contacts/SplitwiseImport.tsx msgid "Close" msgstr "Close" @@ -479,6 +524,10 @@ msgstr "Couldn’t add this contact. Try again." msgid "Couldn't change your password. Try again." msgstr "Couldn't change your password. Try again." +#: src/features/contacts/SplitwiseImport.tsx +msgid "Couldn’t check the file." +msgstr "Couldn’t check the file." + #: src/features/auth/SignUpPage.tsx msgid "Couldn't create your account. Try again." msgstr "Couldn't create your account. Try again." @@ -491,6 +540,10 @@ msgstr "Couldn’t delete the expense. Try again." msgid "Couldn’t delete the payment. Try again." msgstr "Couldn’t delete the payment. Try again." +#: src/features/contacts/SplitwiseImport.tsx +msgid "Couldn’t import. Nothing was added." +msgstr "Couldn’t import. Nothing was added." + #: src/features/activity/ActivityPage.tsx #: src/features/contacts/ContactPage.tsx msgid "Couldn't load activity" @@ -806,6 +859,26 @@ msgstr "Home & bills" msgid "How to split" msgstr "How to split" +#: src/features/contacts/SplitwiseImport.tsx +msgid "Import" +msgstr "Import" + +#: src/features/contacts/SplitwiseImport.tsx +msgid "Import anyway" +msgstr "Import anyway" + +#: src/features/contacts/SplitwiseImport.tsx +msgid "Import from Splitwise" +msgstr "Import from Splitwise" + +#: src/features/contacts/SplitwiseImport.tsx +msgid "Imported {counts}" +msgstr "Imported {counts}" + +#: src/features/contacts/SplitwiseImport.tsx +msgid "Importing…" +msgstr "Importing…" + #: src/features/auth/LoginPage.tsx msgid "Invalid email or password." msgstr "Invalid email or password." @@ -1046,6 +1119,10 @@ msgstr "Note" msgid "Note <0>(optional)" msgstr "Note <0>(optional)" +#: src/features/contacts/SplitwiseImport.tsx +msgid "Nothing new to import." +msgstr "Nothing new to import." + #: src/features/contacts/ContactsPage.tsx msgid "Nothing to settle" msgstr "Nothing to settle" @@ -1405,6 +1482,10 @@ msgstr "That’s more than you owe {name} ({current})." msgid "That’s your email. You’re always in it." msgstr "That’s your email. You’re always in it." +#: src/features/contacts/SplitwiseImport.tsx +msgid "The file’s rows don’t add up to its total (off by {offBy})." +msgstr "The file’s rows don’t add up to its total (off by {offBy})." + #: src/lib/repeat.ts msgid "The monthly repeat stops too." msgstr "The monthly repeat stops too." @@ -1461,6 +1542,14 @@ msgstr "This can’t be undone." msgid "This expense doesn’t exist" msgstr "This expense doesn’t exist" +#: src/features/contacts/SplitwiseImport.tsx +msgid "This file is too large." +msgstr "This file is too large." + +#: src/features/contacts/SplitwiseImport.tsx +msgid "This file isn’t a supported Splitwise export." +msgstr "This file isn’t a supported Splitwise export." + #: src/app/ErrorPages.tsx msgid "This page doesn’t exist" msgstr "This page doesn’t exist" @@ -1504,6 +1593,7 @@ msgstr "Transport" #: src/components/LoadError.tsx #: src/features/activity/ActivityListFooter.tsx +#: src/features/contacts/SplitwiseImport.tsx msgid "Try again" msgstr "Try again" @@ -1555,6 +1645,10 @@ msgstr "What was it for?" msgid "What you’ve entered won’t be saved." msgstr "What you’ve entered won’t be saved." +#: src/features/contacts/SplitwiseImport.tsx +msgid "Which one are you?" +msgstr "Which one are you?" + #: src/features/add/PaymentForm.tsx msgid "Who did you pay?" msgstr "Who did you pay?" diff --git a/frontend/src/locales/pl.po b/frontend/src/locales/pl.po index e5a46a6..45fdd68 100644 --- a/frontend/src/locales/pl.po +++ b/frontend/src/locales/pl.po @@ -23,6 +23,10 @@ msgstr "{assignedNumber} z {totalAmount}" msgid "{assignedPercent}% of 100%" msgstr "{assignedPercent}% ze 100%" +#: src/features/contacts/SplitwiseImport.tsx +msgid "{counts} between {ownName} and {otherName}." +msgstr "{counts} – {ownName} i {otherName}." + #: src/features/activity/ActivityRows.tsx msgid "{date} · {subline}" msgstr "{date} · {subline}" @@ -63,6 +67,14 @@ msgstr "Dodano do kontaktów: {displayName}" msgid "{each} each" msgstr "Po {each}" +#: src/features/contacts/SplitwiseImport.tsx +msgid "{expenseCount, plural, one {# expense} other {# expenses}}" +msgstr "{expenseCount, plural, one {# wydatek} few {# wydatki} many {# wydatków} other {# wydatku}}" + +#: src/features/contacts/SplitwiseImport.tsx +msgid "{expenses} and {payments}" +msgstr "{expenses} i {payments}" + #: src/features/add/DateSheet.tsx msgid "{futureDate} is in the future. It still counts towards your balances straight away." msgstr "{futureDate} to data z przyszłości. Mimo to od razu wlicza się do sald." @@ -119,6 +131,10 @@ msgstr "{payerName} płaci, {payeeName} otrzymuje" msgid "{payerName} paid you" msgstr "{payerName} płaci, ty otrzymujesz" +#: src/features/contacts/SplitwiseImport.tsx +msgid "{paymentCount, plural, one {# payment} other {# payments}}" +msgstr "{paymentCount, plural, one {# płatność} few {# płatności} many {# płatności} other {# płatności}}" + #: src/features/add/SplitEditorSheet.tsx msgid "{peopleCount, plural, one {{sharing} of # person sharing} other {{sharing} of # people sharing}}" msgstr "{peopleCount, plural, one {{sharing} z # osoby w podziale} few {{sharing} z # osób w podziale} many {{sharing} z # osób w podziale} other {{sharing} z # osoby w podziale}}" @@ -169,6 +185,10 @@ msgstr "{shareCount, plural, one {{personName}: # udział} few {{personName}: # msgid "{shareCount, plural, one {# share} other {# shares}}" msgstr "{shareCount, plural, one {# udział} few {# udziały} many {# udziałów} other {# udziału}}" +#: src/features/contacts/SplitwiseImport.tsx +msgid "{skippedCount, plural, other {# skipped.}}" +msgstr "{skippedCount, plural, other {Pominięto: #.}}" + #: src/features/add/ExpenseForm.tsx msgid "{title} added." msgstr "Dodano „{title}”." @@ -300,6 +320,18 @@ msgstr "Suma to {assigned}%, a nie 100%. Dotknij, aby poprawić." msgid "Adds up to {totalLabel}" msgstr "Zgadza się: {totalLabel}" +#: src/features/contacts/SplitwiseImport.tsx +msgid "After import, {contactName} owes you {amount}." +msgstr "Po imporcie {contactName} ma ci oddać {amount}." + +#: src/features/contacts/SplitwiseImport.tsx +msgid "After import, you owe {contactName} {amount}." +msgstr "Po imporcie masz do oddania {amount}." + +#: src/features/contacts/SplitwiseImport.tsx +msgid "After import, you’re settled up." +msgstr "Po imporcie wszystko będzie rozliczone." + #: src/features/add/SplitEditorSheet.tsx msgid "All of it assigned" msgstr "Przypisano całość" @@ -402,6 +434,10 @@ msgstr "Sprawdź podział" msgid "Check your connection and try again." msgstr "Sprawdź połączenie i spróbuj ponownie." +#: src/features/contacts/SplitwiseImport.tsx +msgid "Checking the file" +msgstr "Sprawdzanie pliku" + #: src/features/add/PaymentForm.tsx msgid "Choose" msgstr "Wybierz" @@ -410,6 +446,14 @@ msgstr "Wybierz" msgid "Choose a person" msgstr "Wybierz osobę" +#: src/features/contacts/SplitwiseImport.tsx +msgid "Choose another file" +msgstr "Wybierz inny plik" + +#: src/features/contacts/SplitwiseImport.tsx +msgid "Choose which person in the file is you." +msgstr "Wybierz, która osoba w pliku to ty." + #: src/features/add/SplitEditorSheet.tsx msgid "Choose who paid and how the cost is shared." msgstr "Wybierz, kto płaci i jak podzielić koszt." @@ -424,6 +468,7 @@ msgstr "Wybierz, komu płacisz" #: src/features/add/ScreenFrame.tsx #: src/features/add/SplitEditorSheet.tsx +#: src/features/contacts/SplitwiseImport.tsx msgid "Close" msgstr "Zamknij" @@ -479,6 +524,10 @@ msgstr "Nie udało się dodać tego kontaktu. Spróbuj ponownie." msgid "Couldn't change your password. Try again." msgstr "Nie udało się zmienić hasła. Spróbuj ponownie." +#: src/features/contacts/SplitwiseImport.tsx +msgid "Couldn’t check the file." +msgstr "Nie udało się sprawdzić pliku." + #: src/features/auth/SignUpPage.tsx msgid "Couldn't create your account. Try again." msgstr "Nie udało się założyć konta. Spróbuj ponownie." @@ -491,6 +540,10 @@ msgstr "Nie udało się usunąć wydatku. Spróbuj ponownie." msgid "Couldn’t delete the payment. Try again." msgstr "Nie udało się usunąć płatności. Spróbuj ponownie." +#: src/features/contacts/SplitwiseImport.tsx +msgid "Couldn’t import. Nothing was added." +msgstr "Nie udało się zaimportować. Niczego nie dodano." + #: src/features/activity/ActivityPage.tsx #: src/features/contacts/ContactPage.tsx msgid "Couldn't load activity" @@ -806,6 +859,26 @@ msgstr "Dom i rachunki" msgid "How to split" msgstr "Jak podzielić" +#: src/features/contacts/SplitwiseImport.tsx +msgid "Import" +msgstr "Importuj" + +#: src/features/contacts/SplitwiseImport.tsx +msgid "Import anyway" +msgstr "Importuj mimo to" + +#: src/features/contacts/SplitwiseImport.tsx +msgid "Import from Splitwise" +msgstr "Import ze Splitwise" + +#: src/features/contacts/SplitwiseImport.tsx +msgid "Imported {counts}" +msgstr "Zaimportowano: {counts}" + +#: src/features/contacts/SplitwiseImport.tsx +msgid "Importing…" +msgstr "Importowanie…" + #: src/features/auth/LoginPage.tsx msgid "Invalid email or password." msgstr "Nieprawidłowy e-mail lub hasło." @@ -1046,6 +1119,10 @@ msgstr "Notatka" msgid "Note <0>(optional)" msgstr "Notatka <0>(opcjonalnie)" +#: src/features/contacts/SplitwiseImport.tsx +msgid "Nothing new to import." +msgstr "Nie ma nic nowego do zaimportowania." + #: src/features/contacts/ContactsPage.tsx msgid "Nothing to settle" msgstr "Nie ma nic do rozliczenia" @@ -1405,6 +1482,10 @@ msgstr "To więcej, niż masz do oddania ({name}: {current})." msgid "That’s your email. You’re always in it." msgstr "To twój adres e-mail. Zawsze bierzesz udział w wydatku." +#: src/features/contacts/SplitwiseImport.tsx +msgid "The file’s rows don’t add up to its total (off by {offBy})." +msgstr "Pozycje w pliku nie sumują się do jego salda (różnica: {offBy})." + #: src/lib/repeat.ts msgid "The monthly repeat stops too." msgstr "Powtarzanie co miesiąc też się zatrzyma." @@ -1461,6 +1542,14 @@ msgstr "Tego nie można cofnąć." msgid "This expense doesn’t exist" msgstr "Ten wydatek nie istnieje" +#: src/features/contacts/SplitwiseImport.tsx +msgid "This file is too large." +msgstr "Ten plik jest za duży." + +#: src/features/contacts/SplitwiseImport.tsx +msgid "This file isn’t a supported Splitwise export." +msgstr "Ten plik nie jest obsługiwanym eksportem ze Splitwise." + #: src/app/ErrorPages.tsx msgid "This page doesn’t exist" msgstr "Ta strona nie istnieje" @@ -1504,6 +1593,7 @@ msgstr "Transport" #: src/components/LoadError.tsx #: src/features/activity/ActivityListFooter.tsx +#: src/features/contacts/SplitwiseImport.tsx msgid "Try again" msgstr "Spróbuj ponownie" @@ -1555,6 +1645,10 @@ msgstr "Na co był wydatek?" msgid "What you’ve entered won’t be saved." msgstr "Wpisane dane nie zostaną zapisane." +#: src/features/contacts/SplitwiseImport.tsx +msgid "Which one are you?" +msgstr "Która osoba to ty?" + #: src/features/add/PaymentForm.tsx msgid "Who did you pay?" msgstr "Komu płacisz?" diff --git a/src/Controller/Api/SplitwiseImportApiController.php b/src/Controller/Api/SplitwiseImportApiController.php new file mode 100644 index 0000000..4d8e0a6 --- /dev/null +++ b/src/Controller/Api/SplitwiseImportApiController.php @@ -0,0 +1,74 @@ + '\d+'])] + #[IsGranted('ROLE_USER')] + public function preview( + int $userId, + #[MapRequestPayload(acceptFormat: 'json', validationFailedStatusCode: Response::HTTP_BAD_REQUEST)] + SplitwisePreviewRequest $request, + ): JsonResponse { + [$user, $contact] = $this->pair($userId); + + return $this->json($this->importService->preview($user, $contact, $request->csv)); + } + + #[Route('/contacts/{userId}/import/splitwise', name: 'api_contacts_import_splitwise', methods: ['POST'], requirements: ['userId' => '\d+'])] + #[IsGranted('ROLE_USER')] + public function import( + int $userId, + #[MapRequestPayload(acceptFormat: 'json', validationFailedStatusCode: Response::HTTP_BAD_REQUEST)] + SplitwiseImportRequest $request, + ): JsonResponse { + [$user, $contact] = $this->pair($userId); + + return $this->json($this->importService->import($user, $contact, $request->csv, $request->ownColumn)); + } + + /** + * @return array{User, User} + */ + private function pair(int $userId): array + { + /** @var User $user */ + $user = $this->getUser(); + + if ($userId === $user->getId()) { + throw new BadRequestHttpException('You cannot import with yourself.'); + } + + $contact = $this->userRepository->find($userId); + if (null === $contact || !$this->contactService->isKnownContact($user, $contact)) { + throw $this->createNotFoundException('Contact not found.'); + } + + return [$user, $contact]; + } +} diff --git a/src/Dto/SplitwiseImportPreview.php b/src/Dto/SplitwiseImportPreview.php new file mode 100644 index 0000000..f232e48 --- /dev/null +++ b/src/Dto/SplitwiseImportPreview.php @@ -0,0 +1,20 @@ + + */ + public function findBetweenPair(User $first, User $second, string $currency): array + { + return $this->createQueryBuilder('e') + ->join('e.debts', 'd') + ->where('e.currency = :currency') + ->andWhere('(e.payee = :first AND d.payer = :second) OR (e.payee = :second AND d.payer = :first)') + ->setParameter('currency', $currency) + ->setParameter('first', $first) + ->setParameter('second', $second) + ->getQuery() + ->getResult(); + } } diff --git a/src/Repository/TransferRepository.php b/src/Repository/TransferRepository.php index 95d0222..70cece5 100644 --- a/src/Repository/TransferRepository.php +++ b/src/Repository/TransferRepository.php @@ -67,4 +67,19 @@ public function findLastCreatedAtByCounterpart(User $user): array return $lastCreatedAt; } + + /** + * @return list + */ + public function findBetweenPair(User $first, User $second, string $currency): array + { + return $this->createQueryBuilder('t') + ->where('t.currency = :currency') + ->andWhere('(t.payer = :first AND t.payee = :second) OR (t.payer = :second AND t.payee = :first)') + ->setParameter('currency', $currency) + ->setParameter('first', $first) + ->setParameter('second', $second) + ->getQuery() + ->getResult(); + } } diff --git a/src/Services/Splitwise/SplitwiseCategoryMapper.php b/src/Services/Splitwise/SplitwiseCategoryMapper.php new file mode 100644 index 0000000..4ae40ac --- /dev/null +++ b/src/Services/Splitwise/SplitwiseCategoryMapper.php @@ -0,0 +1,105 @@ + - Other" is assumed for the rest. + */ +class SplitwiseCategoryMapper +{ + private const array PAYMENT_LABELS = ['Payment', 'Płatność']; + + private const array CATEGORIES = [ + 'Groceries' => ExpenseCategory::Groceries, + 'Artykuły spożywcze' => ExpenseCategory::Groceries, + + 'Dining out' => ExpenseCategory::FoodAndDrink, + 'Jedzenie na mieście' => ExpenseCategory::FoodAndDrink, + 'Liquor' => ExpenseCategory::FoodAndDrink, + 'Alkohol' => ExpenseCategory::FoodAndDrink, + 'Food and drink - Other' => ExpenseCategory::FoodAndDrink, + 'Jedzenie i napoje - Inne' => ExpenseCategory::FoodAndDrink, + + 'Bicycle' => ExpenseCategory::Transport, + 'Rower' => ExpenseCategory::Transport, + 'Bus/train' => ExpenseCategory::Transport, + 'Autobus/pociąg' => ExpenseCategory::Transport, + 'Car' => ExpenseCategory::Transport, + 'Samochód' => ExpenseCategory::Transport, + 'Gas/fuel' => ExpenseCategory::Transport, + 'Paliwo' => ExpenseCategory::Transport, + 'Hotel' => ExpenseCategory::Transport, + 'Parking' => ExpenseCategory::Transport, + 'Plane' => ExpenseCategory::Transport, + 'Samolot' => ExpenseCategory::Transport, + 'Taxi' => ExpenseCategory::Transport, + 'Transportation - Other' => ExpenseCategory::Transport, + 'Transport - Inne' => ExpenseCategory::Transport, + + 'Cleaning' => ExpenseCategory::HomeAndBills, + 'Sprzątanie' => ExpenseCategory::HomeAndBills, + 'Electricity' => ExpenseCategory::HomeAndBills, + 'Prąd' => ExpenseCategory::HomeAndBills, + 'Heat/gas' => ExpenseCategory::HomeAndBills, + 'Ogrzewanie/gaz' => ExpenseCategory::HomeAndBills, + 'Trash' => ExpenseCategory::HomeAndBills, + 'Śmieci' => ExpenseCategory::HomeAndBills, + 'TV/Phone/Internet' => ExpenseCategory::HomeAndBills, + 'TV/Telefon/Internet' => ExpenseCategory::HomeAndBills, + 'Water' => ExpenseCategory::HomeAndBills, + 'Woda' => ExpenseCategory::HomeAndBills, + 'Utilities - Other' => ExpenseCategory::HomeAndBills, + 'Media - Inne' => ExpenseCategory::HomeAndBills, + 'Electronics' => ExpenseCategory::HomeAndBills, + 'Elektronika' => ExpenseCategory::HomeAndBills, + 'Furniture' => ExpenseCategory::HomeAndBills, + 'Meble' => ExpenseCategory::HomeAndBills, + 'Household supplies' => ExpenseCategory::HomeAndBills, + 'AGD' => ExpenseCategory::HomeAndBills, + 'Maintenance' => ExpenseCategory::HomeAndBills, + 'Utrzymanie' => ExpenseCategory::HomeAndBills, + 'Mortgage' => ExpenseCategory::HomeAndBills, + 'Kredyt' => ExpenseCategory::HomeAndBills, + 'Pets' => ExpenseCategory::HomeAndBills, + 'Zwierzęta' => ExpenseCategory::HomeAndBills, + 'Rent' => ExpenseCategory::HomeAndBills, + 'Czynsz' => ExpenseCategory::HomeAndBills, + 'Services' => ExpenseCategory::HomeAndBills, + 'Usługi' => ExpenseCategory::HomeAndBills, + 'Home - Other' => ExpenseCategory::HomeAndBills, + 'Dom - Inne' => ExpenseCategory::HomeAndBills, + + 'Games' => ExpenseCategory::Entertainment, + 'Gry' => ExpenseCategory::Entertainment, + 'Movies' => ExpenseCategory::Entertainment, + 'Filmy' => ExpenseCategory::Entertainment, + 'Music' => ExpenseCategory::Entertainment, + 'Muzyka' => ExpenseCategory::Entertainment, + 'Sports' => ExpenseCategory::Entertainment, + 'Sporty' => ExpenseCategory::Entertainment, + 'Entertainment - Other' => ExpenseCategory::Entertainment, + 'Rozrywka - Inne' => ExpenseCategory::Entertainment, + + 'Gifts' => ExpenseCategory::Gifts, + 'Prezenty' => ExpenseCategory::Gifts, + + 'Medical expenses' => ExpenseCategory::Health, + 'Wydatki medyczne' => ExpenseCategory::Health, + ]; + + public function isPayment(string $label): bool + { + return in_array($label, self::PAYMENT_LABELS, true); + } + + public function toCategory(string $label): ExpenseCategory + { + return self::CATEGORIES[$label] ?? ExpenseCategory::General; + } +} diff --git a/src/Services/Splitwise/SplitwiseCsvParser.php b/src/Services/Splitwise/SplitwiseCsvParser.php new file mode 100644 index 0000000..686428c --- /dev/null +++ b/src/Services/Splitwise/SplitwiseCsvParser.php @@ -0,0 +1,146 @@ +readLines($csv); + + if (count($lines) < 4 || !$this->isNote($lines[0]) || !$this->isBlank($lines[1]) || self::COLUMNS !== count($lines[2]) || !$this->isBlank($lines[3])) { + throw new UnsupportedSplitwiseExportException(); + } + + $names = [trim((string) $lines[2][5]), trim((string) $lines[2][6])]; + if ('' === $names[0] || '' === $names[1]) { + throw new UnsupportedSplitwiseExportException(); + } + + $index = 4; + $rows = []; + while ($index < count($lines) && !$this->isBlank($lines[$index]) && !$this->isTotal($lines[$index])) { + $rows[] = $this->parseRow($lines[$index]); + ++$index; + } + + $totals = []; + for (; $index < count($lines); ++$index) { + $line = $lines[$index]; + if ($this->isBlank($line)) { + continue; + } + + [$currency, $nets] = $this->parseTotal($line); + if (isset($totals[$currency])) { + throw new UnsupportedSplitwiseExportException(); + } + + $totals[$currency] = $nets; + } + + return new SplitwiseExport($names, $rows, $totals); + } + + /** + * @return list> + */ + private function readLines(string $csv): array + { + $stream = fopen('php://memory', 'r+'); + if (false === $stream) { + throw new \RuntimeException('Could not open a memory stream.'); + } + + fwrite($stream, preg_replace('/^\xEF\xBB\xBF/', '', $csv) ?? $csv); + rewind($stream); + + $lines = []; + while (false !== ($line = fgetcsv($stream, escape: ''))) { + $lines[] = $line; + } + + fclose($stream); + + return $lines; + } + + /** + * @param list $line + */ + private function parseRow(array $line): SplitwiseRow + { + if (self::COLUMNS !== count($line)) { + throw new UnsupportedSplitwiseExportException(); + } + + [$date, $description, $category, $cost, $currency, $netA, $netB] = array_map(static fn (?string $cell): string => trim((string) $cell), $line); + + $parsedDate = \DateTimeImmutable::createFromFormat('!Y-m-d', $date); + if (false === $parsedDate || $parsedDate->format('Y-m-d') !== $date) { + throw new UnsupportedSplitwiseExportException(); + } + + if (1 !== preg_match('/^[A-Z]{3}$/', $currency) || !$this->isDecimal($cost) || !$this->isDecimal($netA) || !$this->isDecimal($netB)) { + throw new UnsupportedSplitwiseExportException(); + } + + return new SplitwiseRow($parsedDate, $description, $category, $cost, $currency, [$netA, $netB]); + } + + /** + * @param list $line + * + * @return array{string, array{string, string}} + */ + private function parseTotal(array $line): array + { + $cells = array_map(static fn (?string $cell): string => trim((string) $cell), $line); + if (!$this->isTotal($line) || 1 !== preg_match('/^[A-Z]{3}$/', $cells[4]) || !$this->isDecimal($cells[5]) || !$this->isDecimal($cells[6])) { + throw new UnsupportedSplitwiseExportException(); + } + + return [$cells[4], [$cells[5], $cells[6]]]; + } + + /** + * @param list $line + */ + private function isTotal(array $line): bool + { + return self::COLUMNS === count($line) && '' === trim((string) $line[2]) && '' === trim((string) $line[3]); + } + + /** + * @param list $line + */ + private function isBlank(array $line): bool + { + return 1 === count($line) && '' === trim((string) $line[0]); + } + + /** + * @param list $line + */ + private function isNote(array $line): bool + { + return 1 === count($line) && '' !== trim((string) $line[0]); + } + + private function isDecimal(string $value): bool + { + return 1 === preg_match(self::DECIMAL, $value); + } +} diff --git a/src/Services/Splitwise/SplitwiseExport.php b/src/Services/Splitwise/SplitwiseExport.php new file mode 100644 index 0000000..24a4134 --- /dev/null +++ b/src/Services/Splitwise/SplitwiseExport.php @@ -0,0 +1,20 @@ + $rows + * @param array $totalsByCurrency the Total balance per currency, per person column + */ + public function __construct( + public array $names, + public array $rows, + public array $totalsByCurrency, + ) { + } +} diff --git a/src/Services/Splitwise/SplitwiseImportService.php b/src/Services/Splitwise/SplitwiseImportService.php new file mode 100644 index 0000000..38b456c --- /dev/null +++ b/src/Services/Splitwise/SplitwiseImportService.php @@ -0,0 +1,262 @@ +read($csv); + $existing = $this->existingKeyCounts($user, $contact); + $balance = $this->currentBalance($user, $contact); + + return new SplitwiseImportPreview( + names: $export->names, + mismatch: $this->totalMismatch($export), + options: [ + $this->summarize($balance, $this->plan($export, $user, $contact, 0, $existing)), + $this->summarize($balance, $this->plan($export, $user, $contact, 1, $existing)), + ], + ); + } + + /** + * @param 0|1 $ownColumn + */ + public function import(User $user, User $contact, string $csv, int $ownColumn): SplitwiseImportSummary + { + $plan = $this->plan($this->read($csv), $user, $contact, $ownColumn, $this->existingKeyCounts($user, $contact)); + $summary = $this->summarize($this->currentBalance($user, $contact), $plan); + + $this->entityManager->wrapInTransaction(function () use ($plan): void { + foreach ($plan['items'] as $item) { + $this->entityManager->persist($item); + if ($item instanceof Expense) { + array_map($this->entityManager->persist(...), $item->getDebts()->toArray()); + } + } + }); + + return $summary; + } + + /** + * A row the pair already has is skipped as many times as the pair has it, so re-importing is + * harmless while repeated rows within one file still import. + * + * @param 0|1 $ownColumn + * @param array $existing counts of the pair's existing rows by dedupe key + * + * @return array{items: list, skipped: int, ownNet: string} + */ + private function plan(SplitwiseExport $export, User $user, User $contact, int $ownColumn, array $existing): array + { + $people = 0 === $ownColumn ? [$user, $contact] : [$contact, $user]; + + $items = []; + $skipped = 0; + $ownNet = '0.00'; + foreach ($export->rows as $row) { + $net = bcadd($row->nets[0], '0', 2); + if (self::CURRENCY !== $row->currency || 0 === bccomp($net, '0', 2)) { + ++$skipped; + continue; + } + + $owedColumn = bccomp($net, '0', 2) > 0 ? 0 : 1; + $owed = $people[$owedColumn]; + $owing = $people[1 - $owedColumn]; + $absoluteNet = ltrim($net, '-'); + + $isPayment = $this->categoryMapper->isPayment($row->category); + $key = $isPayment + ? $this->transferKey($row->date, $absoluteNet, $owed, $owing) + : $this->expenseKey($row->date, bcadd($row->cost, '0', 2), $owed, $this->title($row->description)); + + if (($existing[$key] ?? 0) > 0) { + --$existing[$key]; + ++$skipped; + continue; + } + + $items[] = $isPayment + ? new Transfer($owed, $owing, $absoluteNet, $row->date, null, self::CURRENCY) + : $this->buildExpense($row, $owed, $owing, $absoluteNet); + $ownNet = bcadd($ownNet, bcadd($row->nets[$ownColumn], '0', 2), 2); + } + + return ['items' => $items, 'skipped' => $skipped, 'ownNet' => $ownNet]; + } + + /** + * The export has only each side's net, not who paid; booking it as the owed person paying the + * whole cost keeps the balance right. + */ + private function buildExpense(SplitwiseRow $row, User $payee, User $debtor, string $debtorShare): Expense + { + $cost = bcadd($row->cost, '0', 2); + $expense = new Expense( + $payee, + $this->title($row->description), + null, + $cost, + $row->date, + self::CURRENCY, + SplitType::Exact, + $this->categoryMapper->toCategory($row->category), + ); + + $expense->addDebt(new Debt($debtor, $expense, $debtorShare, self::CURRENCY)); + + $ownShare = bcsub($cost, $debtorShare, 2); + if (bccomp($ownShare, '0', 2) > 0) { + $expense->addDebt(new Debt($payee, $expense, $ownShare, self::CURRENCY)); + } + + return $expense; + } + + private function read(string $csv): SplitwiseExport + { + $export = $this->parser->parse($csv); + + foreach ($export->rows as $row) { + if (self::CURRENCY === $row->currency && !$this->isImportable($row)) { + throw new UnsupportedSplitwiseExportException(); + } + } + + $total = $export->totalsByCurrency[self::CURRENCY] ?? null; + if (null !== $total && !$this->cancelsOut($total)) { + throw new UnsupportedSplitwiseExportException(); + } + + return $export; + } + + private function isImportable(SplitwiseRow $row): bool + { + return $this->cancelsOut($row->nets) + && 1 === preg_match(self::AMOUNT, $row->cost) + && bccomp($row->cost, '0', 2) >= 0 + && bccomp($row->cost, self::MAX_AMOUNT, 2) <= 0 + && bccomp(ltrim($row->nets[0], '-'), $row->cost, 2) <= 0; + } + + /** + * @param array{string, string} $nets + */ + private function cancelsOut(array $nets): bool + { + return 1 === preg_match(self::AMOUNT, $nets[0]) + && 1 === preg_match(self::AMOUNT, $nets[1]) + && 0 === bccomp(bcadd($nets[0], $nets[1], 2), '0', 2); + } + + private function totalMismatch(SplitwiseExport $export): ?string + { + $difference = bcsub('0', $export->totalsByCurrency[self::CURRENCY][0] ?? '0', 2); + foreach ($export->rows as $row) { + if (self::CURRENCY === $row->currency) { + $difference = bcadd($difference, $row->nets[0], 2); + } + } + + return 0 === bccomp($difference, '0', 2) ? null : $difference; + } + + /** + * @param array{items: list, skipped: int, ownNet: string} $plan + */ + private function summarize(string $currentBalance, array $plan): SplitwiseImportSummary + { + $expenses = count(array_filter($plan['items'], static fn (Expense|Transfer $item): bool => $item instanceof Expense)); + + return new SplitwiseImportSummary( + expenses: $expenses, + transfers: count($plan['items']) - $expenses, + skipped: $plan['skipped'], + balance: bcadd($currentBalance, $plan['ownNet'], 2), + ); + } + + private function currentBalance(User $user, User $contact): string + { + $balances = $this->balanceService->getBalancesByCounterpart($user)[(int) $contact->getId()] ?? []; + foreach ($balances as $balance) { + if (self::CURRENCY === $balance->currency) { + return $balance->amount; + } + } + + return '0.00'; + } + + /** + * @return array + */ + private function existingKeyCounts(User $user, User $contact): array + { + $keys = []; + foreach ($this->expenseRepository->findBetweenPair($user, $contact, self::CURRENCY) as $expense) { + $keys[] = $this->expenseKey($expense->getOccurredOn(), $expense->getAmount(), $expense->getPayee(), trim($expense->getTitle())); + } + + foreach ($this->transferRepository->findBetweenPair($user, $contact, self::CURRENCY) as $transfer) { + $keys[] = $this->transferKey($transfer->getOccurredOn(), $transfer->getAmount(), $transfer->getPayer(), $transfer->getPayee()); + } + + return array_count_values($keys); + } + + /** Transfers match without their text: Splitwise generates it, in the exporting user's language. */ + private function transferKey(\DateTimeImmutable $date, string $amount, User $payer, User $payee): string + { + return implode('|', ['transfer', $date->format('Y-m-d'), $amount, $payer->getId(), $payee->getId()]); + } + + private function expenseKey(\DateTimeImmutable $date, string $amount, User $payee, string $title): string + { + return implode('|', ['expense', $date->format('Y-m-d'), $amount, $payee->getId(), $title]); + } + + private function title(string $description): string + { + $title = mb_substr(trim($description), 0, self::TITLE_MAX_LENGTH); + + return '' === $title ? 'Splitwise' : $title; + } +} diff --git a/src/Services/Splitwise/SplitwiseRow.php b/src/Services/Splitwise/SplitwiseRow.php new file mode 100644 index 0000000..b7b32f3 --- /dev/null +++ b/src/Services/Splitwise/SplitwiseRow.php @@ -0,0 +1,21 @@ +client = static::createClient(); + $entityManager = $this->getEntityManager(); + + $this->anna = UserFactory::createUser('anna@example.com'); + $this->ben = UserFactory::createUser('ben@example.com'); + $entityManager->persist($this->anna); + $entityManager->persist($this->ben); + $entityManager->persist(new Contact($this->anna, $this->ben)); + $entityManager->flush(); + + $this->client->loginUser($this->anna); + } + + public function testNotLoggedIn(): void + { + $client = $this->client; + $client->restart(); + $this->requestJson($client, 'POST', $this->previewUrl(), ['csv' => self::fixture('en.csv')]); + + $this->assertResponseStatusCodeSame(401); + } + + public function testPreviewDescribesBothSidesWithoutWriting(): void + { + $this->requestJson($this->client, 'POST', $this->previewUrl(), ['csv' => self::fixture('en.csv')]); + + $this->assertJsonResponseIsSuccessful(200); + $this->assertSame([ + 'names' => ['Anna Kowalska', 'Ben Nowak'], + 'mismatch' => null, + 'options' => [ + ['expenses' => 4, 'transfers' => 1, 'skipped' => 2, 'balance' => '122.20'], + ['expenses' => 4, 'transfers' => 1, 'skipped' => 2, 'balance' => '-122.20'], + ], + ], $this->getJsonResponse()); + + $this->assertSame(0, $this->countRows(Expense::class)); + $this->assertSame(0, $this->countRows(Transfer::class)); + } + + public function testPreviewReportsTotalMismatch(): void + { + $csv = str_replace('PLN,122.20,-122.20', 'PLN,120.00,-120.00', self::fixture('en.csv')); + + $this->requestJson($this->client, 'POST', $this->previewUrl(), ['csv' => $csv]); + + $this->assertJsonResponseIsSuccessful(200); + $this->assertSame('2.20', $this->getJsonResponse()['mismatch']); + } + + public function testImportCreatesExpensesAndTransfersForTheChosenSide(): void + { + $this->requestJson($this->client, 'POST', $this->url(), ['csv' => self::fixture('en.csv'), 'ownColumn' => 0]); + + $this->assertJsonResponseIsSuccessful(200); + $this->assertSame(['expenses' => 4, 'transfers' => 1, 'skipped' => 2, 'balance' => '122.20'], $this->getJsonResponse()); + + $entityManager = $this->getEntityManager(); + $entityManager->clear(); + + $groceries = $entityManager->getRepository(Expense::class)->findOneBy(['title' => 'Groceries run']); + $this->assertNotNull($groceries); + $this->assertSame('anna@example.com', $groceries->getPayee()->getEmail()); + $this->assertSame('100.00', $groceries->getAmount()); + $this->assertSame(ExpenseCategory::Groceries, $groceries->getCategory()); + $this->assertSame('2025-01-10', $groceries->getOccurredOn()->format('Y-m-d')); + $this->assertNull($groceries->getDescription()); + $this->assertSame(['anna@example.com' => '50.00', 'ben@example.com' => '50.00'], $this->sharesByEmail($groceries)); + + $taxi = $entityManager->getRepository(Expense::class)->findOneBy(['title' => 'Taxi, airport']); + $this->assertNotNull($taxi); + $this->assertSame('ben@example.com', $taxi->getPayee()->getEmail()); + $this->assertSame(ExpenseCategory::Transport, $taxi->getCategory()); + $this->assertSame(['anna@example.com' => '80.00'], $this->sharesByEmail($taxi)); + + $transfer = $entityManager->getRepository(Transfer::class)->findOneBy([]); + $this->assertNotNull($transfer); + $this->assertSame('ben@example.com', $transfer->getPayer()->getEmail()); + $this->assertSame('anna@example.com', $transfer->getPayee()->getEmail()); + $this->assertSame('20.00', $transfer->getAmount()); + $this->assertNull($transfer->getDescription()); + + $this->client->request('GET', '/api/contacts'); + $this->assertSame([['currency' => 'PLN', 'amount' => '122.20']], $this->getJsonResponse()['items'][0]['balances']); + } + + public function testImportAsSecondPersonFlipsDirection(): void + { + $this->requestJson($this->client, 'POST', $this->url(), ['csv' => self::fixture('en.csv'), 'ownColumn' => 1]); + + $this->assertJsonResponseIsSuccessful(200); + $this->assertSame('-122.20', $this->getJsonResponse()['balance']); + + $this->getEntityManager()->clear(); + $groceries = $this->getEntityManager()->getRepository(Expense::class)->findOneBy(['title' => 'Groceries run']); + $this->assertNotNull($groceries); + $this->assertSame('ben@example.com', $groceries->getPayee()->getEmail()); + } + + public function testReimportSkipsEverythingAlreadyImported(): void + { + $this->requestJson($this->client, 'POST', $this->url(), ['csv' => self::fixture('en.csv'), 'ownColumn' => 0]); + $this->assertJsonResponseIsSuccessful(200); + + $this->requestJson($this->client, 'POST', $this->previewUrl(), ['csv' => self::fixture('en.csv')]); + + $this->assertJsonResponseIsSuccessful(200); + $this->assertSame(['expenses' => 0, 'transfers' => 0, 'skipped' => 7, 'balance' => '122.20'], $this->getJsonResponse()['options'][0]); + } + + public function testPolishExportOfTheSameHistoryAddsNothing(): void + { + $this->requestJson($this->client, 'POST', $this->url(), ['csv' => self::fixture('en.csv'), 'ownColumn' => 0]); + $this->assertJsonResponseIsSuccessful(200); + + $this->requestJson($this->client, 'POST', $this->url(), ['csv' => self::fixture('pl.csv'), 'ownColumn' => 0]); + + $this->assertJsonResponseIsSuccessful(200); + $this->assertSame(['expenses' => 0, 'transfers' => 0, 'skipped' => 7, 'balance' => '122.20'], $this->getJsonResponse()); + $this->assertSame(4, $this->countRows(Expense::class)); + $this->assertSame(1, $this->countRows(Transfer::class)); + } + + public function testPolishExportMapsCategoriesAndPayments(): void + { + $this->requestJson($this->client, 'POST', $this->url(), ['csv' => self::fixture('pl.csv'), 'ownColumn' => 0]); + + $this->assertJsonResponseIsSuccessful(200); + $this->assertSame(['expenses' => 4, 'transfers' => 1, 'skipped' => 2, 'balance' => '122.20'], $this->getJsonResponse()); + + $this->getEntityManager()->clear(); + $phone = $this->getEntityManager()->getRepository(Expense::class)->findOneBy(['title' => 'Phone']); + $this->assertNotNull($phone); + $this->assertSame(ExpenseCategory::HomeAndBills, $phone->getCategory()); + } + + public function testImportRequiresOwnColumn(): void + { + $this->requestJson($this->client, 'POST', $this->url(), ['csv' => self::fixture('en.csv')]); + + $this->assertResponseStatusCodeSame(400); + $this->assertSame(0, $this->countRows(Expense::class)); + } + + public function testPreviewChecksOnlyThePlnTotal(): void + { + $csv = str_replace('EUR,15.00,-15.00', 'EUR,99.00,-98.00', self::fixture('en.csv')); + + $this->requestJson($this->client, 'POST', $this->previewUrl(), ['csv' => $csv]); + + $this->assertJsonResponseIsSuccessful(200); + $this->assertNull($this->getJsonResponse()['mismatch']); + } + + public function testSkipsOtherCurrenciesWhateverTheirAmounts(): void + { + $csv = self::header() + ."2025-01-10,Lunch,General,10.00,PLN,10.00,-10.00\n" + ."2025-01-11,Hotel,Hotel,150000000.00,VND,150000000.00,-150000000.00\n" + ."2025-01-12,Dinner,Dining out,12.345,KWD,6.172,-6.173\n\n" + ."2025-02-01,Total balance, , ,PLN,10.00,-10.00\n"; + + $this->requestJson($this->client, 'POST', $this->url(), ['csv' => $csv, 'ownColumn' => 0]); + + $this->assertJsonResponseIsSuccessful(200); + $this->assertSame(['expenses' => 1, 'transfers' => 0, 'skipped' => 2, 'balance' => '10.00'], $this->getJsonResponse()); + } + + /** + * @dataProvider unimportablePlnProvider + */ + public function testRejectsPlnAmountsItCannotImport(string $rows): void + { + $this->requestJson($this->client, 'POST', $this->url(), ['csv' => self::header().$rows, 'ownColumn' => 0]); + + $this->assertResponseStatusCodeSame(422); + $this->assertSame(0, $this->countRows(Expense::class)); + } + + /** + * @return iterable + */ + public static function unimportablePlnProvider(): iterable + { + $total = "\n2025-02-01,Total balance, , ,PLN,10.00,-10.00\n"; + + yield 'nets do not cancel out' => ['2025-01-10,Lunch,General,10.00,PLN,10.00,-9.00'.$total]; + yield 'owed more than the cost' => ['2025-01-10,Lunch,General,10.00,PLN,12.00,-12.00'.$total]; + yield 'negative cost' => ['2025-01-10,Lunch,General,-10.00,PLN,10.00,-10.00'.$total]; + yield 'cost beyond the amount column' => ['2025-01-10,House,General,100000000.00,PLN,10.00,-10.00'.$total]; + yield 'third decimal' => ['2025-01-10,Lunch,General,10.005,PLN,10.00,-10.00'.$total]; + yield 'total does not cancel out' => ["2025-01-10,Lunch,General,10.00,PLN,10.00,-10.00\n\n2025-02-01,Total balance, , ,PLN,10.00,-9.00\n"]; + } + + public function testRejectsFileOfAnotherShape(): void + { + $this->requestJson($this->client, 'POST', $this->previewUrl(), ['csv' => "Date,Amount\n2025-01-10,10.00\n"]); + + $this->assertResponseStatusCodeSame(422); + $this->assertResponseHeaderSame('Content-Type', 'application/json'); + } + + public function testRejectsUnrelatedUser(): void + { + $stranger = UserFactory::createUser('stranger@example.com'); + $this->getEntityManager()->persist($stranger); + $this->getEntityManager()->flush(); + + $this->requestJson($this->client, 'POST', '/api/contacts/'.$stranger->getId().'/import/splitwise', ['csv' => self::fixture('en.csv'), 'ownColumn' => 0]); + + $this->assertResponseStatusCodeSame(404); + $this->assertSame(0, $this->countRows(Expense::class)); + } + + private function url(): string + { + return '/api/contacts/'.$this->ben->getId().'/import/splitwise'; + } + + private function previewUrl(): string + { + return $this->url().'/preview'; + } + + /** + * @return array + */ + private function sharesByEmail(Expense $expense): array + { + $shares = []; + foreach ($expense->getDebts() as $debt) { + $shares[(string) $debt->getPayer()->getEmail()] = $debt->getAmount(); + } + + ksort($shares); + + return $shares; + } + + /** + * @param class-string $entityClass + */ + private function countRows(string $entityClass): int + { + return (int) $this->getEntityManager()->createQueryBuilder() + ->select('COUNT(entity.id)') + ->from($entityClass, 'entity') + ->getQuery() + ->getSingleScalarResult(); + } + + private function getEntityManager(): EntityManagerInterface + { + return static::getContainer()->get(EntityManagerInterface::class); + } + + private static function header(): string + { + return "Note: does not include group expenses\n\nDate,Description,Category,Cost,Currency,Anna Kowalska,Ben Nowak\n\n"; + } + + private static function fixture(string $file): string + { + return (string) file_get_contents(__DIR__.'/../Support/fixtures/splitwise/'.$file); + } +} diff --git a/tests/Support/fixtures/splitwise/en.csv b/tests/Support/fixtures/splitwise/en.csv new file mode 100644 index 0000000..14e7086 --- /dev/null +++ b/tests/Support/fixtures/splitwise/en.csv @@ -0,0 +1,14 @@ +Note: does not include group expenses + +Date,Description,Category,Cost,Currency,Anna Kowalska,Ben Nowak + +2025-01-10,Groceries run,Groceries,100.00,PLN,50.00,-50.00 +2025-01-11,"Taxi, airport",Taxi,80.00,PLN,-80.00,80.00 +2025-01-12,Ben N. paid Anna K.,Payment,20.00,PLN,-20.00,20.00 +2025-01-13,Gift for mum,General,90.00,PLN,0.00,0.00 +2025-01-14,Dinner,Dining out,30.00,EUR,15.00,-15.00 +2025-01-15,Phone,TV/Phone/Internet,86.10,PLN,86.10,-86.10 +2025-01-15,Phone,TV/Phone/Internet,86.10,PLN,86.10,-86.10 + +2025-02-01,Total balance, , ,PLN,122.20,-122.20 +2025-02-01,Total balance, , ,EUR,15.00,-15.00 diff --git a/tests/Support/fixtures/splitwise/pl.csv b/tests/Support/fixtures/splitwise/pl.csv new file mode 100644 index 0000000..d02e58b --- /dev/null +++ b/tests/Support/fixtures/splitwise/pl.csv @@ -0,0 +1,14 @@ +Uwaga: Nie obejmuje wydatków grupy + +Data,Opis,Kategoria,Koszt,Waluta,Anna Kowalska,Ben Nowak + +2025-01-10,Groceries run,Artykuły spożywcze,100.00,PLN,50.00,-50.00 +2025-01-11,"Taxi, airport",Taxi,80.00,PLN,-80.00,80.00 +2025-01-12,Ben N. zapłacił(a) użytkownikowi Anna K.,Płatność,20.00,PLN,-20.00,20.00 +2025-01-13,Gift for mum,Ogólne,90.00,PLN,0.00,0.00 +2025-01-14,Dinner,Jedzenie na mieście,30.00,EUR,15.00,-15.00 +2025-01-15,Phone,TV/Telefon/Internet,86.10,PLN,86.10,-86.10 +2025-01-15,Phone,TV/Telefon/Internet,86.10,PLN,86.10,-86.10 + +2025-02-01,Całkowite saldo, , ,PLN,122.20,-122.20 +2025-02-01,Całkowite saldo, , ,EUR,15.00,-15.00 diff --git a/tests/Unit/Services/Splitwise/SplitwiseCsvParserTest.php b/tests/Unit/Services/Splitwise/SplitwiseCsvParserTest.php new file mode 100644 index 0000000..c92e024 --- /dev/null +++ b/tests/Unit/Services/Splitwise/SplitwiseCsvParserTest.php @@ -0,0 +1,90 @@ +parse(self::fixture($file)); + + $this->assertSame(['Anna Kowalska', 'Ben Nowak'], $export->names); + $this->assertCount(7, $export->rows); + $this->assertSame(['PLN' => ['122.20', '-122.20'], 'EUR' => ['15.00', '-15.00']], $export->totalsByCurrency); + + $taxi = $export->rows[1]; + $this->assertSame('2025-01-11', $taxi->date->format('Y-m-d')); + $this->assertSame('Taxi, airport', $taxi->description); + $this->assertSame('80.00', $taxi->cost); + $this->assertSame(['-80.00', '80.00'], $taxi->nets); + $this->assertSame($paymentCategory, $export->rows[2]->category); + } + + /** + * @return iterable + */ + public static function languageProvider(): iterable + { + yield 'English' => ['en.csv', 'Payment']; + yield 'Polish' => ['pl.csv', 'Płatność']; + } + + public function testStripsByteOrderMark(): void + { + $export = (new SplitwiseCsvParser())->parse("\xEF\xBB\xBF".self::fixture('en.csv')); + + $this->assertSame(['Anna Kowalska', 'Ben Nowak'], $export->names); + } + + public function testAcceptsExportWithoutRows(): void + { + $export = (new SplitwiseCsvParser())->parse(self::HEADER."2025-02-01,Total balance, , ,PLN,0.00,0.00\n"); + + $this->assertSame([], $export->rows); + } + + /** + * @dataProvider invalidProvider + */ + public function testRejectsFilesOfAnotherShape(string $csv): void + { + $this->expectException(UnprocessableEntityHttpException::class); + + (new SplitwiseCsvParser())->parse($csv); + } + + /** + * @return iterable + */ + public static function invalidProvider(): iterable + { + $total = "\n2025-02-01,Total balance, , ,PLN,10.00,-10.00\n"; + + yield 'empty' => ['']; + yield 'plain table' => ["Date,Description,Amount\n2025-01-10,Lunch,10.00\n"]; + yield 'group export with three people' => ["Note: does not include group expenses\n\nDate,Description,Category,Cost,Currency,Anna,Ben,Cleo\n"]; + yield 'blank name' => ["Note\n\nDate,Description,Category,Cost,Currency,Anna, \n\n"]; + yield 'bad date' => [self::HEADER.'10.01.2025,Lunch,General,10.00,PLN,10.00,-10.00'.$total]; + yield 'comma decimal' => [self::HEADER.'2025-01-10,Lunch,General,"10,00",PLN,10.00,-10.00'.$total]; + yield 'total without a currency' => [self::HEADER."2025-01-10,Lunch,General,10.00,PLN,10.00,-10.00\n\n2025-02-01,Total balance, , , ,10.00,-10.00\n"]; + yield 'short row' => [self::HEADER.'2025-01-10,Lunch,General,10.00,PLN'.$total]; + yield 'trailing junk' => [self::HEADER.'2025-01-10,Lunch,General,10.00,PLN,10.00,-10.00'.$total."something else\n"]; + yield 'duplicate total' => [self::HEADER.'2025-01-10,Lunch,General,10.00,PLN,10.00,-10.00'.$total."2025-02-01,Total balance, , ,PLN,10.00,-10.00\n"]; + } + + private static function fixture(string $file): string + { + return (string) file_get_contents(__DIR__.'/../../../Support/fixtures/splitwise/'.$file); + } +}