projects

rheaarchived

A grocery receipt scanning application

chore: ignore personal receipt data and macos cruft

daniel daum committed parent 38da4b8 commit 7d54450Signed, not verified

SignedGitea couldn't verify the signature.

Showing 4 changed files with 661 additions and 0 deletions.

.gitignore +13 −0
@@ -72,3 +72,16 @@ claude.md7272build/7373dist/7474DerivedData/7576# macOS77.DS_Store7879# Personal receipt data — never commit real purchase/receipt data.80# receipts_raw/ is the local baseline extraction pipeline's working data81# (scans, per-receipt JSON, extracted CSVs). db/baseline/ and82# db/baseline_full.sql are generated data dumps loaded from it. Schema/83# tooling under db/ (schema.sql, load_baseline.sh, analysis_queries.sql)84# stay tracked — only the generated data below is excluded.85receipts_raw/86db/baseline/87db/baseline_full.sql
db/analysis_queries.sqladded +342 −0
@@ -0,0 +1,342 @@1-- ============================================================2-- Rhea analytical queries3-- Each query stands alone — paste into Metabase (native question)4-- or Jupyter. All build on v_prices / base tables; line_type5-- filtering is already handled by the views.6-- ============================================================78-- ------------------------------------------------------------9-- 1. TOTAL SPEND10-- ------------------------------------------------------------1112-- 1a. All-time grocery spend13SELECT SUM(total) AS total_spend, COUNT(*) AS n_receipts14FROM receipts;1516-- 1b. Spend per month (Metabase line chart)17SELECT date_trunc('month', purchase_date)::date AS month,18       SUM(total) AS spend,19       COUNT(*)   AS trips20FROM receipts21GROUP BY 1 ORDER BY 1;2223-- 1c. Spend by month AND chain (stacked bar)24SELECT date_trunc('month', purchase_date)::date AS month,25       chain,26       SUM(total) AS spend27FROM receipts28GROUP BY 1, 2 ORDER BY 1, 2;2930-- 1d. Spend by category (uses normalized product category)31SELECT COALESCE(product_category, 'unmapped') AS category,32       SUM(price_paid) AS spend,33       COUNT(*)        AS n_purchases34FROM v_prices35GROUP BY 1 ORDER BY spend DESC;3637-- ------------------------------------------------------------38-- 2. RETAILER BREAKDOWN39-- ------------------------------------------------------------4041-- 2a. Which retailer gets our money42SELECT chain,43       SUM(total)                   AS spend,44       COUNT(*)                     AS trips,45       ROUND(AVG(total), 2)         AS avg_basket,46       MIN(purchase_date)           AS first_trip,47       MAX(purchase_date)           AS last_trip48FROM receipts49GROUP BY chain ORDER BY spend DESC;5051-- 2b. Share of wallet over time (100% stacked area in Metabase)52SELECT date_trunc('month', purchase_date)::date AS month,53       chain,54       SUM(total) AS spend55FROM receipts56GROUP BY 1, 2 ORDER BY 1;5758-- ------------------------------------------------------------59-- 3. WHAT WE BUY MOST60-- ------------------------------------------------------------6162-- 3a. Most frequently purchased products63SELECT product,64       COUNT(*)                    AS times_bought,65       SUM(price_paid)             AS total_spent,66       COUNT(DISTINCT chain)       AS chains_bought_at67FROM v_prices68GROUP BY product69ORDER BY times_bought DESC70LIMIT 30;7172-- 3b. Where the money actually goes (by product)73SELECT product,74       SUM(price_paid) AS total_spent,75       COUNT(*)        AS times_bought76FROM v_prices77GROUP BY product78ORDER BY total_spent DESC79LIMIT 30;8081-- 3c. Pounds purchased of by-weight staples82SELECT product,83       ROUND(SUM(weight_lbs), 1)          AS total_lbs,84       ROUND(SUM(price_paid), 2)          AS total_spent,85       ROUND(SUM(price_paid) / NULLIF(SUM(weight_lbs), 0), 2) AS blended_price_per_lb86FROM v_prices87WHERE effective_unit = 'lb'88GROUP BY product89ORDER BY total_lbs DESC90LIMIT 20;9192-- ------------------------------------------------------------93-- 4. CROSS-RETAILER PRICE COMPARISON (the point of all this)94-- ------------------------------------------------------------9596-- 4a. Head-to-head: products bought at 2+ chains, cheapest vs priciest chain97WITH per_chain AS (98    SELECT product, effective_unit, chain,99           AVG(effective_unit_price) AS avg_price,100           COUNT(*)                  AS n101    FROM v_prices102    WHERE effective_unit_price IS NOT NULL103    GROUP BY 1, 2, 3104),105spread AS (106    SELECT product, effective_unit,107           COUNT(*)                                        AS n_chains,108           MIN(avg_price)                                  AS cheapest,109           MAX(avg_price)                                  AS priciest110    FROM per_chain111    GROUP BY 1, 2112    HAVING COUNT(*) >= 2113)114SELECT s.product,115       s.effective_unit,116       cheap.chain                                          AS cheapest_at,117       ROUND(s.cheapest, 2)                                 AS cheapest_price,118       exp.chain                                            AS priciest_at,119       ROUND(s.priciest, 2)                                 AS priciest_price,120       ROUND(100.0 * (s.priciest - s.cheapest) / s.cheapest, 0) AS pct_premium121FROM spread s122JOIN per_chain cheap ON cheap.product = s.product AND cheap.effective_unit = s.effective_unit123                    AND cheap.avg_price = s.cheapest124JOIN per_chain exp   ON exp.product = s.product   AND exp.effective_unit = s.effective_unit125                    AND exp.avg_price = s.priciest126ORDER BY pct_premium DESC;127128-- 4b. Single product deep-dive (swap the product name; Metabase: make it a filter variable)129SELECT chain, purchase_date, raw_name,130       effective_unit, effective_unit_price,131       weight_lbs, quantity, price_paid, on_sale132FROM v_prices133WHERE product = 'bananas'   -- or: product LIKE '%yogurt%'134ORDER BY purchase_date;135136-- 4c. Which chain "wins" the most products (is cheapest most often)137WITH per_chain AS (138    SELECT product, chain, AVG(effective_unit_price) AS avg_price139    FROM v_prices140    WHERE effective_unit_price IS NOT NULL141    GROUP BY 1, 2142),143ranked AS (144    SELECT product, chain,145           RANK() OVER (PARTITION BY product ORDER BY avg_price) AS rnk,146           COUNT(*) OVER (PARTITION BY product) AS n_chains147    FROM per_chain148)149SELECT chain,150       COUNT(*) AS products_cheapest_at151FROM ranked152WHERE rnk = 1 AND n_chains >= 2153GROUP BY chain154ORDER BY products_cheapest_at DESC;155156-- 4d. The organic premium: same product organic vs not, per lb157WITH base AS (158    SELECT REPLACE(product, 'organic ', '') AS base_product,159           is_organic,160           AVG(effective_unit_price)        AS avg_price161    FROM v_prices162    WHERE effective_unit = 'lb' AND effective_unit_price IS NOT NULL163    GROUP BY 1, 2164)165SELECT o.base_product,166       ROUND(c.avg_price, 2)  AS conventional_per_lb,167       ROUND(o.avg_price, 2)  AS organic_per_lb,168       ROUND(100.0 * (o.avg_price - c.avg_price) / c.avg_price, 0) AS organic_premium_pct169FROM base o170JOIN base c ON c.base_product = o.base_product171           AND o.is_organic IS TRUE AND c.is_organic IS FALSE172ORDER BY organic_premium_pct DESC;173174-- ------------------------------------------------------------175-- 5. SHOPPING FREQUENCY & HABITS176-- ------------------------------------------------------------177178-- 5a. How often we shop (trips per week, overall and by chain)179SELECT chain,180       COUNT(*)                                            AS trips,181       ROUND(COUNT(*)::numeric /182             NULLIF((MAX(purchase_date) - MIN(purchase_date)) / 7.0, 0), 2) AS trips_per_week183FROM receipts184GROUP BY chain ORDER BY trips DESC;185186-- 5b. Days between trips (overall cadence)187WITH gaps AS (188    SELECT purchase_date - LAG(purchase_date) OVER (ORDER BY purchase_date) AS gap189    FROM receipts190)191SELECT ROUND(AVG(gap), 1)                 AS avg_days_between_trips,192       PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY gap) AS median_gap,193       MAX(gap)                           AS longest_gap194FROM gaps WHERE gap IS NOT NULL;195196-- 5c. Day-of-week habits197SELECT to_char(purchase_date, 'Dy') AS dow,198       COUNT(*)                     AS trips,199       ROUND(AVG(total), 2)         AS avg_basket200FROM receipts201GROUP BY 1, EXTRACT(dow FROM purchase_date)202ORDER BY EXTRACT(dow FROM purchase_date);203204-- 5d. Repurchase cadence per product (how often do we rebuy bananas?)205WITH gaps AS (206    SELECT product,207           purchase_date - LAG(purchase_date) OVER (PARTITION BY product ORDER BY purchase_date) AS gap208    FROM v_prices209)210SELECT product,211       COUNT(*) + 1                    AS times_bought,212       ROUND(AVG(gap), 1)              AS avg_days_between213FROM gaps214WHERE gap IS NOT NULL215GROUP BY product216HAVING COUNT(*) >= 4217ORDER BY times_bought DESC218LIMIT 25;219220-- ------------------------------------------------------------221-- 6. SALES & DISCOUNTS222-- ------------------------------------------------------------223224-- 6a. Sale behavior per chain (are Safeway's sales real?)225SELECT * FROM v_chain_sale_stats ORDER BY pct_lines_on_sale DESC;226227-- 6b. Shelf price vs paid price per chain — "costs more but discounts more"?228SELECT chain,229       ROUND(AVG(effective_unit_list_price), 2) AS avg_shelf_unit_price,230       ROUND(AVG(effective_unit_price), 2)      AS avg_paid_unit_price,231       ROUND(100.0 * (AVG(effective_unit_list_price) - AVG(effective_unit_price))232             / NULLIF(AVG(effective_unit_list_price), 0), 1) AS avg_realized_discount_pct233FROM v_prices234WHERE effective_unit_list_price IS NOT NULL235GROUP BY chain ORDER BY avg_shelf_unit_price DESC;236237-- 6c. Our best scores (biggest single-line discounts)238SELECT purchase_date, chain, product,239       list_price, price_paid, discount_amount, discount_pct240FROM v_prices241WHERE on_sale242ORDER BY discount_amount DESC243LIMIT 25;244245-- 6d. Total saved per month246SELECT date_trunc('month', purchase_date)::date AS month,247       SUM(discount_amount) AS saved,248       SUM(price_paid)      AS spent249FROM v_prices250GROUP BY 1 ORDER BY 1;251252-- ------------------------------------------------------------253-- 7. PRICE TRENDS (personal inflation)254-- ------------------------------------------------------------255256-- 7a. Price history for one product across chains (line chart, one line per chain)257SELECT purchase_date, chain, effective_unit_price258FROM v_prices259WHERE product = 'bananas' AND effective_unit_price IS NOT NULL260ORDER BY purchase_date;261262-- 7b. Personal price index: avg unit price of repeat staples, by quarter263WITH staples AS (264    SELECT product FROM v_prices265    GROUP BY product HAVING COUNT(*) >= 6266)267SELECT date_trunc('quarter', purchase_date)::date AS quarter,268       ROUND(AVG(effective_unit_price), 2)        AS avg_staple_unit_price269FROM v_prices270WHERE product IN (SELECT product FROM staples)271  AND effective_unit_price IS NOT NULL272GROUP BY 1 ORDER BY 1;273274-- 7c. Products whose price rose the most (first vs last purchase)275WITH firsts AS (276    SELECT DISTINCT ON (product) product,277           effective_unit_price AS first_price, purchase_date AS first_date278    FROM v_prices WHERE effective_unit_price IS NOT NULL279    ORDER BY product, purchase_date280),281lasts AS (282    SELECT DISTINCT ON (product) product,283           effective_unit_price AS last_price, purchase_date AS last_date284    FROM v_prices WHERE effective_unit_price IS NOT NULL285    ORDER BY product, purchase_date DESC286)287SELECT f.product, f.first_date, f.first_price, l.last_date, l.last_price,288       ROUND(100.0 * (l.last_price - f.first_price) / f.first_price, 0) AS pct_change289FROM firsts f290JOIN lasts l USING (product)291WHERE l.last_date > f.first_date + 60      -- at least ~2 months apart292  AND f.first_price > 0293ORDER BY pct_change DESC294LIMIT 25;295296-- ------------------------------------------------------------297-- 8. ODDS & ENDS298-- ------------------------------------------------------------299300-- 8a. Biggest single baskets301SELECT purchase_date, chain, total,302       (SELECT COUNT(*) FROM receipt_line_items li WHERE li.receipt_id = r.id) AS n_items303FROM receipts r304ORDER BY total DESC LIMIT 10;305306-- 8b. Deposits & fees paid over time (CRV, bag fees)307SELECT date_trunc('month', r.purchase_date)::date AS month,308       li.line_type,309       SUM(li.price_paid) AS amount310FROM receipt_line_items li JOIN receipts r ON r.id = li.receipt_id311WHERE li.line_type IN ('deposit', 'fee')312GROUP BY 1, 2 ORDER BY 1;313314-- 8c. Non-grocery spend hiding in grocery runs (Costco effect)315SELECT r.chain, li.raw_name, li.common_name, li.price_paid, r.purchase_date316FROM receipt_line_items li JOIN receipts r ON r.id = li.receipt_id317WHERE li.line_type = 'non_grocery'318ORDER BY li.price_paid DESC;319320-- 8d. Products we only ever buy at one chain (loyalty / availability)321SELECT product, MAX(chain) AS only_chain,322       COUNT(*) AS times_bought, SUM(price_paid) AS spent323FROM v_prices324GROUP BY product325HAVING COUNT(DISTINCT chain) = 1 AND COUNT(*) >= 5326ORDER BY spent DESC;327328-- 8e. Price volatility: staples with the widest price swings329SELECT product, effective_unit,330       COUNT(*)                             AS n,331       ROUND(MIN(effective_unit_price), 2)  AS min_price,332       ROUND(MAX(effective_unit_price), 2)  AS max_price,333       ROUND(STDDEV(effective_unit_price), 2) AS stddev334FROM v_prices335WHERE effective_unit_price IS NOT NULL336GROUP BY 1, 2337HAVING COUNT(*) >= 5338ORDER BY stddev DESC NULLS LAST339LIMIT 25;340341-- 8f. Data quality: receipts whose lines don't reconcile (should be only the 3 damaged scans)342SELECT * FROM v_receipt_qc WHERE ABS(COALESCE(unexplained_diff, 0)) > 0.02;
db/load_baseline.shadded +95 −0
@@ -0,0 +1,95 @@1#!/usr/bin/env bash2# Load the bulk-extracted baseline dataset into Postgres.3# Usage:  ./load_baseline.sh "postgres://user:pass@host:5432/dbname"4# Expects db/baseline/{products.csv,receipts.csv,line_items.csv} (produced by the5# bulk extraction) and applies schema.sql first. Idempotent: re-running upserts.6set -euo pipefail78DB_URL="${1:?usage: ./load_baseline.sh <postgres-connection-url>}"9DIR="$(cd "$(dirname "$0")" && pwd)"1011psql "$DB_URL" -v ON_ERROR_STOP=1 -f "$DIR/schema.sql"1213psql "$DB_URL" -v ON_ERROR_STOP=1 <<SQL14BEGIN;1516-- ---------- staging ----------17CREATE TEMP TABLE stg_products (LIKE products INCLUDING DEFAULTS EXCLUDING IDENTITY EXCLUDING CONSTRAINTS);18ALTER TABLE stg_products DROP COLUMN id;19\copy stg_products (common_name, category, is_organic, default_unit, notes, created_at) FROM '$DIR/baseline/products.csv' WITH (FORMAT csv, HEADER true)2021CREATE TEMP TABLE stg_receipts (LIKE receipts INCLUDING DEFAULTS EXCLUDING CONSTRAINTS);22\copy stg_receipts (id, receipt_key, merchant, chain, store_number, store_address, purchase_date, purchased_at, receipt_number, total, tax, payment_method, confirmed, source, source_file, overall_confidence) FROM '$DIR/baseline/receipts.csv' WITH (FORMAT csv, HEADER true)2324CREATE TEMP TABLE stg_line_items (25    receipt_key     TEXT,26    line_no         INT,27    item_code       TEXT,28    raw_name        TEXT,29    ai_common_name  TEXT,30    common_name     TEXT,31    category        TEXT,32    line_type       TEXT,33    quantity        NUMERIC,34    unit_price      NUMERIC,35    weight_lbs      NUMERIC,36    price_per_lb    NUMERIC,37    list_price      NUMERIC,38    price_paid      NUMERIC,39    item_confidence NUMERIC40);41\copy stg_line_items FROM '$DIR/baseline/line_items.csv' WITH (FORMAT csv, HEADER true)4243-- ---------- upsert products ----------44INSERT INTO products (common_name, category, is_organic, default_unit, notes)45SELECT common_name, category, COALESCE(is_organic, FALSE), default_unit, notes46FROM stg_products47ON CONFLICT (common_name) DO UPDATE SET48    category = EXCLUDED.category,49    is_organic = EXCLUDED.is_organic,50    default_unit = EXCLUDED.default_unit;5152-- ---------- upsert receipts (natural key wins) ----------53INSERT INTO receipts (id, receipt_key, merchant, chain, store_number, store_address,54                      purchase_date, purchased_at, receipt_number, total, tax,55                      payment_method, confirmed, source, source_file, overall_confidence)56SELECT id, receipt_key, merchant, chain, store_number, store_address,57       purchase_date, purchased_at, receipt_number, total, tax,58       payment_method, confirmed, source, source_file, overall_confidence59FROM stg_receipts60ON CONFLICT (receipt_key) DO UPDATE SET61    merchant = EXCLUDED.merchant, chain = EXCLUDED.chain,62    store_number = EXCLUDED.store_number, store_address = EXCLUDED.store_address,63    purchase_date = EXCLUDED.purchase_date, purchased_at = EXCLUDED.purchased_at,64    receipt_number = EXCLUDED.receipt_number, total = EXCLUDED.total,65    tax = EXCLUDED.tax, payment_method = EXCLUDED.payment_method,66    confirmed = EXCLUDED.confirmed, source = EXCLUDED.source,67    source_file = EXCLUDED.source_file,68    overall_confidence = EXCLUDED.overall_confidence,69    updated_at = now();7071-- ---------- replace line items per receipt ----------72DELETE FROM receipt_line_items73WHERE receipt_id IN (SELECT r.id FROM receipts r JOIN stg_line_items s ON s.receipt_key = r.receipt_key);7475INSERT INTO receipt_line_items (receipt_id, line_no, item_code, raw_name, ai_common_name,76                                common_name, product_id, category, line_type, quantity,77                                unit_price, weight_lbs, price_per_lb, list_price,78                                price_paid, item_confidence)79SELECT r.id, s.line_no, s.item_code, s.raw_name, s.ai_common_name,80       s.common_name, p.id, s.category, COALESCE(s.line_type, 'item'), s.quantity,81       s.unit_price, s.weight_lbs, s.price_per_lb, s.list_price,82       s.price_paid, s.item_confidence83FROM stg_line_items s84JOIN receipts r ON r.receipt_key = s.receipt_key85LEFT JOIN products p ON p.common_name = s.common_name;8687COMMIT;8889-- ---------- QC report ----------90SELECT COUNT(*) AS receipts FROM receipts;91SELECT COUNT(*) AS line_items FROM receipt_line_items;92SELECT * FROM v_receipt_qc WHERE ABS(COALESCE(unexplained_diff,0)) > 0.02 LIMIT 20;93SQL9495echo "Done."
db/schema.sqladded +211 −0
@@ -0,0 +1,211 @@1-- ============================================================2-- Rhea grocery-receipt analysis schema (v2)3-- Target: self-hosted Postgres. Idempotent: safe to re-run.4-- Run:  psql -d <your_database> -f schema.sql5-- ============================================================67-- ------------------------------------------------------------8-- products: canonical product dimension for cross-store analysis.9-- common_name is the controlled vocabulary you filter on10-- (lowercase, plural where natural: 'bananas', 'yellow onions').11-- ------------------------------------------------------------12CREATE TABLE IF NOT EXISTS products (13    id           BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,14    common_name  TEXT NOT NULL UNIQUE,15    category     TEXT,                                   -- normalized: produce, dairy, meat, seafood, bakery, pantry, frozen, beverage, alcohol, snacks, household, other16    is_organic   BOOLEAN NOT NULL DEFAULT FALSE,17    default_unit TEXT CHECK (default_unit IN ('lb','each')),18    notes        TEXT,19    created_at   TIMESTAMPTZ NOT NULL DEFAULT now()20);2122-- ------------------------------------------------------------23-- receipts: one row per receipt.24-- receipt_key is the natural key (chain_store_date_receiptnumber)25-- and is UNIQUE so baseline + Rhea exports can't double-insert.26-- ------------------------------------------------------------27CREATE TABLE IF NOT EXISTS receipts (28    id             UUID PRIMARY KEY,29    receipt_key    TEXT NOT NULL UNIQUE,30    merchant       TEXT NOT NULL,31    chain          TEXT,32    store_number   TEXT,33    store_address  TEXT,34    purchase_date  DATE NOT NULL,35    purchased_at   TIMESTAMPTZ,                          -- full timestamp when the receipt shows a time36    receipt_number TEXT,37    total          NUMERIC(10,2) NOT NULL,38    tax            NUMERIC(10,2),39    payment_method TEXT,40    confirmed      BOOLEAN NOT NULL DEFAULT FALSE,41    source         TEXT NOT NULL DEFAULT 'rhea'42                   CHECK (source IN ('baseline','rhea','manual')),43    source_file    TEXT,44    overall_confidence NUMERIC(3,2),45    created_at     TIMESTAMPTZ NOT NULL DEFAULT now(),46    updated_at     TIMESTAMPTZ NOT NULL DEFAULT now()47);4849CREATE INDEX IF NOT EXISTS idx_receipts_chain_date ON receipts (chain, purchase_date);5051-- ------------------------------------------------------------52-- receipt_line_items: one row per printed line.53-- raw_name      = exactly as printed (never edited)54-- ai_common_name= model suggestion55-- common_name   = canonical name (what you query on); should match products.common_name56-- line_type     = keeps deposits/fees/refunds/non-grocery out of price stats57-- effective_*   = generated columns that normalize per-lb vs per-each pricing58-- ------------------------------------------------------------59CREATE TABLE IF NOT EXISTS receipt_line_items (60    id             UUID PRIMARY KEY DEFAULT gen_random_uuid(),61    receipt_id     UUID NOT NULL REFERENCES receipts(id) ON DELETE CASCADE,62    line_no        INT  NOT NULL,63    item_code      TEXT,                                 -- UPC / PLU / SKU as printed64    raw_name       TEXT NOT NULL,65    ai_common_name TEXT,66    common_name    TEXT,67    product_id     BIGINT REFERENCES products(id),68    category       TEXT,                                 -- department as printed (PRODUCE, GROCERY, ...)69    line_type      TEXT NOT NULL DEFAULT 'item'70                   CHECK (line_type IN ('item','deposit','fee','refund','discount','non_grocery')),71    quantity       NUMERIC(10,3),                        -- by-unit items72    unit_price     NUMERIC(10,4),73    weight_lbs     NUMERIC(10,4),                        -- by-weight items74    price_per_lb   NUMERIC(10,4),75    list_price     NUMERIC(10,2),                        -- regular shelf price76    price_paid     NUMERIC(10,2),                        -- actual charged after discounts77    item_confidence NUMERIC(3,2),7879    -- Normalized comparison columns (the point of this schema):80    effective_unit TEXT GENERATED ALWAYS AS (81        CASE WHEN weight_lbs IS NOT NULL AND weight_lbs > 0 THEN 'lb' ELSE 'each' END82    ) STORED,83    effective_unit_price NUMERIC(12,4) GENERATED ALWAYS AS (84        CASE85            WHEN weight_lbs IS NOT NULL AND weight_lbs > 0 THEN price_paid / weight_lbs86            WHEN quantity   IS NOT NULL AND quantity   > 0 THEN price_paid / quantity87            ELSE price_paid88        END89    ) STORED,90    discount_amount NUMERIC(10,2) GENERATED ALWAYS AS (91        CASE WHEN list_price IS NOT NULL AND price_paid IS NOT NULL92              AND list_price > price_paid93             THEN list_price - price_paid END94    ) STORED,9596    UNIQUE (receipt_id, line_no)97);9899CREATE INDEX IF NOT EXISTS idx_li_common_name ON receipt_line_items (common_name);100CREATE INDEX IF NOT EXISTS idx_li_product     ON receipt_line_items (product_id);101CREATE INDEX IF NOT EXISTS idx_li_receipt     ON receipt_line_items (receipt_id);102103-- ------------------------------------------------------------104-- Analysis views105-- ------------------------------------------------------------106107-- Every real grocery purchase, price-normalized. Primary Metabase/Jupyter source.108CREATE OR REPLACE VIEW v_prices AS109SELECT110    r.chain,111    r.store_number,112    r.store_address,113    r.purchase_date,114    COALESCE(li.common_name, li.ai_common_name, li.raw_name) AS product,115    p.is_organic,116    p.category                        AS product_category,117    li.common_name,118    li.raw_name,119    li.category,120    li.item_code,121    li.effective_unit,122    li.effective_unit_price,          -- $/lb or $/each, based on price actually paid123    CASE                              -- same normalization, at regular shelf price124        WHEN li.weight_lbs IS NOT NULL AND li.weight_lbs > 0 THEN li.list_price / li.weight_lbs125        WHEN li.quantity   IS NOT NULL AND li.quantity   > 0 THEN li.list_price / li.quantity126        ELSE li.list_price127    END                               AS effective_unit_list_price,128    li.quantity,129    li.weight_lbs,130    li.list_price,131    li.price_paid,132    (li.discount_amount IS NOT NULL)  AS on_sale,133    li.discount_amount,134    CASE WHEN li.discount_amount IS NOT NULL AND li.list_price > 0135         THEN ROUND(100.0 * li.discount_amount / li.list_price, 1)136    END                               AS discount_pct,137    r.receipt_key,138    li.line_no139FROM receipt_line_items li140JOIN receipts r ON r.id = li.receipt_id141LEFT JOIN products p ON p.id = li.product_id142WHERE li.line_type = 'item';143144-- "Are bananas cheaper at Whole Foods or Safeway?"145-- SELECT * FROM v_price_comparison WHERE product LIKE '%banana%';146CREATE OR REPLACE VIEW v_price_comparison AS147SELECT148    product,149    effective_unit,150    chain,151    COUNT(*)                              AS n_purchases,152    ROUND(MIN(effective_unit_price), 2)   AS min_price,153    ROUND(AVG(effective_unit_price), 2)   AS avg_price,154    ROUND(MAX(effective_unit_price), 2)   AS max_price,155    MAX(purchase_date)                    AS last_purchased156FROM v_prices157GROUP BY product, effective_unit, chain;158159-- Price history of a product over time, per chain (Metabase line chart).160CREATE OR REPLACE VIEW v_price_history AS161SELECT162    purchase_date,163    chain,164    product,165    effective_unit,166    effective_unit_price,167    on_sale168FROM v_prices169ORDER BY product, purchase_date;170171-- "Does Safeway cost more but run more sales?" — sale behavior per chain.172CREATE OR REPLACE VIEW v_chain_sale_stats AS173SELECT174    chain,175    COUNT(*)                                          AS n_lines,176    COUNT(*) FILTER (WHERE on_sale)                   AS n_on_sale,177    ROUND(100.0 * COUNT(*) FILTER (WHERE on_sale) / COUNT(*), 1) AS pct_lines_on_sale,178    ROUND(AVG(discount_pct) FILTER (WHERE on_sale), 1)           AS avg_discount_pct,179    ROUND(SUM(discount_amount), 2)                    AS total_saved,180    ROUND(SUM(price_paid), 2)                         AS total_spent181FROM v_prices182GROUP BY chain;183184-- Monthly spend by chain and category (Metabase dashboard).185CREATE OR REPLACE VIEW v_monthly_spend AS186SELECT187    date_trunc('month', r.purchase_date)::date AS month,188    r.chain,189    COALESCE(li.category, 'UNKNOWN')           AS category,190    SUM(li.price_paid)                         AS spend,191    COUNT(DISTINCT r.id)                       AS n_receipts192FROM receipt_line_items li193JOIN receipts r ON r.id = li.receipt_id194WHERE li.line_type IN ('item','non_grocery')195GROUP BY 1, 2, 3;196197-- QC: does the sum of line items match the printed receipt total?198CREATE OR REPLACE VIEW v_receipt_qc AS199SELECT200    r.receipt_key,201    r.chain,202    r.purchase_date,203    r.total                             AS printed_total,204    SUM(li.price_paid)                  AS line_item_sum,205    r.total - COALESCE(SUM(li.price_paid), 0) - COALESCE(r.tax, 0) AS unexplained_diff,206    r.source,207    r.source_file208FROM receipts r209LEFT JOIN receipt_line_items li ON li.receipt_id = r.id210GROUP BY r.id211ORDER BY ABS(r.total - COALESCE(SUM(li.price_paid), 0) - COALESCE(r.tax, 0)) DESC;