rheaarchived
- 40 commits
- 1 branch
- 0 tags
- updated
CLAUDE.md
16.3 KB · 217 lines
1# Project: Rhea (macOS receipt extraction app)23## What it is4A native macOS SwiftUI app that ingests scanned grocery-receipt PDFs, extracts structured5data from each via a local vision model, lets the user review/edit the extraction against the6source image, confirms it, and exports confirmed records to CSV or Postgres for analysis.7(Formerly scaffolded as "ReceiptVault"; the app, bundle, and sources are now "Rhea".)89## Stack & build10- Swift 5 language mode, SwiftUI, macOS 14+.11- **Xcode macOS App project**, generated from `project.yml` by **XcodeGen** (the project is *not*12 committed; `project.yml` is the source of truth).13- Bundle identifier: `net.danieldaum.rhea`. Product/app name: `Rhea`.14- Architecture: MVVM. Views are dumb; state lives in a single `@Observable @MainActor` view model (`ReceiptsViewModel`).15- No third-party SPM/runtime dependencies — Apple frameworks only (SwiftUI, AppKit, PDFKit, Foundation,16 Observation), with one deliberate exception: **Sparkle 2** (`sparkle-project/Sparkle`, pinned exact17 version in `project.yml`'s `packages:`), added for in-app auto-updates (ticket #27) since Apple provides18 no first-party update mechanism outside the App Store. XcodeGen is a build-time dev tool installed via19 Homebrew, not an app dependency.20- File layout: `Rhea/{Models,ViewModels,Views,Services}`, plus `Rhea/Assets.xcassets`.2122## Build & distribution23- One-time: `brew install xcodegen`.24- Generate / regenerate the project: `xcodegen generate` (writes `Rhea.xcodeproj`).25- Develop: open `Rhea.xcodeproj` in Xcode and Run, or26 `xcodebuild -project Rhea.xcodeproj -scheme Rhea -configuration Debug build`.27- Distribute a `.dmg`: in Xcode, **Product ▸ Archive ▸ Distribute App**. A warning-free download28 requires a paid **Developer ID** signature + **notarization** (`net.danieldaum.rhea`). The project is29 currently set to ad-hoc "sign to run locally" (`CODE_SIGN_IDENTITY = -`); set your team / Developer ID in30 `project.yml` (or the Signing & Capabilities tab) before notarizing.31- Icon: `Rhea/Assets.xcassets/AppIcon.appiconset` (generated from `Packaging/AppIcon.png`, the 1024px32 master). Regenerate sizes with `sips` if the master changes.3334## Critical conventions (learned the hard way)35- **Do not put editable line-item controls inside a SwiftUI `Form`.** On macOS, `Form` auto-converts titled36 `TextField`s into labeled rows (placeholder becomes a permanent label) and overrides `.frame(width:)`,37 which breaks column alignment. `ReceiptEditForm` is a plain `ScrollView` + `VStack` of cards with38 fixed-width columns instead.39- **Be lenient when decoding model output.** Vision models emit off-type values (numeric `barcode`/40 `storeNumber`, quoted decimals). `Models/LenientDecoding.swift` coerces String/number/null so one bad41 field never fails the whole receipt.42- `RheaApp.swift` keeps an `NSApplicationDelegateAdaptor` that sets `.regular` activation. As a proper43 `.app` this is redundant (a bundled app is already foreground), but it's harmless and still lets the raw44 binary take keyboard focus if run directly. Keep it.45- Keep the build green (`xcodebuild ... build`) after each change. Swift 5 language mode (`SWIFT_VERSION`)46 is intentional — Swift 6 strict concurrency would flag the `@MainActor`/actor hand-offs.4748## File map49- `project.yml` — XcodeGen spec (target, bundle id, signing, icon, deployment target).50- `Rhea/RheaApp.swift` — `@main` app entry; AppDelegate activation; loads vault on launch; saves on background.51- `Rhea/Assets.xcassets/AppIcon.appiconset` — macOS app icon.52- `Rhea/Models/Receipt.swift` — `Receipt`, `ExtractedReceipt`, `LineItem`, `ReceiptStatus` (+ lenient `Codable`).53- `Rhea/Models/ReceiptKeys.swift` — computed `Receipt.publicID`, `Receipt.naturalKey`, `LineItem.stableKey`; `slugComponent`.54- `Rhea/Models/LenientDecoding.swift` — `KeyedDecodingContainer.lenientString/lenientDecimal`.55- `Rhea/Models/AppEnums.swift` — `SidebarItem`, `ReceiptFilter`.56- `Rhea/ViewModels/ReceiptsViewModel.swift` — state, import, sequential processing queue, confirm, delete, export.57- `Rhea/Services/LocalStore.swift` — durable on-disk store (Application Support).58- `Rhea/Services/ExtractionService.swift` — OpenAI-compatible vision call + JSON parsing + prompt.59- `Rhea/Services/PDFService.swift` — renders a PDF's first page to PNG.60- `Rhea/Services/PersistenceStore.swift` — persistence protocol.61- `Rhea/Services/CSVExporter.swift`, `CSVStore.swift` — CSV export.62- `Rhea/Services/PostgresStore.swift`, `PostgresSQLExporter.swift` — Postgres export via `psql` + schema constant.63- `Rhea/Services/UpdaterService.swift` — Sparkle `SPUStandardUpdaterController` wrapper + `UpdaterViewModel`64 for the "Check for Updates…" menu item.65- `Rhea/Info.plist` — partial plist merged into the `GENERATE_INFOPLIST_FILE`-generated one; holds66 `SUFeedURL`/`SUPublicEDKey`, which aren't keys Xcode recognizes as `INFOPLIST_KEY_*` synonyms.67- `Rhea/Views/` — `ReceiptListView`, `ReceiptDetailView`, `ReceiptEditForm`, `SidebarView`, `SettingsView`, `ResizableSplitView`.68- `Packaging/AppIcon.png` — 1024px icon master.6970## Data model71`Receipt`: `id` (UUID), `sourceURL` (URL — points at the in-vault copy), `pageImage` (Data?), `status`72(`queued`/`inProgress`/`done`/`failed`), `extracted` (`ExtractedReceipt?`), `confirmed` (Bool),73`errorMessage` (String?), and processing timestamps `submittedAt`/`startedAt`/`finishedAt` (Date?).74- Computed: `publicID` = `rcpt_<uuid, no dashes>`; `naturalKey` = `chain_storeNumber_date_receiptNumber`75 (slugified, falls back to `publicID` when parts are missing).7677`ExtractedReceipt`: `merchant`, `chain?`, `storeNumber?`, `storeAddress?`, `date` (ISO-8601),78`receiptNumber?`, `total` (Decimal), `tax?`, `paymentMethod?`, `lineItems`.7980`LineItem`: `name` (receipt-printed), `aiCommonName?` (model's normalized suggestion), `userCommonName?`81(user's own normalized name), `category?`, `barcode?`, `quantity?`, `unitPrice?`, `weightLbs?`,82`pricePerLb?`, `listPrice?`, `pricePaid?`, `lineTotal?`.83- Computed: `stableKey(receiptKey:index:)` = `barcode_<barcode>` when present, else `<receiptKey>_itemNN`.84- The model emits `commonName`; decoding maps that (and legacy saved `commonName`) into `aiCommonName`.8586## Persistence (`LocalStore`)87Durable store under `~/Library/Application Support/Rhea/`:88- `Store/<uuid>.json` — receipt record (metadata + extracted + timing; image bytes excluded).89- `Files/<uuid>/<originalName>` — copy of the imported PDF (so nothing depends on the user's file location).90- `Files/<uuid>/page.png` — rendered page image used by the UI and the model.9192Atomic writes. The vault is the single source of truth: loaded on launch, saved on every mutation, and93removed (record + files) on delete. There is no seeded sample data; first launch starts empty.94`CSVStore`/`PostgresSQLExporter` are export-only (`load()` returns `[]`).9596## Import + sequential processing queue97- Importing one or many PDFs (toolbar ⌘O or drag-and-drop) copies each into the vault, renders its page,98 enqueues it as `queued` with `submittedAt`, and kicks the queue.99- `processQueue()` is reentrancy-guarded and drains `queued` receipts **one at a time** in import order:100 stamps `startedAt` + `inProgress`, calls extraction, then sets `done`/`failed` + `finishedAt`, persisting101 each step.102- Re-process re-enqueues an item (clears extraction/error, unconfirms). Items left `inProgress` by a crash103 are re-queued and resumed on next launch.104- `queuePosition(for:)` and `processingDuration(for:)` drive the list's `N/M` indicator and count-up timer.105106## Status flow107`queued` → `inProgress` → `done` (shown as blue **"Processed"**) → user clicks **Confirm** → `confirmed`108(green). Detail fields are editable while unconfirmed and lock once confirmed.109110## Extraction (`ExtractionService`)111- OpenAI-compatible chat-completions endpoint with vision (LM Studio / oMLX). Endpoint + model name are112 configurable in Settings.113- Uses `response_format: { type: "text" }` (the server rejects `json_object`); the prompt demands a single114 JSON object and `extractJSON()` strips fences/prose before decoding.115116## UI117Three-pane `NavigationSplitView`:118- **LEFT** (`SidebarView`): Receipts / Settings, with a badge counting queued + in-progress.119- **CENTER** (`ReceiptListView`): a `Table` with columns Receipt / Date / Total / Status / Time.120 - Top segmented filter (`ReceiptFilter`): **All / Queued / Processed / Confirmed / Failed**.121 - Status pill: gray "Queued", orange spinner + "Processing" with `N/M` position, blue "Processed",122 green "Confirmed", red "Failed". Time column counts up live while processing, then shows final duration.123 - Right-click context menu: Extract / Re-process, Confirm / Unconfirm, Reveal Source in Finder, and Delete124 (permanent, removes on-disk files, behind a confirmation dialog).125- **RIGHT** (`ReceiptDetailView`):126 - Failed → selectable/copyable error pane (with a Copy button).127 - Extracted → `ResizableHSplit`: source PDF image on the left, `ReceiptEditForm` on the right.128 - Pending → image plus a status banner (queued shows `N/M`; in-progress shows a spinner + elapsed time).129130### `ReceiptEditForm` (review/validation surface)131Plain `ScrollView` of cards (no `Form`):132- **Receipt Details** card: read-only, copyable `Receipt ID` + `Key`, then editable receipt fields.133- **Line Items** card, one row per item:134 - Left (identity): item name (primary), "Your common name" (editable), the **AI suggestion** as a distinct135 blue accent (outlined `AI` mark + text, with a one-tap "use" affordance), and tertiary category136 (small color dot + muted text) + barcode in their own aligned columns.137 - Right (pricing): fixed-width columns so values line up across rows — `qty × ea` (or `wt @ /lb`), the138 bold line total, and the struck original price all share one right edge.139- `ResizableHSplit` (`ResizableSplitView.swift`) is a custom divider that shows the resize cursor on hover.140141## Export (from Settings)142Only confirmed receipts with extracted data are exported.143- **CSV** (`CSVExporter`) → `~/Documents/Rhea/receipts.csv`, one row per line item. Columns include144 `RECEIPT_ID`, `RECEIPT_KEY`, `ITEM_KEY`, the store/receipt fields, `ITEM`, `AI_COMMON_NAME`,145 `COMMON_NAME` (the user's value), and weight/qty/price columns.146- **Postgres** (`PostgresStore`) → upserts via `psql` into `receipts` + `receipt_line_items`, which now carry147 `receipt_key`, `item_key`, `ai_common_name`, and `common_name` (user). Schema uses148 `ALTER TABLE ... ADD COLUMN IF NOT EXISTS` so older databases upgrade in place. `PostgresSQLExporter`149 holds the schema constant shown in Settings.150151## Auto-updates (Sparkle)152- `UpdaterService` wraps `SPUStandardUpdaterController`; `RheaApp` adds a "Check for Updates…" item to the153 app menu (`CommandGroup(after: .appInfo)`) bound to `UpdaterViewModel.canCheckForUpdates`.154- `SUEnableAutomaticChecks` is deliberately not set — Sparkle shows its own one-time consent alert on first155 launch rather than the app silently opting the user into background checks.156- `SUFeedURL`/`SUPublicEDKey` live in `Rhea/Info.plist` (see File map) rather than as `INFOPLIST_KEY_*`157 build settings, since Xcode doesn't recognize those as generated-Info.plist synonyms.158- **Stable feed URL**: each tagged release's `appcast.xml` is uploaded as a release asset (per-release URL,159 changes every tag) *and* force-pushed to a dedicated orphan branch `appcast-feed`160 (`.gitea/workflows/release.yml`, "Publish appcast to stable feed branch" step). `SUFeedURL` points at that161 branch's raw file (`.../raw/branch/appcast-feed/appcast.xml`), which is the one URL that never changes.162 Gitea has no GitHub-style `/releases/latest/download/<asset>` redirect (confirmed 404), which is why this163 exists instead of pointing `SUFeedURL` straight at a release asset.164- The feed is single-item (current release only, no history) — Sparkle only needs the newest165 `sparkle:version` to compare against the running app.166167## Change log1681. **Filters & statuses:** top filter is now All / Queued / Processed / Confirmed / Failed; the post-extraction169 `done` state is labeled blue **"Processed"**, green only after the user confirms.1702. **Right-click context menu** in the list: Extract / Re-process, Confirm / Unconfirm, Reveal Source in Finder,171 Delete (with confirmation).1723. **Durable local storage** (`LocalStore`) under Application Support — JSON record + copied original PDF +173 rendered PNG per receipt. Removed the old per-launch sample data; the vault is authoritative across174 quits/crashes.1754. **Editable details before confirm**, with read-only `Receipt ID` (`rcpt_…`) and natural `Key` surfaced.1765. **Keyboard input fix:** activation-policy AppDelegate so text fields accept typing.1776. **Extraction 400 fix:** switched `response_format` to `text`.1787. **Robust decoding:** lenient String/number/null coercion for model type drift.1798. **Copyable error pane** for failed receipts.1809. **ID/key system:** prefixed `publicID`, composite `naturalKey`, per-item `stableKey` — all flow into exports.18110. **AI vs. user common name:** split into read-only `aiCommonName` + editable `userCommonName`; both exported.18211. **Bulk upload + sequential auto-processing queue** with spinner, `N/M` position, and count-up timer.18312. **Line-items redesign:** off `Form`, fixed-width aligned pricing columns, clear hierarchy, blue AI accent,184 quiet category dots.18513. **Renamed ReceiptVault → Rhea** across package, sources, app struct, display strings, and storage paths.18614. **Converted to a real Xcode macOS App** (XcodeGen `project.yml`), with a generated app icon and bundle id187 `net.danieldaum.rhea`, so it builds/archives as a distributable `.app`/`.dmg`.18815. **Schema v2 for cross-retailer analysis** (authoritative DDL in `db/schema.sql`; loader in189 `db/load_baseline.sh`): `purchase_date DATE` (was TEXT), UNIQUE `receipt_key` with upserts keyed on it190 (prevents baseline + Rhea double-inserts), line items get `line_no`/`item_code`/`raw_name` (was191 name/item_key/barcode), new `line_type` (`item`/`deposit`/`fee`/`refund`/`discount`/`non_grocery`) to keep192 deposits/fees out of price stats, generated columns `effective_unit` + `effective_unit_price` normalizing193 per-lb vs per-each pricing, a `products` dimension (canonical `common_name` vocabulary), and analysis views194 (`v_prices`, `v_price_comparison`, `v_price_history`, `v_monthly_spend`, `v_receipt_qc`).195 `LineItem` gained `lineType` (lenient-decoded; `effectiveLineType` defaults to "item"); the extraction196 prompt demands weight lines be extracted (never default by-weight items to qty 1) and classifies lineType.197 Both Postgres paths (`PostgresStore`, `PostgresSQLExporter`) now emit ALL columns (the old exporter dropped198 common names/weights). Old prototype databases must be dropped — v2 is not migration-compatible.19916. **Prompt hardening from the 146-receipt baseline run** (`ExtractionService`): weight/qty modifier200 lines can print above OR below their item (attach by weight×rate arithmetic); savings lines are201 attributed by Price/You-Pay arithmetic, not adjacency; multi-buy deals use average unit price;202 voided lines become negative `refund` lines; mandatory self-check that line items (+tax) sum to the203 printed total before answering; `commonName` convention aligned with the DB products vocabulary204 (lowercase, 1-4 words, brand-free, keep organic/fat/boneless qualifiers). Chain examples now include205 GROCERY OUTLET and PIEDMONT GROCERY. The baseline dataset/pipeline lives in `receipts_raw/`206 (extraction spec, per-receipt JSONs, `qc.py`, `assemble.py`, `products_map.csv`) and loads via207 `db/baseline_full.sql` or `db/load_baseline.sh`; analysis queries in `db/analysis_queries.sql`.20817. **Sparkle 2 auto-updates** (ticket #27, first third-party dependency — see "Stack & build" exception):209 `UpdaterService` + "Check for Updates…" menu item; `SUFeedURL`/`SUPublicEDKey` merged into the generated210 Info.plist via `Rhea/Info.plist`; release workflow force-pushes each release's `appcast.xml` to a211 dedicated `appcast-feed` branch so Sparkle has one stable feed URL (Gitea has no "latest release asset"212 redirect). See "Auto-updates (Sparkle)" above for details.213214## Working agreement215- Keep the build green (`xcodebuild ... build`) after each change; run `xcodegen generate` after editing `project.yml`.216- When unsure about a requirement, ask before inventing scope.217- Preserve the conventions in "Critical conventions" above; they encode bugs already fixed.