rheaarchived
- 40 commits
- 1 branch
- 0 tags
- updated
schema.sql
8.8 KB · 211 lines
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;