From a5638a13bf766d1b686cddfb971189812f8fb1fc Mon Sep 17 00:00:00 2001 From: Ame <37273244+ame180@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:18:50 +0100 Subject: [PATCH 1/9] feat: import a Splitwise friend export into a contact's history --- .../Api/SplitwiseImportApiController.php | 66 +++++ src/Dto/SplitwiseImportPreview.php | 20 ++ src/Dto/SplitwiseImportRequest.php | 23 ++ src/Dto/SplitwiseImportSummary.php | 17 ++ src/Repository/ExpenseRepository.php | 18 ++ src/Repository/TransferRepository.php | 15 ++ .../Splitwise/SplitwiseCategoryMapper.php | 106 ++++++++ src/Services/Splitwise/SplitwiseCsvParser.php | 166 +++++++++++++ src/Services/Splitwise/SplitwiseExport.php | 48 ++++ .../Splitwise/SplitwiseImportService.php | 211 ++++++++++++++++ src/Services/Splitwise/SplitwiseRow.php | 21 ++ .../Api/SplitwiseImportApiControllerTest.php | 230 ++++++++++++++++++ tests/Support/fixtures/splitwise/en.csv | 14 ++ tests/Support/fixtures/splitwise/pl.csv | 14 ++ .../Splitwise/SplitwiseCsvParserTest.php | 105 ++++++++ 15 files changed, 1074 insertions(+) create mode 100644 src/Controller/Api/SplitwiseImportApiController.php create mode 100644 src/Dto/SplitwiseImportPreview.php create mode 100644 src/Dto/SplitwiseImportRequest.php create mode 100644 src/Dto/SplitwiseImportSummary.php create mode 100644 src/Services/Splitwise/SplitwiseCategoryMapper.php create mode 100644 src/Services/Splitwise/SplitwiseCsvParser.php create mode 100644 src/Services/Splitwise/SplitwiseExport.php create mode 100644 src/Services/Splitwise/SplitwiseImportService.php create mode 100644 src/Services/Splitwise/SplitwiseRow.php create mode 100644 tests/Api/SplitwiseImportApiControllerTest.php create mode 100644 tests/Support/fixtures/splitwise/en.csv create mode 100644 tests/Support/fixtures/splitwise/pl.csv create mode 100644 tests/Unit/Services/Splitwise/SplitwiseCsvParserTest.php diff --git a/src/Controller/Api/SplitwiseImportApiController.php b/src/Controller/Api/SplitwiseImportApiController.php new file mode 100644 index 0000000..def8078 --- /dev/null +++ b/src/Controller/Api/SplitwiseImportApiController.php @@ -0,0 +1,66 @@ + '\d+'])] + #[IsGranted('ROLE_USER')] + public function import( + int $userId, + #[MapRequestPayload(acceptFormat: 'json', validationFailedStatusCode: Response::HTTP_BAD_REQUEST)] + SplitwiseImportRequest $request, + #[MapQueryParameter] + bool $dryRun = false, + ): JsonResponse { + /** @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.'); + } + + if ($dryRun) { + return $this->json($this->importService->preview($user, $contact, $request->csv)); + } + + if (null === $request->ownColumn) { + throw new BadRequestHttpException('Choose which person in the file is you.'); + } + + return $this->json($this->importService->import($user, $contact, $request->csv, $request->ownColumn)); + } +} diff --git a/src/Dto/SplitwiseImportPreview.php b/src/Dto/SplitwiseImportPreview.php new file mode 100644 index 0000000..8e572fc --- /dev/null +++ b/src/Dto/SplitwiseImportPreview.php @@ -0,0 +1,20 @@ + $mismatches per currency, the file's rows minus its Total balance (first person's side) + * @param array{SplitwiseImportSummary, SplitwiseImportSummary} $options what importing would do if the user is the first or the second person + */ + public function __construct( + public array $names, + public array $mismatches, + public array $options, + ) { + } +} diff --git a/src/Dto/SplitwiseImportRequest.php b/src/Dto/SplitwiseImportRequest.php new file mode 100644 index 0000000..9186e2c --- /dev/null +++ b/src/Dto/SplitwiseImportRequest.php @@ -0,0 +1,23 @@ + + */ + 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..cc0ca04 --- /dev/null +++ b/src/Services/Splitwise/SplitwiseCategoryMapper.php @@ -0,0 +1,106 @@ + - Other" for the Other subcategories. Source: Splitwise's public + * GET /api/v3.0/get_categories with Accept-Language en and pl. + */ +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); + } + + /** Everything else (General, the rest of Life, unknown labels) is general. */ + 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..841a046 --- /dev/null +++ b/src/Services/Splitwise/SplitwiseCsvParser.php @@ -0,0 +1,166 @@ +readLines($csv); + + if (count($lines) < 4 || !$this->isNote($lines[0]) || !$this->isBlank($lines[1]) || self::COLUMNS !== count($lines[2]) || !$this->isBlank($lines[3])) { + throw $this->notAnExport(); + } + + $names = [trim((string) $lines[2][5]), trim((string) $lines[2][6])]; + if ('' === $names[0] || '' === $names[1]) { + throw $this->notAnExport(); + } + + $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, $net] = $this->parseTotal($line); + if (isset($totals[$currency])) { + throw $this->notAnExport(); + } + + $totals[$currency] = $net; + } + + 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 $this->notAnExport(); + } + + [$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 $this->notAnExport(); + } + + if (1 !== preg_match('/^[A-Z]{3}$/', $currency) || !$this->isDecimal($cost) || !$this->isDecimal($netA) || !$this->isDecimal($netB)) { + throw $this->notAnExport(); + } + + $absoluteNet = ltrim($netA, '-'); + if (0 !== bccomp(bcadd($netA, $netB, self::SCALE), '0', self::SCALE) + || bccomp($cost, '0', self::SCALE) < 0 + || bccomp($absoluteNet, $cost, self::SCALE) > 0) { + throw $this->notAnExport(); + } + + return new SplitwiseRow($parsedDate, $description, $category, $cost, $currency, [$netA, $netB]); + } + + /** + * @param list $line + * + * @return array{string, string} + */ + private function parseTotal(array $line): array + { + if (self::COLUMNS !== count($line)) { + throw $this->notAnExport(); + } + + $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])) { + throw $this->notAnExport(); + } + + return [$cells[4], $cells[5]]; + } + + /** + * @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); + } + + private function notAnExport(): UnprocessableEntityHttpException + { + return new UnprocessableEntityHttpException('The file is not a Splitwise friend export.'); + } +} diff --git a/src/Services/Splitwise/SplitwiseExport.php b/src/Services/Splitwise/SplitwiseExport.php new file mode 100644 index 0000000..a698322 --- /dev/null +++ b/src/Services/Splitwise/SplitwiseExport.php @@ -0,0 +1,48 @@ + $rows + * @param array $totalsByCurrency the first person's Total balance per currency + */ + public function __construct( + public array $names, + public array $rows, + public array $totalsByCurrency, + ) { + } + + /** + * Currencies whose rows don't add up to the file's own Total balance, with the difference + * (rows minus total) from the first person's side. + * + * @return list + */ + public function totalMismatches(): array + { + $sums = array_fill_keys(array_keys($this->totalsByCurrency), '0'); + foreach ($this->rows as $row) { + $sums[$row->currency] = bcadd($sums[$row->currency] ?? '0', $row->nets[0], SplitwiseCsvParser::SCALE); + } + + ksort($sums); + + $mismatches = []; + foreach ($sums as $currency => $sum) { + $difference = bcsub($sum, $this->totalsByCurrency[$currency] ?? '0', SplitwiseCsvParser::SCALE); + if (0 !== bccomp($difference, '0', SplitwiseCsvParser::SCALE)) { + $mismatches[] = new CurrencyAmount((string) $currency, bcadd($difference, '0', 2)); + } + } + + return $mismatches; + } +} diff --git a/src/Services/Splitwise/SplitwiseImportService.php b/src/Services/Splitwise/SplitwiseImportService.php new file mode 100644 index 0000000..d49f912 --- /dev/null +++ b/src/Services/Splitwise/SplitwiseImportService.php @@ -0,0 +1,211 @@ +parser->parse($csv); + + return new SplitwiseImportPreview( + names: $export->names, + mismatches: $export->totalMismatches(), + options: [ + $this->summarize($user, $contact, $this->plan($export, $user, $contact, 0)), + $this->summarize($user, $contact, $this->plan($export, $user, $contact, 1)), + ], + ); + } + + /** + * All or nothing: every row is written in one transaction. + * + * @param 0|1 $ownColumn + */ + public function import(User $user, User $contact, string $csv, int $ownColumn): SplitwiseImportSummary + { + $plan = $this->plan($this->parser->parse($csv), $user, $contact, $ownColumn); + $summary = $this->summarize($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; + } + + /** + * Builds (without persisting) what the import would add when the user is the person in + * $ownColumn. 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 + * + * @return array{items: list, skipped: int, ownNet: string} + */ + private function plan(SplitwiseExport $export, User $user, User $contact, int $ownColumn): array + { + $people = 0 === $ownColumn ? [$user, $contact] : [$contact, $user]; + $existing = $this->existingKeyCounts($user, $contact); + + $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 person owed paid the whole cost; the other owes their net, the rest is the payer's own share. + */ + 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; + } + + /** + * @param array{items: list, skipped: int, ownNet: string} $plan + */ + private function summarize(User $user, User $contact, 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($this->currentBalance($user, $contact), $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->url(dryRun: true), ['csv' => self::fixture('en.csv')]); + + $this->assertResponseStatusCodeSame(401); + } + + public function testDryRunDescribesBothSidesWithoutWriting(): void + { + $this->requestJson($this->client, 'POST', $this->url(dryRun: true), ['csv' => self::fixture('en.csv')]); + + $this->assertJsonResponseIsSuccessful(200); + $this->assertSame([ + 'names' => ['Anna Kowalska', 'Ben Nowak'], + 'mismatches' => [], + '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 testDryRunReportsTotalMismatch(): void + { + $csv = str_replace('PLN,122.20,-122.20', 'PLN,120.00,-120.00', self::fixture('en.csv')); + + $this->requestJson($this->client, 'POST', $this->url(dryRun: true), ['csv' => $csv]); + + $this->assertJsonResponseIsSuccessful(200); + $this->assertSame([['currency' => 'PLN', 'amount' => '2.20']], $this->getJsonResponse()['mismatches']); + } + + 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->url(dryRun: true), ['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 testRejectsFileOfAnotherShape(): void + { + $this->requestJson($this->client, 'POST', $this->url(dryRun: true), ['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(bool $dryRun = false): string + { + return '/api/contacts/'.$this->ben->getId().'/import/splitwise'.($dryRun ? '?dryRun=1' : ''); + } + + /** + * @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 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..b0aaa86 --- /dev/null +++ b/tests/Unit/Services/Splitwise/SplitwiseCsvParserTest.php @@ -0,0 +1,105 @@ +parse(self::fixture($file)); + + $this->assertSame(['Anna Kowalska', 'Ben Nowak'], $export->names); + $this->assertCount(7, $export->rows); + $this->assertSame(['PLN' => '122.20', 'EUR' => '15.00'], $export->totalsByCurrency); + $this->assertSame([], $export->totalMismatches()); + + $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 testReportsMismatchPerCurrency(): void + { + $csv = self::HEADER."2025-01-10,Lunch,General,10.00,PLN,10.00,-10.00\n2025-01-10,Taxi,General,8.00,EUR,4.00,-4.00\n\n" + ."2025-02-01,Total balance, , ,PLN,12.50,-12.50\n2025-02-01,Total balance, , ,EUR,4.00,-4.00\n"; + + $mismatches = (new SplitwiseCsvParser())->parse($csv)->totalMismatches(); + + $this->assertCount(1, $mismatches); + $this->assertSame('PLN', $mismatches[0]->currency); + $this->assertSame('-2.50', $mismatches[0]->amount); + } + + 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); + $this->assertSame([], $export->totalMismatches()); + } + + /** + * @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 'nets do not cancel out' => [self::HEADER.'2025-01-10,Lunch,General,10.00,PLN,10.00,-9.00'.$total]; + yield 'owed more than the cost' => [self::HEADER.'2025-01-10,Lunch,General,10.00,PLN,12.00,-12.00'.$total]; + 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); + } +} From e6a70605b37c1fb7afeb0353e2af0797759ccdc8 Mon Sep 17 00:00:00 2001 From: Ame <37273244+ame180@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:22:11 +0100 Subject: [PATCH 2/9] feat: import from Splitwise on Edit contact --- frontend/src/api/splitwiseImport.ts | 27 ++ frontend/src/api/types.ts | 17 + .../src/features/contacts/EditContactPage.tsx | 5 + .../contacts/SplitwiseImport.test.tsx | 139 +++++++ .../src/features/contacts/SplitwiseImport.tsx | 344 ++++++++++++++++++ frontend/src/locales/en.po | 98 +++++ frontend/src/locales/pl.po | 98 +++++ 7 files changed, 728 insertions(+) create mode 100644 frontend/src/api/splitwiseImport.ts create mode 100644 frontend/src/features/contacts/SplitwiseImport.test.tsx create mode 100644 frontend/src/features/contacts/SplitwiseImport.tsx diff --git a/frontend/src/api/splitwiseImport.ts b/frontend/src/api/splitwiseImport.ts new file mode 100644 index 0000000..bd1a4d5 --- /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)}?dryRun=1`, { + 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..773d2ac 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] + /** Per currency, how far the file's rows are off its own total. */ + mismatches: CurrencyAmount[] + /** 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..0f4fbb0 --- /dev/null +++ b/frontend/src/features/contacts/SplitwiseImport.test.tsx @@ -0,0 +1,139 @@ +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'], + mismatches: [], + 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 }) { + const fetchMock = vi.fn((input: string, init?: RequestInit) => { + if (init?.method === 'POST' && input.endsWith('?dryRun=1')) { + return Promise.resolve(jsonResponse(previewReply.status, previewReply.body)) + } + if (init?.method === 'POST') { + return Promise.resolve(jsonResponse(200, preview.options[0])) + } + 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('?dryRun=1')) + .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('offers Import anyway when the rows do not add up', async () => { + stubApi({ + status: 200, + body: { ...preview, mismatches: [{ currency: 'PLN', amount: '-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 isn’t a Splitwise friend 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..3f16e85 --- /dev/null +++ b/frontend/src/features/contacts/SplitwiseImport.tsx @@ -0,0 +1,344 @@ +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, formatMoney, formatPln } from '@/lib/money' +import { getShortName } from '@/lib/person' + +// Matches the server's limit on the CSV text. +const MAX_FILE_BYTES = 1_048_576 + +type OwnColumn = 0 | 1 + +/** A quiet row on Edit contact: pick a Splitwise friend export, confirm in a sheet, import. */ +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 ? ( + 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, + hint, + children, +}: { + message: string + hint?: string + children: ReactNode +}) { + return ( + <> +
+ {message} + {hint &&

{hint}

} +
+ {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.mismatches.length > 0 + const offBy = mismatchText(preview) + + 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 mismatchText(preview: SplitwiseImportPreview) { + return preview.mismatches + .map((mismatch) => formatMoney(mismatch.amount, mismatch.currency)) + .join(', ') +} + +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..0ee1062 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,30 @@ 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/contacts/SplitwiseImport.tsx +msgid "In Splitwise, open the friend → Export as spreadsheet." +msgstr "In Splitwise, open the friend → Export as spreadsheet." + #: src/features/auth/LoginPage.tsx msgid "Invalid email or password." msgstr "Invalid email or password." @@ -1046,6 +1123,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 +1486,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 +1546,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 isn’t a Splitwise friend export." +msgstr "This isn’t a Splitwise friend export." + #: src/app/ErrorPages.tsx msgid "This page doesn’t exist" msgstr "This page doesn’t exist" @@ -1504,6 +1597,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 +1649,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..b0a4cd9 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,30 @@ 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/contacts/SplitwiseImport.tsx +msgid "In Splitwise, open the friend → Export as spreadsheet." +msgstr "W Splitwise otwórz znajomego → Eksportuj jako arkusz kalkulacyjny." + #: src/features/auth/LoginPage.tsx msgid "Invalid email or password." msgstr "Nieprawidłowy e-mail lub hasło." @@ -1046,6 +1123,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 +1486,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 +1546,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 isn’t a Splitwise friend export." +msgstr "To nie jest eksport znajomego ze Splitwise." + #: src/app/ErrorPages.tsx msgid "This page doesn’t exist" msgstr "Ta strona nie istnieje" @@ -1504,6 +1597,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 +1649,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?" From 577f3f47da3789d869a9f4ea3793cf13c283b8b7 Mon Sep 17 00:00:00 2001 From: Ame <37273244+ame180@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:24:45 +0100 Subject: [PATCH 3/9] fix: pad the Splitwise picker when nothing is chosen yet --- frontend/src/features/contacts/SplitwiseImport.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/frontend/src/features/contacts/SplitwiseImport.tsx b/frontend/src/features/contacts/SplitwiseImport.tsx index 3f16e85..a36e668 100644 --- a/frontend/src/features/contacts/SplitwiseImport.tsx +++ b/frontend/src/features/contacts/SplitwiseImport.tsx @@ -19,6 +19,7 @@ import { } from '@/components/ui/sheet' import { balanceDirection, formatMoney, 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 @@ -225,7 +226,10 @@ function SummaryBody({ return ( <> -
+
Which one are you? From 317fbb62c73088435ab9946e5fc232159799c352 Mon Sep 17 00:00:00 2001 From: Ame <37273244+ame180@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:30:07 +0100 Subject: [PATCH 4/9] fix: address review findings on the Splitwise import --- .../contacts/SplitwiseImport.test.tsx | 21 +++++++++++++++++-- .../src/features/contacts/SplitwiseImport.tsx | 5 ++++- src/Dto/SplitwiseImportRequest.php | 2 +- src/Services/Splitwise/SplitwiseCsvParser.php | 12 +++++------ .../Splitwise/SplitwiseImportService.php | 20 ++++++++++-------- .../Splitwise/SplitwiseCsvParserTest.php | 2 ++ 6 files changed, 43 insertions(+), 19 deletions(-) diff --git a/frontend/src/features/contacts/SplitwiseImport.test.tsx b/frontend/src/features/contacts/SplitwiseImport.test.tsx index 0f4fbb0..38dedbf 100644 --- a/frontend/src/features/contacts/SplitwiseImport.test.tsx +++ b/frontend/src/features/contacts/SplitwiseImport.test.tsx @@ -25,13 +25,16 @@ const preview: SplitwiseImportPreview = { type Reply = { status: number; body: unknown } -function stubApi(previewReply: Reply = { status: 200, body: preview }) { +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('?dryRun=1')) { return Promise.resolve(jsonResponse(previewReply.status, previewReply.body)) } if (init?.method === 'POST') { - return Promise.resolve(jsonResponse(200, preview.options[0])) + return Promise.resolve(jsonResponse(importReply.status, importReply.body)) } return Promise.resolve(jsonResponse(200, { totals: [], items: [ania] })) }) @@ -92,6 +95,20 @@ describe('Splitwise import', () => { 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, diff --git a/frontend/src/features/contacts/SplitwiseImport.tsx b/frontend/src/features/contacts/SplitwiseImport.tsx index a36e668..d05feec 100644 --- a/frontend/src/features/contacts/SplitwiseImport.tsx +++ b/frontend/src/features/contacts/SplitwiseImport.tsx @@ -123,7 +123,10 @@ export function SplitwiseImport({ contact }: { contact: ContactListItem }) { contact={contact} preview={previewMutation.data} ownColumn={ownColumn} - onOwnColumnChange={setOwnColumn} + onOwnColumnChange={(column) => { + setOwnColumn(column) + importMutation.reset() + }} importing={importMutation.isPending} importFailed={importMutation.isError} onImport={runImport} diff --git a/src/Dto/SplitwiseImportRequest.php b/src/Dto/SplitwiseImportRequest.php index 9186e2c..defc20f 100644 --- a/src/Dto/SplitwiseImportRequest.php +++ b/src/Dto/SplitwiseImportRequest.php @@ -13,7 +13,7 @@ */ public function __construct( #[Assert\NotBlank] - #[Assert\Length(max: 1_048_576)] + #[Assert\Length(max: 1_048_576, countUnit: Assert\Length::COUNT_BYTES)] public string $csv, #[Assert\Choice([0, 1])] diff --git a/src/Services/Splitwise/SplitwiseCsvParser.php b/src/Services/Splitwise/SplitwiseCsvParser.php index 841a046..6276ca8 100644 --- a/src/Services/Splitwise/SplitwiseCsvParser.php +++ b/src/Services/Splitwise/SplitwiseCsvParser.php @@ -14,11 +14,13 @@ */ class SplitwiseCsvParser { - /** Splitwise writes 2 decimals; a little headroom keeps sums exact for 3-decimal currencies. */ + /** A third decimal is accepted so a file that also has a 3-decimal currency (skipped on import) still reads. */ public const int SCALE = 3; private const int COLUMNS = 7; private const string DECIMAL = '/^-?\d+(\.\d{1,3})?$/'; + /** The amount columns are DECIMAL(10,2). */ + private const string MAX_AMOUNT = '99999999.99'; public function parse(string $csv): SplitwiseExport { @@ -104,6 +106,7 @@ private function parseRow(array $line): SplitwiseRow $absoluteNet = ltrim($netA, '-'); if (0 !== bccomp(bcadd($netA, $netB, self::SCALE), '0', self::SCALE) || bccomp($cost, '0', self::SCALE) < 0 + || bccomp($cost, self::MAX_AMOUNT, self::SCALE) > 0 || bccomp($absoluteNet, $cost, self::SCALE) > 0) { throw $this->notAnExport(); } @@ -118,12 +121,9 @@ private function parseRow(array $line): SplitwiseRow */ private function parseTotal(array $line): array { - if (self::COLUMNS !== count($line)) { - throw $this->notAnExport(); - } - $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])) { + if (!$this->isTotal($line) || 1 !== preg_match('/^[A-Z]{3}$/', $cells[4]) || !$this->isDecimal($cells[5]) || !$this->isDecimal($cells[6]) + || 0 !== bccomp(bcadd($cells[5], $cells[6], self::SCALE), '0', self::SCALE)) { throw $this->notAnExport(); } diff --git a/src/Services/Splitwise/SplitwiseImportService.php b/src/Services/Splitwise/SplitwiseImportService.php index d49f912..7d0a1c1 100644 --- a/src/Services/Splitwise/SplitwiseImportService.php +++ b/src/Services/Splitwise/SplitwiseImportService.php @@ -38,13 +38,15 @@ public function __construct( public function preview(User $user, User $contact, string $csv): SplitwiseImportPreview { $export = $this->parser->parse($csv); + $existing = $this->existingKeyCounts($user, $contact); + $balance = $this->currentBalance($user, $contact); return new SplitwiseImportPreview( names: $export->names, mismatches: $export->totalMismatches(), options: [ - $this->summarize($user, $contact, $this->plan($export, $user, $contact, 0)), - $this->summarize($user, $contact, $this->plan($export, $user, $contact, 1)), + $this->summarize($balance, $this->plan($export, $user, $contact, 0, $existing)), + $this->summarize($balance, $this->plan($export, $user, $contact, 1, $existing)), ], ); } @@ -56,8 +58,8 @@ public function preview(User $user, User $contact, string $csv): SplitwiseImport */ public function import(User $user, User $contact, string $csv, int $ownColumn): SplitwiseImportSummary { - $plan = $this->plan($this->parser->parse($csv), $user, $contact, $ownColumn); - $summary = $this->summarize($user, $contact, $plan); + $plan = $this->plan($this->parser->parse($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) { @@ -76,14 +78,14 @@ public function import(User $user, User $contact, string $csv, int $ownColumn): * $ownColumn. 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 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 + private function plan(SplitwiseExport $export, User $user, User $contact, int $ownColumn, array $existing): array { $people = 0 === $ownColumn ? [$user, $contact] : [$contact, $user]; - $existing = $this->existingKeyCounts($user, $contact); $items = []; $skipped = 0; @@ -150,7 +152,7 @@ private function buildExpense(SplitwiseRow $row, User $payee, User $debtor, stri /** * @param array{items: list, skipped: int, ownNet: string} $plan */ - private function summarize(User $user, User $contact, array $plan): SplitwiseImportSummary + private function summarize(string $currentBalance, array $plan): SplitwiseImportSummary { $expenses = count(array_filter($plan['items'], static fn (Expense|Transfer $item): bool => $item instanceof Expense)); @@ -158,7 +160,7 @@ private function summarize(User $user, User $contact, array $plan): SplitwiseImp expenses: $expenses, transfers: count($plan['items']) - $expenses, skipped: $plan['skipped'], - balance: bcadd($this->currentBalance($user, $contact), $plan['ownNet'], 2), + balance: bcadd($currentBalance, $plan['ownNet'], 2), ); } diff --git a/tests/Unit/Services/Splitwise/SplitwiseCsvParserTest.php b/tests/Unit/Services/Splitwise/SplitwiseCsvParserTest.php index b0aaa86..9add973 100644 --- a/tests/Unit/Services/Splitwise/SplitwiseCsvParserTest.php +++ b/tests/Unit/Services/Splitwise/SplitwiseCsvParserTest.php @@ -92,6 +92,8 @@ public static function invalidProvider(): iterable 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 'nets do not cancel out' => [self::HEADER.'2025-01-10,Lunch,General,10.00,PLN,10.00,-9.00'.$total]; + yield 'cost beyond the amount column' => [self::HEADER.'2025-01-10,House,General,100000000.00,PLN,10.00,-10.00'.$total]; + yield 'total does not cancel out' => [self::HEADER."2025-01-10,Lunch,General,10.00,PLN,10.00,-10.00\n\n2025-02-01,Total balance, , ,PLN,10.00,-9.00\n"]; yield 'owed more than the cost' => [self::HEADER.'2025-01-10,Lunch,General,10.00,PLN,12.00,-12.00'.$total]; 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"]; From 3e553cf14b075ba4b022f597d4cceb3d2a99a9e1 Mon Sep 17 00:00:00 2001 From: Ame <37273244+ame180@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:31:16 +0100 Subject: [PATCH 5/9] fix: cap Splitwise amounts only on the PLN rows that get imported --- src/Services/Splitwise/SplitwiseCsvParser.php | 4 ++-- tests/Unit/Services/Splitwise/SplitwiseCsvParserTest.php | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/Services/Splitwise/SplitwiseCsvParser.php b/src/Services/Splitwise/SplitwiseCsvParser.php index 6276ca8..475079a 100644 --- a/src/Services/Splitwise/SplitwiseCsvParser.php +++ b/src/Services/Splitwise/SplitwiseCsvParser.php @@ -19,7 +19,7 @@ class SplitwiseCsvParser private const int COLUMNS = 7; private const string DECIMAL = '/^-?\d+(\.\d{1,3})?$/'; - /** The amount columns are DECIMAL(10,2). */ + /** The amount columns are DECIMAL(10,2); only PLN rows are written, so other currencies may exceed it. */ private const string MAX_AMOUNT = '99999999.99'; public function parse(string $csv): SplitwiseExport @@ -106,7 +106,7 @@ private function parseRow(array $line): SplitwiseRow $absoluteNet = ltrim($netA, '-'); if (0 !== bccomp(bcadd($netA, $netB, self::SCALE), '0', self::SCALE) || bccomp($cost, '0', self::SCALE) < 0 - || bccomp($cost, self::MAX_AMOUNT, self::SCALE) > 0 + || ('PLN' === $currency && bccomp($cost, self::MAX_AMOUNT, self::SCALE) > 0) || bccomp($absoluteNet, $cost, self::SCALE) > 0) { throw $this->notAnExport(); } diff --git a/tests/Unit/Services/Splitwise/SplitwiseCsvParserTest.php b/tests/Unit/Services/Splitwise/SplitwiseCsvParserTest.php index 9add973..b0bfcc7 100644 --- a/tests/Unit/Services/Splitwise/SplitwiseCsvParserTest.php +++ b/tests/Unit/Services/Splitwise/SplitwiseCsvParserTest.php @@ -60,6 +60,13 @@ public function testReportsMismatchPerCurrency(): void $this->assertSame('-2.50', $mismatches[0]->amount); } + public function testAcceptsLargeAmountsInOtherCurrencies(): void + { + $csv = self::HEADER."2025-01-10,Hotel,Hotel,150000000.00,VND,150000000.00,-150000000.00\n\n2025-02-01,Total balance, , ,VND,150000000.00,-150000000.00\n"; + + $this->assertCount(1, (new SplitwiseCsvParser())->parse($csv)->rows); + } + public function testAcceptsExportWithoutRows(): void { $export = (new SplitwiseCsvParser())->parse(self::HEADER."2025-02-01,Total balance, , ,PLN,0.00,0.00\n"); From 6a0358ffeec2af4e8a77e04bcd2cadaa64dc1d6a Mon Sep 17 00:00:00 2001 From: Ame <37273244+ame180@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:32:15 +0100 Subject: [PATCH 6/9] refactor: share the imported currency between the Splitwise parser and import --- src/Services/Splitwise/SplitwiseCsvParser.php | 2 +- src/Services/Splitwise/SplitwiseImportService.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Services/Splitwise/SplitwiseCsvParser.php b/src/Services/Splitwise/SplitwiseCsvParser.php index 475079a..e54a735 100644 --- a/src/Services/Splitwise/SplitwiseCsvParser.php +++ b/src/Services/Splitwise/SplitwiseCsvParser.php @@ -106,7 +106,7 @@ private function parseRow(array $line): SplitwiseRow $absoluteNet = ltrim($netA, '-'); if (0 !== bccomp(bcadd($netA, $netB, self::SCALE), '0', self::SCALE) || bccomp($cost, '0', self::SCALE) < 0 - || ('PLN' === $currency && bccomp($cost, self::MAX_AMOUNT, self::SCALE) > 0) + || (SplitwiseImportService::CURRENCY === $currency && bccomp($cost, self::MAX_AMOUNT, self::SCALE) > 0) || bccomp($absoluteNet, $cost, self::SCALE) > 0) { throw $this->notAnExport(); } diff --git a/src/Services/Splitwise/SplitwiseImportService.php b/src/Services/Splitwise/SplitwiseImportService.php index 7d0a1c1..948bdc8 100644 --- a/src/Services/Splitwise/SplitwiseImportService.php +++ b/src/Services/Splitwise/SplitwiseImportService.php @@ -22,7 +22,7 @@ */ class SplitwiseImportService { - private const string CURRENCY = 'PLN'; + public const string CURRENCY = 'PLN'; private const int TITLE_MAX_LENGTH = 255; public function __construct( From 1f9468a45ae31e11ab21027114c984bb1a5873da Mon Sep 17 00:00:00 2001 From: Ame <37273244+ame180@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:58:22 +0100 Subject: [PATCH 7/9] refactor: check only the PLN rows and total on Splitwise import and soften the wrong-file copy --- frontend/src/api/types.ts | 4 +- .../contacts/SplitwiseImport.test.tsx | 8 ++- .../src/features/contacts/SplitwiseImport.tsx | 31 ++------ frontend/src/locales/en.po | 8 +-- frontend/src/locales/pl.po | 8 +-- src/Dto/SplitwiseImportPreview.php | 8 +-- .../Splitwise/SplitwiseCategoryMapper.php | 5 +- src/Services/Splitwise/SplitwiseCsvParser.php | 41 ++++------- src/Services/Splitwise/SplitwiseExport.php | 34 +-------- .../Splitwise/SplitwiseImportService.php | 70 ++++++++++++++++--- .../UnsupportedSplitwiseExportException.php | 15 ++++ .../Api/SplitwiseImportApiControllerTest.php | 59 +++++++++++++++- .../Splitwise/SplitwiseCsvParserTest.php | 28 +------- 13 files changed, 173 insertions(+), 146 deletions(-) create mode 100644 src/Services/Splitwise/UnsupportedSplitwiseExportException.php diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index 773d2ac..7589b17 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -195,8 +195,8 @@ export type SplitwiseImportSummary = { export type SplitwiseImportPreview = { /** The file's two people, in column order. */ names: [string, string] - /** Per currency, how far the file's rows are off its own total. */ - mismatches: CurrencyAmount[] + /** 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] } diff --git a/frontend/src/features/contacts/SplitwiseImport.test.tsx b/frontend/src/features/contacts/SplitwiseImport.test.tsx index 38dedbf..19e31d2 100644 --- a/frontend/src/features/contacts/SplitwiseImport.test.tsx +++ b/frontend/src/features/contacts/SplitwiseImport.test.tsx @@ -16,7 +16,7 @@ const ania: ContactListItem = { const preview: SplitwiseImportPreview = { names: ['Ame Nowak', 'Anna Kowalska'], - mismatches: [], + mismatch: null, options: [ { expenses: 137, transfers: 44, skipped: 6, balance: '9642.18' }, { expenses: 3, transfers: 0, skipped: 184, balance: '-9642.18' }, @@ -112,7 +112,7 @@ describe('Splitwise import', () => { it('offers Import anyway when the rows do not add up', async () => { stubApi({ status: 200, - body: { ...preview, mismatches: [{ currency: 'PLN', amount: '-192.92' }] }, + body: { ...preview, mismatch: '-192.92' }, }) await chooseFile() @@ -142,7 +142,9 @@ describe('Splitwise import', () => { stubApi({ status: 422, body: { status: 422, title: 'Unprocessable Entity' } }) await chooseFile() - expect(await screen.findByText('This isn’t a Splitwise friend export.')).toBeInTheDocument() + expect( + await screen.findByText('This file isn’t a supported Splitwise export.'), + ).toBeInTheDocument() expect(screen.getByRole('button', { name: 'Choose another file' })).toBeInTheDocument() }) diff --git a/frontend/src/features/contacts/SplitwiseImport.tsx b/frontend/src/features/contacts/SplitwiseImport.tsx index d05feec..9388df0 100644 --- a/frontend/src/features/contacts/SplitwiseImport.tsx +++ b/frontend/src/features/contacts/SplitwiseImport.tsx @@ -17,7 +17,7 @@ import { SheetHeader, SheetTitle, } from '@/components/ui/sheet' -import { balanceDirection, formatMoney, formatPln } from '@/lib/money' +import { balanceDirection, formatPln } from '@/lib/money' import { getShortName } from '@/lib/person' import { cn } from '@/lib/utils' @@ -26,7 +26,6 @@ const MAX_FILE_BYTES = 1_048_576 type OwnColumn = 0 | 1 -/** A quiet row on Edit contact: pick a Splitwise friend export, confirm in a sheet, import. */ export function SplitwiseImport({ contact }: { contact: ContactListItem }) { const { t } = useLingui() const userId = contact.person.id @@ -134,10 +133,7 @@ export function SplitwiseImport({ contact }: { contact: ContactListItem }) { /> ) : previewMutation.isError ? ( isWrongFile(previewMutation.error) ? ( - + ) : ( @@ -173,20 +169,11 @@ function countsText(summary: SplitwiseImportSummary) { return translate`${expenses} and ${payments}` } -function StatusBody({ - message, - hint, - children, -}: { - message: string - hint?: string - children: ReactNode -}) { +function StatusBody({ message, children }: { message: string; children: ReactNode }) { return ( <> -
+
{message} - {hint &&

{hint}

}
{children} @@ -224,8 +211,8 @@ function SummaryBody({ }: SummaryBodyProps) { const { t } = useLingui() const summary = ownColumn === null ? null : preview.options[ownColumn] - const hasMismatch = preview.mismatches.length > 0 - const offBy = mismatchText(preview) + const hasMismatch = preview.mismatch !== null + const offBy = preview.mismatch === null ? '' : formatPln(preview.mismatch) return ( <> @@ -312,12 +299,6 @@ function SummaryBody({ ) } -function mismatchText(preview: SplitwiseImportPreview) { - return preview.mismatches - .map((mismatch) => formatMoney(mismatch.amount, mismatch.currency)) - .join(', ') -} - function SummaryText({ summary, ownName, diff --git a/frontend/src/locales/en.po b/frontend/src/locales/en.po index 0ee1062..625156a 100644 --- a/frontend/src/locales/en.po +++ b/frontend/src/locales/en.po @@ -879,10 +879,6 @@ msgstr "Imported {counts}" msgid "Importing…" msgstr "Importing…" -#: src/features/contacts/SplitwiseImport.tsx -msgid "In Splitwise, open the friend → Export as spreadsheet." -msgstr "In Splitwise, open the friend → Export as spreadsheet." - #: src/features/auth/LoginPage.tsx msgid "Invalid email or password." msgstr "Invalid email or password." @@ -1551,8 +1547,8 @@ msgid "This file is too large." msgstr "This file is too large." #: src/features/contacts/SplitwiseImport.tsx -msgid "This isn’t a Splitwise friend export." -msgstr "This isn’t a Splitwise friend export." +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" diff --git a/frontend/src/locales/pl.po b/frontend/src/locales/pl.po index b0a4cd9..45fdd68 100644 --- a/frontend/src/locales/pl.po +++ b/frontend/src/locales/pl.po @@ -879,10 +879,6 @@ msgstr "Zaimportowano: {counts}" msgid "Importing…" msgstr "Importowanie…" -#: src/features/contacts/SplitwiseImport.tsx -msgid "In Splitwise, open the friend → Export as spreadsheet." -msgstr "W Splitwise otwórz znajomego → Eksportuj jako arkusz kalkulacyjny." - #: src/features/auth/LoginPage.tsx msgid "Invalid email or password." msgstr "Nieprawidłowy e-mail lub hasło." @@ -1551,8 +1547,8 @@ msgid "This file is too large." msgstr "Ten plik jest za duży." #: src/features/contacts/SplitwiseImport.tsx -msgid "This isn’t a Splitwise friend export." -msgstr "To nie jest eksport znajomego ze Splitwise." +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" diff --git a/src/Dto/SplitwiseImportPreview.php b/src/Dto/SplitwiseImportPreview.php index 8e572fc..6a8e354 100644 --- a/src/Dto/SplitwiseImportPreview.php +++ b/src/Dto/SplitwiseImportPreview.php @@ -7,13 +7,13 @@ readonly class SplitwiseImportPreview { /** - * @param array{string, string} $names the file's two people, in column order - * @param list $mismatches per currency, the file's rows minus its Total balance (first person's side) - * @param array{SplitwiseImportSummary, SplitwiseImportSummary} $options what importing would do if the user is the first or the second person + * @param array{string, string} $names the file's two people, in column order + * @param ?string $mismatch how far the file's PLN rows are off its own PLN total; null when they agree + * @param array{SplitwiseImportSummary, SplitwiseImportSummary} $options what importing would do if the user is the first or the second person */ public function __construct( public array $names, - public array $mismatches, + public ?string $mismatch, public array $options, ) { } diff --git a/src/Services/Splitwise/SplitwiseCategoryMapper.php b/src/Services/Splitwise/SplitwiseCategoryMapper.php index cc0ca04..4ae40ac 100644 --- a/src/Services/Splitwise/SplitwiseCategoryMapper.php +++ b/src/Services/Splitwise/SplitwiseCategoryMapper.php @@ -8,8 +8,8 @@ /** * Splitwise category labels in English and Polish, as its exports write them: the subcategory - * name, or " - Other" for the Other subcategories. Source: Splitwise's public - * GET /api/v3.0/get_categories with Accept-Language en and pl. + * name, from Splitwise's public GET /api/v3.0/get_categories with Accept-Language en and pl. The + * Other subcategories were seen only as "Home - Other"; " - Other" is assumed for the rest. */ class SplitwiseCategoryMapper { @@ -98,7 +98,6 @@ public function isPayment(string $label): bool return in_array($label, self::PAYMENT_LABELS, true); } - /** Everything else (General, the rest of Life, unknown labels) is general. */ 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 index e54a735..86068f1 100644 --- a/src/Services/Splitwise/SplitwiseCsvParser.php +++ b/src/Services/Splitwise/SplitwiseCsvParser.php @@ -4,23 +4,17 @@ namespace App\Services\Splitwise; -use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException; - /** - * Reads a Splitwise friend export ("Export as spreadsheet" on a friend). Splitwise translates - * its labels, so the file is read by position: a note line, a blank line, a 7-column header - * ending in the two people's names, a blank line, the expense rows, a blank line, then one Total - * balance row per currency (with empty Category and Cost). + * Reads a Splitwise friend export. Splitwise translates its labels, so the file is read by + * position: a note line, a blank line, a 7-column header ending in the two people's names, a + * blank line, the expense rows, a blank line, then one Total balance row per currency (with empty + * Category and Cost). Only the shape is checked here; the amounts that get imported are checked + * on import. */ class SplitwiseCsvParser { - /** A third decimal is accepted so a file that also has a 3-decimal currency (skipped on import) still reads. */ - public const int SCALE = 3; - private const int COLUMNS = 7; - private const string DECIMAL = '/^-?\d+(\.\d{1,3})?$/'; - /** The amount columns are DECIMAL(10,2); only PLN rows are written, so other currencies may exceed it. */ - private const string MAX_AMOUNT = '99999999.99'; + private const string DECIMAL = '/^-?\d+(\.\d+)?$/'; public function parse(string $csv): SplitwiseExport { @@ -49,12 +43,12 @@ public function parse(string $csv): SplitwiseExport continue; } - [$currency, $net] = $this->parseTotal($line); + [$currency, $nets] = $this->parseTotal($line); if (isset($totals[$currency])) { throw $this->notAnExport(); } - $totals[$currency] = $net; + $totals[$currency] = $nets; } return new SplitwiseExport($names, $rows, $totals); @@ -103,31 +97,22 @@ private function parseRow(array $line): SplitwiseRow throw $this->notAnExport(); } - $absoluteNet = ltrim($netA, '-'); - if (0 !== bccomp(bcadd($netA, $netB, self::SCALE), '0', self::SCALE) - || bccomp($cost, '0', self::SCALE) < 0 - || (SplitwiseImportService::CURRENCY === $currency && bccomp($cost, self::MAX_AMOUNT, self::SCALE) > 0) - || bccomp($absoluteNet, $cost, self::SCALE) > 0) { - throw $this->notAnExport(); - } - return new SplitwiseRow($parsedDate, $description, $category, $cost, $currency, [$netA, $netB]); } /** * @param list $line * - * @return array{string, string} + * @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]) - || 0 !== bccomp(bcadd($cells[5], $cells[6], self::SCALE), '0', self::SCALE)) { + if (!$this->isTotal($line) || 1 !== preg_match('/^[A-Z]{3}$/', $cells[4]) || !$this->isDecimal($cells[5]) || !$this->isDecimal($cells[6])) { throw $this->notAnExport(); } - return [$cells[4], $cells[5]]; + return [$cells[4], [$cells[5], $cells[6]]]; } /** @@ -159,8 +144,8 @@ private function isDecimal(string $value): bool return 1 === preg_match(self::DECIMAL, $value); } - private function notAnExport(): UnprocessableEntityHttpException + private function notAnExport(): UnsupportedSplitwiseExportException { - return new UnprocessableEntityHttpException('The file is not a Splitwise friend export.'); + return new UnsupportedSplitwiseExportException(); } } diff --git a/src/Services/Splitwise/SplitwiseExport.php b/src/Services/Splitwise/SplitwiseExport.php index a698322..24a4134 100644 --- a/src/Services/Splitwise/SplitwiseExport.php +++ b/src/Services/Splitwise/SplitwiseExport.php @@ -4,14 +4,12 @@ namespace App\Services\Splitwise; -use App\Dto\CurrencyAmount; - readonly class SplitwiseExport { /** - * @param array{string, string} $names the two person columns, in file order - * @param list $rows - * @param array $totalsByCurrency the first person's Total balance per currency + * @param array{string, string} $names the two person columns, in file order + * @param list $rows + * @param array $totalsByCurrency the Total balance per currency, per person column */ public function __construct( public array $names, @@ -19,30 +17,4 @@ public function __construct( public array $totalsByCurrency, ) { } - - /** - * Currencies whose rows don't add up to the file's own Total balance, with the difference - * (rows minus total) from the first person's side. - * - * @return list - */ - public function totalMismatches(): array - { - $sums = array_fill_keys(array_keys($this->totalsByCurrency), '0'); - foreach ($this->rows as $row) { - $sums[$row->currency] = bcadd($sums[$row->currency] ?? '0', $row->nets[0], SplitwiseCsvParser::SCALE); - } - - ksort($sums); - - $mismatches = []; - foreach ($sums as $currency => $sum) { - $difference = bcsub($sum, $this->totalsByCurrency[$currency] ?? '0', SplitwiseCsvParser::SCALE); - if (0 !== bccomp($difference, '0', SplitwiseCsvParser::SCALE)) { - $mismatches[] = new CurrencyAmount((string) $currency, bcadd($difference, '0', 2)); - } - } - - return $mismatches; - } } diff --git a/src/Services/Splitwise/SplitwiseImportService.php b/src/Services/Splitwise/SplitwiseImportService.php index 948bdc8..f1b063d 100644 --- a/src/Services/Splitwise/SplitwiseImportService.php +++ b/src/Services/Splitwise/SplitwiseImportService.php @@ -22,8 +22,10 @@ */ class SplitwiseImportService { - public const string CURRENCY = 'PLN'; + private const string CURRENCY = 'PLN'; private const int TITLE_MAX_LENGTH = 255; + private const string AMOUNT = '/^-?\d+(\.\d{1,2})?$/'; + private const string MAX_AMOUNT = '99999999.99'; public function __construct( private readonly SplitwiseCsvParser $parser, @@ -37,13 +39,13 @@ public function __construct( public function preview(User $user, User $contact, string $csv): SplitwiseImportPreview { - $export = $this->parser->parse($csv); + $export = $this->read($csv); $existing = $this->existingKeyCounts($user, $contact); $balance = $this->currentBalance($user, $contact); return new SplitwiseImportPreview( names: $export->names, - mismatches: $export->totalMismatches(), + 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)), @@ -52,13 +54,11 @@ public function preview(User $user, User $contact, string $csv): SplitwiseImport } /** - * All or nothing: every row is written in one transaction. - * * @param 0|1 $ownColumn */ public function import(User $user, User $contact, string $csv, int $ownColumn): SplitwiseImportSummary { - $plan = $this->plan($this->parser->parse($csv), $user, $contact, $ownColumn, $this->existingKeyCounts($user, $contact)); + $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 { @@ -74,9 +74,8 @@ public function import(User $user, User $contact, string $csv, int $ownColumn): } /** - * Builds (without persisting) what the import would add when the user is the person in - * $ownColumn. 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. + * 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 @@ -123,7 +122,8 @@ private function plan(SplitwiseExport $export, User $user, User $contact, int $o } /** - * The person owed paid the whole cost; the other owes their net, the rest is the payer's own share. + * 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 { @@ -149,6 +149,56 @@ private function buildExpense(SplitwiseRow $row, User $payee, User $debtor, stri 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); + } + + /** The file's PLN rows minus its PLN Total balance, from the first person's side; null when they agree. */ + 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 */ diff --git a/src/Services/Splitwise/UnsupportedSplitwiseExportException.php b/src/Services/Splitwise/UnsupportedSplitwiseExportException.php new file mode 100644 index 0000000..fa365c2 --- /dev/null +++ b/src/Services/Splitwise/UnsupportedSplitwiseExportException.php @@ -0,0 +1,15 @@ +assertJsonResponseIsSuccessful(200); $this->assertSame([ 'names' => ['Anna Kowalska', 'Ben Nowak'], - 'mismatches' => [], + 'mismatch' => null, 'options' => [ ['expenses' => 4, 'transfers' => 1, 'skipped' => 2, 'balance' => '122.20'], ['expenses' => 4, 'transfers' => 1, 'skipped' => 2, 'balance' => '-122.20'], @@ -69,7 +69,7 @@ public function testDryRunReportsTotalMismatch(): void $this->requestJson($this->client, 'POST', $this->url(dryRun: true), ['csv' => $csv]); $this->assertJsonResponseIsSuccessful(200); - $this->assertSame([['currency' => 'PLN', 'amount' => '2.20']], $this->getJsonResponse()['mismatches']); + $this->assertSame('2.20', $this->getJsonResponse()['mismatch']); } public function testImportCreatesExpensesAndTransfersForTheChosenSide(): void @@ -166,6 +166,56 @@ public function testImportRequiresOwnColumn(): void $this->assertSame(0, $this->countRows(Expense::class)); } + public function testDryRunChecksOnlyThePlnTotal(): void + { + $csv = str_replace('EUR,15.00,-15.00', 'EUR,99.00,-99.00', self::fixture('en.csv')); + + $this->requestJson($this->client, 'POST', $this->url(dryRun: true), ['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->url(dryRun: true), ['csv' => "Date,Amount\n2025-01-10,10.00\n"]); @@ -223,6 +273,11 @@ 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/Unit/Services/Splitwise/SplitwiseCsvParserTest.php b/tests/Unit/Services/Splitwise/SplitwiseCsvParserTest.php index b0bfcc7..c92e024 100644 --- a/tests/Unit/Services/Splitwise/SplitwiseCsvParserTest.php +++ b/tests/Unit/Services/Splitwise/SplitwiseCsvParserTest.php @@ -21,8 +21,7 @@ public function testParsesExportByPosition(string $file, string $paymentCategory $this->assertSame(['Anna Kowalska', 'Ben Nowak'], $export->names); $this->assertCount(7, $export->rows); - $this->assertSame(['PLN' => '122.20', 'EUR' => '15.00'], $export->totalsByCurrency); - $this->assertSame([], $export->totalMismatches()); + $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')); @@ -48,31 +47,11 @@ public function testStripsByteOrderMark(): void $this->assertSame(['Anna Kowalska', 'Ben Nowak'], $export->names); } - public function testReportsMismatchPerCurrency(): void - { - $csv = self::HEADER."2025-01-10,Lunch,General,10.00,PLN,10.00,-10.00\n2025-01-10,Taxi,General,8.00,EUR,4.00,-4.00\n\n" - ."2025-02-01,Total balance, , ,PLN,12.50,-12.50\n2025-02-01,Total balance, , ,EUR,4.00,-4.00\n"; - - $mismatches = (new SplitwiseCsvParser())->parse($csv)->totalMismatches(); - - $this->assertCount(1, $mismatches); - $this->assertSame('PLN', $mismatches[0]->currency); - $this->assertSame('-2.50', $mismatches[0]->amount); - } - - public function testAcceptsLargeAmountsInOtherCurrencies(): void - { - $csv = self::HEADER."2025-01-10,Hotel,Hotel,150000000.00,VND,150000000.00,-150000000.00\n\n2025-02-01,Total balance, , ,VND,150000000.00,-150000000.00\n"; - - $this->assertCount(1, (new SplitwiseCsvParser())->parse($csv)->rows); - } - 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); - $this->assertSame([], $export->totalMismatches()); } /** @@ -98,10 +77,7 @@ public static function invalidProvider(): iterable 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 'nets do not cancel out' => [self::HEADER.'2025-01-10,Lunch,General,10.00,PLN,10.00,-9.00'.$total]; - yield 'cost beyond the amount column' => [self::HEADER.'2025-01-10,House,General,100000000.00,PLN,10.00,-10.00'.$total]; - yield 'total does not cancel out' => [self::HEADER."2025-01-10,Lunch,General,10.00,PLN,10.00,-10.00\n\n2025-02-01,Total balance, , ,PLN,10.00,-9.00\n"]; - yield 'owed more than the cost' => [self::HEADER.'2025-01-10,Lunch,General,10.00,PLN,12.00,-12.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"]; From cd780b986b189eed2af1df6280b6452e35262e45 Mon Sep 17 00:00:00 2001 From: Ame <37273244+ame180@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:05:31 +0100 Subject: [PATCH 8/9] refactor: give the Splitwise import preview its own endpoint --- frontend/src/api/splitwiseImport.ts | 2 +- .../contacts/SplitwiseImport.test.tsx | 4 +- .../Api/SplitwiseImportApiController.php | 40 +++++++++++-------- src/Dto/SplitwiseImportRequest.php | 8 ++-- src/Dto/SplitwisePreviewRequest.php | 17 ++++++++ .../Api/SplitwiseImportApiControllerTest.php | 27 ++++++++----- 6 files changed, 65 insertions(+), 33 deletions(-) create mode 100644 src/Dto/SplitwisePreviewRequest.php diff --git a/frontend/src/api/splitwiseImport.ts b/frontend/src/api/splitwiseImport.ts index bd1a4d5..d3cf089 100644 --- a/frontend/src/api/splitwiseImport.ts +++ b/frontend/src/api/splitwiseImport.ts @@ -10,7 +10,7 @@ function importPath(userId: number) { export function useSplitwiseImportPreview(userId: number) { return useMutation({ mutationFn: (csv: string) => - apiRequest(`${importPath(userId)}?dryRun=1`, { + apiRequest(`${importPath(userId)}/preview`, { method: 'POST', body: { csv }, }), diff --git a/frontend/src/features/contacts/SplitwiseImport.test.tsx b/frontend/src/features/contacts/SplitwiseImport.test.tsx index 19e31d2..1ad7ebf 100644 --- a/frontend/src/features/contacts/SplitwiseImport.test.tsx +++ b/frontend/src/features/contacts/SplitwiseImport.test.tsx @@ -30,7 +30,7 @@ function stubApi( importReply: Reply = { status: 200, body: preview.options[0] }, ) { const fetchMock = vi.fn((input: string, init?: RequestInit) => { - if (init?.method === 'POST' && input.endsWith('?dryRun=1')) { + if (init?.method === 'POST' && input.endsWith('/preview')) { return Promise.resolve(jsonResponse(previewReply.status, previewReply.body)) } if (init?.method === 'POST') { @@ -44,7 +44,7 @@ function stubApi( function importCalls(fetchMock: ReturnType) { return fetchMock.mock.calls - .filter(([input, init]) => init?.method === 'POST' && !input.endsWith('?dryRun=1')) + .filter(([input, init]) => init?.method === 'POST' && !input.endsWith('/preview')) .map(([input, init]) => [input, JSON.parse(String(init?.body))]) } diff --git a/src/Controller/Api/SplitwiseImportApiController.php b/src/Controller/Api/SplitwiseImportApiController.php index def8078..4d8e0a6 100644 --- a/src/Controller/Api/SplitwiseImportApiController.php +++ b/src/Controller/Api/SplitwiseImportApiController.php @@ -5,6 +5,7 @@ namespace App\Controller\Api; use App\Dto\SplitwiseImportRequest; +use App\Dto\SplitwisePreviewRequest; use App\Entity\User; use App\Repository\UserRepository; use App\Services\ContactService; @@ -12,7 +13,6 @@ use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\HttpKernel\Attribute\MapQueryParameter; use Symfony\Component\HttpKernel\Attribute\MapRequestPayload; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\Routing\Attribute\Route; @@ -28,19 +28,35 @@ public function __construct( ) { } - /** - * With dryRun=1 nothing is written and the response describes both ways the file's two - * people could map onto the pair; otherwise ownColumn picks one and the rows are imported. - */ + #[Route('/contacts/{userId}/import/splitwise/preview', name: 'api_contacts_import_splitwise_preview', methods: ['POST'], requirements: ['userId' => '\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, - #[MapQueryParameter] - bool $dryRun = false, ): 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(); @@ -53,14 +69,6 @@ public function import( throw $this->createNotFoundException('Contact not found.'); } - if ($dryRun) { - return $this->json($this->importService->preview($user, $contact, $request->csv)); - } - - if (null === $request->ownColumn) { - throw new BadRequestHttpException('Choose which person in the file is you.'); - } - - return $this->json($this->importService->import($user, $contact, $request->csv, $request->ownColumn)); + return [$user, $contact]; } } diff --git a/src/Dto/SplitwiseImportRequest.php b/src/Dto/SplitwiseImportRequest.php index defc20f..e2e887d 100644 --- a/src/Dto/SplitwiseImportRequest.php +++ b/src/Dto/SplitwiseImportRequest.php @@ -8,16 +8,18 @@ readonly class SplitwiseImportRequest { + public const int MAX_CSV_BYTES = 1_048_576; + /** - * @param 0|1|null $ownColumn which of the file's two person columns is the importing user; required unless dry run + * @param 0|1 $ownColumn which of the file's two person columns is the importing user */ public function __construct( #[Assert\NotBlank] - #[Assert\Length(max: 1_048_576, countUnit: Assert\Length::COUNT_BYTES)] + #[Assert\Length(max: self::MAX_CSV_BYTES, countUnit: Assert\Length::COUNT_BYTES)] public string $csv, #[Assert\Choice([0, 1])] - public ?int $ownColumn = null, + public int $ownColumn, ) { } } diff --git a/src/Dto/SplitwisePreviewRequest.php b/src/Dto/SplitwisePreviewRequest.php new file mode 100644 index 0000000..e299de0 --- /dev/null +++ b/src/Dto/SplitwisePreviewRequest.php @@ -0,0 +1,17 @@ +client; $client->restart(); - $this->requestJson($client, 'POST', $this->url(dryRun: true), ['csv' => self::fixture('en.csv')]); + $this->requestJson($client, 'POST', $this->previewUrl(), ['csv' => self::fixture('en.csv')]); $this->assertResponseStatusCodeSame(401); } - public function testDryRunDescribesBothSidesWithoutWriting(): void + public function testPreviewDescribesBothSidesWithoutWriting(): void { - $this->requestJson($this->client, 'POST', $this->url(dryRun: true), ['csv' => self::fixture('en.csv')]); + $this->requestJson($this->client, 'POST', $this->previewUrl(), ['csv' => self::fixture('en.csv')]); $this->assertJsonResponseIsSuccessful(200); $this->assertSame([ @@ -62,11 +62,11 @@ public function testDryRunDescribesBothSidesWithoutWriting(): void $this->assertSame(0, $this->countRows(Transfer::class)); } - public function testDryRunReportsTotalMismatch(): void + 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->url(dryRun: true), ['csv' => $csv]); + $this->requestJson($this->client, 'POST', $this->previewUrl(), ['csv' => $csv]); $this->assertJsonResponseIsSuccessful(200); $this->assertSame('2.20', $this->getJsonResponse()['mismatch']); @@ -126,7 +126,7 @@ 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->url(dryRun: true), ['csv' => self::fixture('en.csv')]); + $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]); @@ -166,11 +166,11 @@ public function testImportRequiresOwnColumn(): void $this->assertSame(0, $this->countRows(Expense::class)); } - public function testDryRunChecksOnlyThePlnTotal(): void + public function testPreviewChecksOnlyThePlnTotal(): void { $csv = str_replace('EUR,15.00,-15.00', 'EUR,99.00,-99.00', self::fixture('en.csv')); - $this->requestJson($this->client, 'POST', $this->url(dryRun: true), ['csv' => $csv]); + $this->requestJson($this->client, 'POST', $this->previewUrl(), ['csv' => $csv]); $this->assertJsonResponseIsSuccessful(200); $this->assertNull($this->getJsonResponse()['mismatch']); @@ -218,7 +218,7 @@ public static function unimportablePlnProvider(): iterable public function testRejectsFileOfAnotherShape(): void { - $this->requestJson($this->client, 'POST', $this->url(dryRun: true), ['csv' => "Date,Amount\n2025-01-10,10.00\n"]); + $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'); @@ -236,9 +236,14 @@ public function testRejectsUnrelatedUser(): void $this->assertSame(0, $this->countRows(Expense::class)); } - private function url(bool $dryRun = false): string + private function url(): string { - return '/api/contacts/'.$this->ben->getId().'/import/splitwise'.($dryRun ? '?dryRun=1' : ''); + return '/api/contacts/'.$this->ben->getId().'/import/splitwise'; + } + + private function previewUrl(): string + { + return $this->url().'/preview'; } /** From e5ab78b6c4e954c83d2a4928ecb49b1c2146d42c Mon Sep 17 00:00:00 2001 From: Ame <37273244+ame180@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:09:02 +0100 Subject: [PATCH 9/9] refactor: tidy the Splitwise parser after review --- src/Dto/SplitwiseImportPreview.php | 2 +- src/Services/Splitwise/SplitwiseCsvParser.php | 23 ++++++++----------- .../Splitwise/SplitwiseImportService.php | 1 - .../Api/SplitwiseImportApiControllerTest.php | 2 +- 4 files changed, 11 insertions(+), 17 deletions(-) diff --git a/src/Dto/SplitwiseImportPreview.php b/src/Dto/SplitwiseImportPreview.php index 6a8e354..f232e48 100644 --- a/src/Dto/SplitwiseImportPreview.php +++ b/src/Dto/SplitwiseImportPreview.php @@ -8,7 +8,7 @@ { /** * @param array{string, string} $names the file's two people, in column order - * @param ?string $mismatch how far the file's PLN rows are off its own PLN total; null when they agree + * @param ?string $mismatch the file's PLN rows minus its PLN total, first person's side; null when they agree * @param array{SplitwiseImportSummary, SplitwiseImportSummary} $options what importing would do if the user is the first or the second person */ public function __construct( diff --git a/src/Services/Splitwise/SplitwiseCsvParser.php b/src/Services/Splitwise/SplitwiseCsvParser.php index 86068f1..686428c 100644 --- a/src/Services/Splitwise/SplitwiseCsvParser.php +++ b/src/Services/Splitwise/SplitwiseCsvParser.php @@ -8,8 +8,8 @@ * Reads a Splitwise friend export. Splitwise translates its labels, so the file is read by * position: a note line, a blank line, a 7-column header ending in the two people's names, a * blank line, the expense rows, a blank line, then one Total balance row per currency (with empty - * Category and Cost). Only the shape is checked here; the amounts that get imported are checked - * on import. + * Category and Cost). Only the shape is checked here; SplitwiseImportService checks the PLN + * amounts. */ class SplitwiseCsvParser { @@ -21,12 +21,12 @@ public function parse(string $csv): SplitwiseExport $lines = $this->readLines($csv); if (count($lines) < 4 || !$this->isNote($lines[0]) || !$this->isBlank($lines[1]) || self::COLUMNS !== count($lines[2]) || !$this->isBlank($lines[3])) { - throw $this->notAnExport(); + throw new UnsupportedSplitwiseExportException(); } $names = [trim((string) $lines[2][5]), trim((string) $lines[2][6])]; if ('' === $names[0] || '' === $names[1]) { - throw $this->notAnExport(); + throw new UnsupportedSplitwiseExportException(); } $index = 4; @@ -45,7 +45,7 @@ public function parse(string $csv): SplitwiseExport [$currency, $nets] = $this->parseTotal($line); if (isset($totals[$currency])) { - throw $this->notAnExport(); + throw new UnsupportedSplitwiseExportException(); } $totals[$currency] = $nets; @@ -83,18 +83,18 @@ private function readLines(string $csv): array private function parseRow(array $line): SplitwiseRow { if (self::COLUMNS !== count($line)) { - throw $this->notAnExport(); + 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 $this->notAnExport(); + throw new UnsupportedSplitwiseExportException(); } if (1 !== preg_match('/^[A-Z]{3}$/', $currency) || !$this->isDecimal($cost) || !$this->isDecimal($netA) || !$this->isDecimal($netB)) { - throw $this->notAnExport(); + throw new UnsupportedSplitwiseExportException(); } return new SplitwiseRow($parsedDate, $description, $category, $cost, $currency, [$netA, $netB]); @@ -109,7 +109,7 @@ 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 $this->notAnExport(); + throw new UnsupportedSplitwiseExportException(); } return [$cells[4], [$cells[5], $cells[6]]]; @@ -143,9 +143,4 @@ private function isDecimal(string $value): bool { return 1 === preg_match(self::DECIMAL, $value); } - - private function notAnExport(): UnsupportedSplitwiseExportException - { - return new UnsupportedSplitwiseExportException(); - } } diff --git a/src/Services/Splitwise/SplitwiseImportService.php b/src/Services/Splitwise/SplitwiseImportService.php index f1b063d..38b456c 100644 --- a/src/Services/Splitwise/SplitwiseImportService.php +++ b/src/Services/Splitwise/SplitwiseImportService.php @@ -186,7 +186,6 @@ private function cancelsOut(array $nets): bool && 0 === bccomp(bcadd($nets[0], $nets[1], 2), '0', 2); } - /** The file's PLN rows minus its PLN Total balance, from the first person's side; null when they agree. */ private function totalMismatch(SplitwiseExport $export): ?string { $difference = bcsub('0', $export->totalsByCurrency[self::CURRENCY][0] ?? '0', 2); diff --git a/tests/Api/SplitwiseImportApiControllerTest.php b/tests/Api/SplitwiseImportApiControllerTest.php index 7c99cac..424286f 100644 --- a/tests/Api/SplitwiseImportApiControllerTest.php +++ b/tests/Api/SplitwiseImportApiControllerTest.php @@ -168,7 +168,7 @@ public function testImportRequiresOwnColumn(): void public function testPreviewChecksOnlyThePlnTotal(): void { - $csv = str_replace('EUR,15.00,-15.00', 'EUR,99.00,-99.00', self::fixture('en.csv')); + $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]);