Project: Rhea (macOS receipt extraction app) #
What it is #
A native macOS SwiftUI app that ingests scanned grocery-receipt PDFs, extracts structured data from each via a local vision model, lets the user review/edit the extraction against the source image, confirms it, and exports confirmed records to CSV or Postgres for analysis. (Formerly scaffolded as "ReceiptVault"; the app, bundle, and sources are now "Rhea".)
Stack & build #
- Swift 5 language mode, SwiftUI, macOS 14+.
- Xcode macOS App project, generated from
project.ymlby XcodeGen (the project is not committed;project.ymlis the source of truth). - Bundle identifier:
net.danieldaum.rhea. Product/app name:Rhea. - Architecture: MVVM. Views are dumb; state lives in a single
@Observable @MainActorview model (ReceiptsViewModel). - No third-party SPM/runtime dependencies — Apple frameworks only (SwiftUI, AppKit, PDFKit, Foundation,
Observation), with one deliberate exception: Sparkle 2 (
sparkle-project/Sparkle, pinned exact version inproject.yml'spackages:), added for in-app auto-updates (ticket #27) since Apple provides no first-party update mechanism outside the App Store. XcodeGen is a build-time dev tool installed via Homebrew, not an app dependency. - File layout:
Rhea/{Models,ViewModels,Views,Services}, plusRhea/Assets.xcassets.
Build & distribution #
- One-time:
brew install xcodegen. - Generate / regenerate the project:
xcodegen generate(writesRhea.xcodeproj). - Develop: open
Rhea.xcodeprojin Xcode and Run, orxcodebuild -project Rhea.xcodeproj -scheme Rhea -configuration Debug build. - Distribute a
.dmg: in Xcode, Product ▸ Archive ▸ Distribute App. A warning-free download requires a paid Developer ID signature + notarization (net.danieldaum.rhea). The project is currently set to ad-hoc "sign to run locally" (CODE_SIGN_IDENTITY = -); set your team / Developer ID inproject.yml(or the Signing & Capabilities tab) before notarizing. - Icon:
Rhea/Assets.xcassets/AppIcon.appiconset(generated fromPackaging/AppIcon.png, the 1024px master). Regenerate sizes withsipsif the master changes.
Critical conventions (learned the hard way) #
- Do not put editable line-item controls inside a SwiftUI
Form. On macOS,Formauto-converts titledTextFields into labeled rows (placeholder becomes a permanent label) and overrides.frame(width:), which breaks column alignment.ReceiptEditFormis a plainScrollView+VStackof cards with fixed-width columns instead. - Be lenient when decoding model output. Vision models emit off-type values (numeric
barcode/storeNumber, quoted decimals).Models/LenientDecoding.swiftcoerces String/number/null so one bad field never fails the whole receipt. RheaApp.swiftkeeps anNSApplicationDelegateAdaptorthat sets.regularactivation. As a proper.appthis is redundant (a bundled app is already foreground), but it's harmless and still lets the raw binary take keyboard focus if run directly. Keep it.- Keep the build green (
xcodebuild ... build) after each change. Swift 5 language mode (SWIFT_VERSION) is intentional — Swift 6 strict concurrency would flag the@MainActor/actor hand-offs.
File map #
project.yml— XcodeGen spec (target, bundle id, signing, icon, deployment target).Rhea/RheaApp.swift—@mainapp entry; AppDelegate activation; loads vault on launch; saves on background.Rhea/Assets.xcassets/AppIcon.appiconset— macOS app icon.Rhea/Models/Receipt.swift—Receipt,ExtractedReceipt,LineItem,ReceiptStatus(+ lenientCodable).Rhea/Models/ReceiptKeys.swift— computedReceipt.publicID,Receipt.naturalKey,LineItem.stableKey;slugComponent.Rhea/Models/LenientDecoding.swift—KeyedDecodingContainer.lenientString/lenientDecimal.Rhea/Models/AppEnums.swift—SidebarItem,ReceiptFilter.Rhea/ViewModels/ReceiptsViewModel.swift— state, import, sequential processing queue, confirm, delete, export.Rhea/Services/LocalStore.swift— durable on-disk store (Application Support).Rhea/Services/ExtractionService.swift— OpenAI-compatible vision call + JSON parsing + prompt.Rhea/Services/PDFService.swift— renders a PDF's first page to PNG.Rhea/Services/PersistenceStore.swift— persistence protocol.Rhea/Services/CSVExporter.swift,CSVStore.swift— CSV export.Rhea/Services/PostgresStore.swift,PostgresSQLExporter.swift— Postgres export viapsql+ schema constant.Rhea/Services/UpdaterService.swift— SparkleSPUStandardUpdaterControllerwrapper +UpdaterViewModelfor the "Check for Updates…" menu item.Rhea/Info.plist— partial plist merged into theGENERATE_INFOPLIST_FILE-generated one; holdsSUFeedURL/SUPublicEDKey, which aren't keys Xcode recognizes asINFOPLIST_KEY_*synonyms.Rhea/Views/—ReceiptListView,ReceiptDetailView,ReceiptEditForm,SidebarView,SettingsView,ResizableSplitView.Packaging/AppIcon.png— 1024px icon master.
Data model #
Receipt: id (UUID), sourceURL (URL — points at the in-vault copy), pageImage (Data?), status
(queued/inProgress/done/failed), extracted (ExtractedReceipt?), confirmed (Bool),
errorMessage (String?), and processing timestamps submittedAt/startedAt/finishedAt (Date?).
- Computed:
publicID=rcpt_<uuid, no dashes>;naturalKey=chain_storeNumber_date_receiptNumber(slugified, falls back topublicIDwhen parts are missing).
ExtractedReceipt: merchant, chain?, storeNumber?, storeAddress?, date (ISO-8601),
receiptNumber?, total (Decimal), tax?, paymentMethod?, lineItems.
LineItem: name (receipt-printed), aiCommonName? (model's normalized suggestion), userCommonName?
(user's own normalized name), category?, barcode?, quantity?, unitPrice?, weightLbs?,
pricePerLb?, listPrice?, pricePaid?, lineTotal?.
- Computed:
stableKey(receiptKey:index:)=barcode_<barcode>when present, else<receiptKey>_itemNN. - The model emits
commonName; decoding maps that (and legacy savedcommonName) intoaiCommonName.
Persistence (LocalStore) #
Durable store under ~/Library/Application Support/Rhea/:
Store/<uuid>.json— receipt record (metadata + extracted + timing; image bytes excluded).Files/<uuid>/<originalName>— copy of the imported PDF (so nothing depends on the user's file location).Files/<uuid>/page.png— rendered page image used by the UI and the model.
Atomic writes. The vault is the single source of truth: loaded on launch, saved on every mutation, and
removed (record + files) on delete. There is no seeded sample data; first launch starts empty.
CSVStore/PostgresSQLExporter are export-only (load() returns []).
Import + sequential processing queue #
- Importing one or many PDFs (toolbar ⌘O or drag-and-drop) copies each into the vault, renders its page,
enqueues it as
queuedwithsubmittedAt, and kicks the queue. processQueue()is reentrancy-guarded and drainsqueuedreceipts one at a time in import order: stampsstartedAt+inProgress, calls extraction, then setsdone/failed+finishedAt, persisting each step.- Re-process re-enqueues an item (clears extraction/error, unconfirms). Items left
inProgressby a crash are re-queued and resumed on next launch. queuePosition(for:)andprocessingDuration(for:)drive the list'sN/Mindicator and count-up timer.
Status flow #
queued → inProgress → done (shown as blue "Processed") → user clicks Confirm → confirmed
(green). Detail fields are editable while unconfirmed and lock once confirmed.
Extraction (ExtractionService) #
- OpenAI-compatible chat-completions endpoint with vision (LM Studio / oMLX). Endpoint + model name are configurable in Settings.
- Uses
response_format: { type: "text" }(the server rejectsjson_object); the prompt demands a single JSON object andextractJSON()strips fences/prose before decoding.
UI #
Three-pane NavigationSplitView:
- LEFT (
SidebarView): Receipts / Settings, with a badge counting queued + in-progress. - CENTER (
ReceiptListView): aTablewith columns Receipt / Date / Total / Status / Time.- Top segmented filter (
ReceiptFilter): All / Queued / Processed / Confirmed / Failed. - Status pill: gray "Queued", orange spinner + "Processing" with
N/Mposition, blue "Processed", green "Confirmed", red "Failed". Time column counts up live while processing, then shows final duration. - Right-click context menu: Extract / Re-process, Confirm / Unconfirm, Reveal Source in Finder, and Delete (permanent, removes on-disk files, behind a confirmation dialog).
- Top segmented filter (
- RIGHT (
ReceiptDetailView):- Failed → selectable/copyable error pane (with a Copy button).
- Extracted →
ResizableHSplit: source PDF image on the left,ReceiptEditFormon the right. - Pending → image plus a status banner (queued shows
N/M; in-progress shows a spinner + elapsed time).
ReceiptEditForm (review/validation surface) #
Plain ScrollView of cards (no Form):
- Receipt Details card: read-only, copyable
Receipt ID+Key, then editable receipt fields. - Line Items card, one row per item:
- Left (identity): item name (primary), "Your common name" (editable), the AI suggestion as a distinct
blue accent (outlined
AImark + text, with a one-tap "use" affordance), and tertiary category (small color dot + muted text) + barcode in their own aligned columns. - Right (pricing): fixed-width columns so values line up across rows —
qty × ea(orwt @ /lb), the bold line total, and the struck original price all share one right edge.
- Left (identity): item name (primary), "Your common name" (editable), the AI suggestion as a distinct
blue accent (outlined
ResizableHSplit(ResizableSplitView.swift) is a custom divider that shows the resize cursor on hover.
Export (from Settings) #
Only confirmed receipts with extracted data are exported.
- CSV (
CSVExporter) →~/Documents/Rhea/receipts.csv, one row per line item. Columns includeRECEIPT_ID,RECEIPT_KEY,ITEM_KEY, the store/receipt fields,ITEM,AI_COMMON_NAME,COMMON_NAME(the user's value), and weight/qty/price columns. - Postgres (
PostgresStore) → upserts viapsqlintoreceipts+receipt_line_items, which now carryreceipt_key,item_key,ai_common_name, andcommon_name(user). Schema usesALTER TABLE ... ADD COLUMN IF NOT EXISTSso older databases upgrade in place.PostgresSQLExporterholds the schema constant shown in Settings.
Auto-updates (Sparkle) #
UpdaterServicewrapsSPUStandardUpdaterController;RheaAppadds a "Check for Updates…" item to the app menu (CommandGroup(after: .appInfo)) bound toUpdaterViewModel.canCheckForUpdates.SUEnableAutomaticChecksis deliberately not set — Sparkle shows its own one-time consent alert on first launch rather than the app silently opting the user into background checks.SUFeedURL/SUPublicEDKeylive inRhea/Info.plist(see File map) rather than asINFOPLIST_KEY_*build settings, since Xcode doesn't recognize those as generated-Info.plist synonyms.- Stable feed URL: each tagged release's
appcast.xmlis uploaded as a release asset (per-release URL, changes every tag) and force-pushed to a dedicated orphan branchappcast-feed(.gitea/workflows/release.yml, "Publish appcast to stable feed branch" step).SUFeedURLpoints at that branch's raw file (.../raw/branch/appcast-feed/appcast.xml), which is the one URL that never changes. Gitea has no GitHub-style/releases/latest/download/<asset>redirect (confirmed 404), which is why this exists instead of pointingSUFeedURLstraight at a release asset. - The feed is single-item (current release only, no history) — Sparkle only needs the newest
sparkle:versionto compare against the running app.
Change log #
- Filters & statuses: top filter is now All / Queued / Processed / Confirmed / Failed; the post-extraction
donestate is labeled blue "Processed", green only after the user confirms. - Right-click context menu in the list: Extract / Re-process, Confirm / Unconfirm, Reveal Source in Finder, Delete (with confirmation).
- Durable local storage (
LocalStore) under Application Support — JSON record + copied original PDF + rendered PNG per receipt. Removed the old per-launch sample data; the vault is authoritative across quits/crashes. - Editable details before confirm, with read-only
Receipt ID(rcpt_…) and naturalKeysurfaced. - Keyboard input fix: activation-policy AppDelegate so text fields accept typing.
- Extraction 400 fix: switched
response_formattotext. - Robust decoding: lenient String/number/null coercion for model type drift.
- Copyable error pane for failed receipts.
- ID/key system: prefixed
publicID, compositenaturalKey, per-itemstableKey— all flow into exports. - AI vs. user common name: split into read-only
aiCommonName+ editableuserCommonName; both exported. - Bulk upload + sequential auto-processing queue with spinner,
N/Mposition, and count-up timer. - Line-items redesign: off
Form, fixed-width aligned pricing columns, clear hierarchy, blue AI accent, quiet category dots. - Renamed ReceiptVault → Rhea across package, sources, app struct, display strings, and storage paths.
- Converted to a real Xcode macOS App (XcodeGen
project.yml), with a generated app icon and bundle idnet.danieldaum.rhea, so it builds/archives as a distributable.app/.dmg. - Schema v2 for cross-retailer analysis (authoritative DDL in
db/schema.sql; loader indb/load_baseline.sh):purchase_date DATE(was TEXT), UNIQUEreceipt_keywith upserts keyed on it (prevents baseline + Rhea double-inserts), line items getline_no/item_code/raw_name(was name/item_key/barcode), newline_type(item/deposit/fee/refund/discount/non_grocery) to keep deposits/fees out of price stats, generated columnseffective_unit+effective_unit_pricenormalizing per-lb vs per-each pricing, aproductsdimension (canonicalcommon_namevocabulary), and analysis views (v_prices,v_price_comparison,v_price_history,v_monthly_spend,v_receipt_qc).LineItemgainedlineType(lenient-decoded;effectiveLineTypedefaults to "item"); the extraction prompt demands weight lines be extracted (never default by-weight items to qty 1) and classifies lineType. Both Postgres paths (PostgresStore,PostgresSQLExporter) now emit ALL columns (the old exporter dropped common names/weights). Old prototype databases must be dropped — v2 is not migration-compatible. - Prompt hardening from the 146-receipt baseline run (
ExtractionService): weight/qty modifier lines can print above OR below their item (attach by weight×rate arithmetic); savings lines are attributed by Price/You-Pay arithmetic, not adjacency; multi-buy deals use average unit price; voided lines become negativerefundlines; mandatory self-check that line items (+tax) sum to the printed total before answering;commonNameconvention aligned with the DB products vocabulary (lowercase, 1-4 words, brand-free, keep organic/fat/boneless qualifiers). Chain examples now include GROCERY OUTLET and PIEDMONT GROCERY. The baseline dataset/pipeline lives inreceipts_raw/(extraction spec, per-receipt JSONs,qc.py,assemble.py,products_map.csv) and loads viadb/baseline_full.sqlordb/load_baseline.sh; analysis queries indb/analysis_queries.sql. - Sparkle 2 auto-updates (ticket #27, first third-party dependency — see "Stack & build" exception):
UpdaterService+ "Check for Updates…" menu item;SUFeedURL/SUPublicEDKeymerged into the generated Info.plist viaRhea/Info.plist; release workflow force-pushes each release'sappcast.xmlto a dedicatedappcast-feedbranch so Sparkle has one stable feed URL (Gitea has no "latest release asset" redirect). See "Auto-updates (Sparkle)" above for details.
Working agreement #
- Keep the build green (
xcodebuild ... build) after each change; runxcodegen generateafter editingproject.yml. - When unsure about a requirement, ask before inventing scope.
- Preserve the conventions in "Critical conventions" above; they encode bugs already fixed.