Propose a transaction split from an attached receipt

Closed
BH
1mo ago
+0-0

Problem

One card charge at a big-box or online retailer often covers several budget categories, like groceries, household and kids. Self-hosters already attach the receipt to the transaction. Today, splitting the charge still means typing every receipt line into the split editor and working out by hand how tax and coupons spread across the lines so the rows add up to the charge.

What changed

Split editor: when the transaction has a receipt the configured model can read (a PDF with any supported model, or a photo with a vision-capable one) and the user has AI enabled, the editor shows Fill from receipt. It re-renders the editor (same pattern as the bill smart-fill) with one row per receipt line. Nothing is saved: the user reviews names, amounts and categories, then submits the editor as usual.

[KEEP YOUR EXISTING BEFORE/AFTER SCREENSHOT TABLE HERE]

(Demo data, a text PDF receipt attached to a $62.00 Whole Foods charge. The provider response was stubbed locally because I had no live model key.)

Transaction::ReceiptItemizer turns the extraction into rows that Entry#split! accepts:

  • It spreads receipt-level tax and discounts over the items in proportion to their amounts.
  • It rounds each row to the currency's default_precision and puts the rounding residue on the largest item, so the rows always sum exactly to the transaction.
  • Any part of the transaction the receipt doesn't cover (a tip, a card fee, a line the model missed) becomes one more row named like the transaction. It isn't silently rescaled, and the editor says how much the receipt accounted for.
  • Inflows keep their sign. Refund receipts that print negative lines (and tax) are read by their magnitudes.
  • Tax already included in the line prices (VAT-style receipts, where the lines minus discounts equal the printed total) isn't added again.
  • A receipt whose currency differs from the transaction's is rejected with a clear reason instead of being read as the transaction currency.
  • Recoverable failures (the provider couldn't read the receipt, or the result can't be turned into a split) are recorded with DebugLogEntry.capture under receipt_itemization, with family, account and provider context and no receipt content. The web and API flows share this.

Providers: Provider::LlmConcept gains ReceiptExtraction / ReceiptLineItem (with a shared ReceiptExtraction.from_response parser), plus supports_receipt_extraction?(content_type:) (default false) and extract_receipt. The capability check is content-type aware: text PDFs are read as text, so they need only a supported chat model, while photos and image-only PDFs need a vision-capable model. Both LLM providers implement it:

  • OpenAI(-compatible), Provider::Openai::ReceiptExtractor:
    • Text PDFs (most emailed receipts) are sent as extracted text, so any supported chat model works (including text-only ones like gpt-4, or with OPENAI_SUPPORTS_PDF_PROCESSING=false), and they honor the JSON mode setting.
    • Photos go to the vision endpoint without response_format, the same choice the PDF vision path makes.
    • Scanned (image-only) PDFs are rendered to page images with pdftoppm (only the first 5 pages are rendered) and sent to the vision endpoint. The renderer moved out of PdfProcessor into Provider::Openai::Concerns::PdfPageRenderer unchanged, so both paths share it, including the coded render_missing_binary error.
    • The response cap is sent only when one is explicitly configured, because the 512-token budget fallback truncates long receipts.
  • Anthropic, Provider::Anthropic::ReceiptExtractor:
    • Text PDFs are sent as text. Photos go as native image blocks and image-only PDFs as native document blocks.
    • The result comes back through a forced tool call, like the other Anthropic extractors. Images over Anthropic's 5 MB limit and PDFs over the request limit are rejected before the call.
    • supports_receipt_extraction? takes the content type the same way: text PDFs need any supported model, while photos and image-only PDFs need supports_pdf_processing?. Usage is recorded before the tool input is parsed, so a failed parse still reports the billed tokens.
  • Parse failures raise a sanitized error that never quotes the model's output, because it holds receipt content and the message reaches logs and Langfuse.
  • Usage is recorded as extract_receipt (text) / extract_receipt_vision (images and scanned PDFs) on both providers.

API: POST /api/v1/transactions/:id/split/itemize (read_write scope, AI-enabled user, account write access; optional attachment_id) returns the proposal. Its split body can be sent to POST /api/v1/transactions/:id/split unchanged. Returns 422 with a reason when there is no readable receipt, the receipt's currency doesn't match, or the transaction can't be split.

The splits rswag spec now gives its account an owner. Without one, Account.accessible_by excluded the account and every documented example returned 404 when run.

Not included: suggesting a category per line. Rows come back uncategorized for the user to pick; that can be a follow-up if it's wanted.

How it was tested

  • test/models/transaction/receipt_itemizer_test.rb covers allocation math (tax, discount, residue, zero-decimal currencies), proposals that split! accepts, unmatched remainder, inflow sign, refund receipts, tax-inclusive receipts, currency mismatch, photo vs PDF availability on a text-only model, debug-log capture, and the failure paths.
  • test/models/provider/openai/receipt_extractor_test.rb covers the text-PDF, image and scanned-PDF request shapes, the page cap (including pdftoppm -l), lenient JSON parsing, text PDFs without vision, the vision requirement for photos and scanned PDFs, sanitized parse errors, the other errors, and renders a real image-only PDF through pdftoppm (skipped when poppler-utils isn't installed).
  • test/models/provider/anthropic/receipt_extractor_test.rb covers text, image and document blocks (including image/jpg → image/jpeg), tool parsing, usage recording (including once on a failed parse), a missing tool call, sanitized parse errors, the vision requirement, and the size and type guards. test/models/provider/anthropic_test.rb and test/models/provider/openai_test.rb cover the content-type-aware supports_receipt_extraction? and the provider response (including a text PDF on gpt-4).
  • test/controllers/splits_controller_test.rb covers the button, prefilled rows and input step at the currency's precision (including three-decimal KWD), nothing saved, the DS::Alert success and failure notices, and AI consent.
  • test/controllers/api/v1/splits_controller_test.rb covers the proposal round-tripping into POST .../split, 422, 401 without a key, 404 for unknown and malformed ids, AI consent and scope.
  • The existing PdfProcessor, AI health probe and admin system health tests pass unchanged after the renderer move.
  • I ran test/models/provider, the splits controller and API tests, test/models/transaction, test/models/ai_health, the admin system health tests and i18n_test on Ruby 3.4.9 with PostgreSQL and Redis: 1,240 runs, 0 failures, 0 errors.
  • bin/rubocop and erb_lint on the changed files are clean, and Brakeman reports no warnings. The endpoint's request and response shape didn't change in the review fixes, so docs/api/openapi.yaml is as before. It adds only this endpoint and schema.

Summary by CodeRabbit

  • New Features

    • Split transactions using line items extracted from attached receipt images or PDFs.
    • Review and adjust proposed splits before saving. Tax and discounts are distributed across items, with any unmatched amount shown separately.
    • API clients can request receipt-based split proposals without creating entries.
    • Receipt itemization is available when AI is enabled and the receipt format is supported.
  • Bug Fixes

    • Split amount fields now respect the transaction currency’s decimal precision.