// Case study · Hacktiv8 bootcamp · Phase 1 milestone
Omnichannel Retail Analytics — from messy raw files to a chatbot that answers in SQL.
A retailer sells through stores, web, a mobile app, and a marketplace. Its data arrives as 19 raw files full of duplicates, mixed timezones, split payments, and late events. I built the pipeline that turns it into a trustworthy analytics layer — and put a natural-language chatbot on top so anyone can ask it questions.
Built during the bootcamp. This is my milestone project for Phase 1 (Data Infrastructure) of Hacktiv8’s Applied AI Engineer bootcamp, built solo in November 2026. The bootcamp is still running: Phase 2 covers LLM applications, RAG, and AI agents, and Phase 3 covers automation with n8n. See the full curriculum →
// Live demo
Ask the Gold layer a question.
This is the real engine running on the Gold tables this pipeline produced (hosted on Neon, read-only). Suggested questions are answered instantly from the benchmark set; anything else goes to an LLM that writes the SQL.
Ask a business question in plain English. The engine writes read-only SQL against the Gold layer, runs it, and charts the answer.
// 01 · Profiling
Profile first, model second.
Before writing a single table, I profiled all 19 files in a pandas notebook to find out what was actually wrong with the data. Every later design decision traces back to a number found here.
| Source | Files | Records |
|---|---|---|
| Operational (11) | customers, customer_profiles, customer_addresses, products, product_categories, stores, sales_channels, promotions, orders, order_items, order_promotions | 58,654 |
| Events (5) | payment, refund, return, support, web events | 64,213 |
| Inventory (1) | inventory_snapshots.csv | 35,040 |
| Reference (2) | campaign_spend.csv, city_reference.json | 863 |
What profiling found
| Duplicate events | 2,006 identical copies across payment, refund, return, support, and web events; 1 duplicated order |
| Mixed timezones | 5,837 event timestamps carry a +07:00 offset instead of UTC |
| Split payments | 1,915 orders were captured in two payments |
| Late events | Up to 56 h ingestion lag; 1,298 payment events arrived more than 24 h late |
| Refunds without capture | 254 refunds on cancelled orders that were never paid |
| Status vs events conflict | 1,953 orders where order status and return events disagree |
| Promo fan-out | Joining items × promotions directly inflates GMV from 15.10M to 23.96M |
| Versioned dimensions | 6 products changed category and 277 customers changed profile mid-period |
| Missing snapshots | 960 of 36,000 expected inventory location-days are missing |
| Bad rows | 1 negative quantity, 18 zero-amount payments, 3 items pointing to an unknown product |
// 02 · Bronze
Bronze: keep the evidence, untouched.
All 19 files land in one generic table, bronze.raw_records. Each row stores the original record as JSONB, plus the file name, row number, source record id, the file’s SHA-256, and the pipeline run id. No deduplication, no joins, no fixes: duplicates and bad rows are kept on purpose, so any number in Gold can be traced back to the exact line it came from.
- Validation before loading: all 19 files must exist, parse, and have the required fields per record type. The checksum and record count are written to
ops.raw_files. - Idempotent: a unique key on (file, row number, checksum) with
ON CONFLICT DO NOTHING. Re-running the same files adds zero rows.
// 03 · Silver
Silver: typed, deduplicated, validated.
Silver turns JSON payloads into 20 typed, normalised tables, each with a lineage column back to Bronze. One generic SQL step builds every table in the same order: validate → deduplicate the valid rows → reject the rest with a reason.
- UTC everywhere:
+07:00timestamps are converted, not truncated. - Safe parsing:
pg_input_is_valid()(PostgreSQL’s TRY_CAST) rejects malformed numbers and dates instead of crashing the run. - Deterministic dedup:
ROW_NUMBER()over a business key (e.g. latestupdated_atper order, one row perevent_id). - Point-in-time joins: each order item gets the product category and customer profile that were valid when the order was placed.
- Primary keys as a safety net: a dedup bug fails loudly instead of silently doubling rows.
2,026 rows were rejected into silver.rejected_records: 2,006 duplicate events, 18 zero-amount payments, 1 duplicate order, and 1 negative quantity — each with its reason code.
// 04 · Quality gate
A quality gate that can stop the line.
Between Silver and Gold, nine checks run and write their results to ops.quality_results. If any required check finds a single bad row, the task fails, Airflow stops, and yesterday’s Gold stays untouched.
- Required (must be 0): duplicate orders, orphan items, non-positive quantity, updated-before-ordered, duplicate payment events, non-positive payment amount, category version gaps.
- Warnings (logged, not blocking): refunds without capture (254), return status mismatch (1,953).
// 05 · Gold
Gold: five tables, fixed grain, no fan-out.
The Gold contract (table names, columns, grain) was fixed by the brief. My job was to fill it correctly — and prove it.
| Table | Grain | What’s inside | Rows |
|---|---|---|---|
gold.order_360 | 1 row per order | GMV, discounts, captured payment, refunds, net revenue, payment & return status | 10,000 |
gold.customer_daily | customer × date | orders, units, revenue, returns, support contacts, new / repeat flags | 11,334 |
gold.product_daily | product × date | units, revenue, refunded units, inventory, category at that date, stockout flag | 7,200 |
gold.channel_campaign_daily | date × channel × campaign | spend, attributed orders & revenue, ROAS, conversion | 2,616 |
gold.executive_kpis_daily | 1 row per business date | orders, revenue, AOV, refund / return / repeat / stockout rates, freshness | 90 |
net_revenue = gross_merchandise_value - discount_amount
+ shipping_revenue - refunded_amount -- 0 if CANCELLED
refund_rate = orders with completed refund / orders with captured payment
roas = attributed net revenue / NULLIF(campaign_spend, 0)Reconciliation: 14 checks after every build
Gold is rebuilt in a single transaction, then validate_gold cross-checks it against Silver: order count, GMV, captured payments, refunds, the net-revenue formula row by row, executive totals vs order totals, customer and product revenue vs executive revenue, and campaign spend — plus four reference checks (every order’s customer and store exist, every product and campaign channel is known). Only when all 14 pass is the run marked SUCCESS.
Decisions that shaped the numbers
| Discount = item + promotion discount | Both are real price cuts. The data confirms it: captured = GMV − both discounts + shipping for 8,776 of 8,785 paid orders. |
| Pre-aggregate before joining | Every source is rolled up per order in a CTE first, so items × promos × payments can never multiply a fact. |
| Cancelled orders: net revenue = 0 | 1,215 cancelled orders were never paid. They still count as orders, but not as revenue. |
| Refund capped at captured amount | The 254 refunds on never-captured orders become 0: no money came in, so none can go out. |
| Only REFUND_COMPLETED is money returned | ISSUED is a request, not a cash movement. |
| Business date = occurred_at | Late events (up to 56 h) land on the day they happened, not the day they arrived. |
| Return rate uses return events | Order status and return events disagree in 1,953 cases; events are the auditable signal. |
| Stockout = any location at 0 | “Zero at every location” never happens in the data, so that definition would always report 0%. |
| Missing snapshot ≠ zero stock | Inventory is NULL when no location reported, instead of silently becoming 0. |
| Latest valid version wins | Rows are validated before deduplication, so a malformed newest update falls back to the previous valid one. |
// 06 · Airflow DAG
Orchestrated end to end in Airflow.
validate_raw_files >> init_schemas >> load_bronze >> build_silver
>> quality_gate >> build_gold >> validate_gold- One run id everywhere: Airflow’s
run_idis stamped on every Bronze, Silver, Gold, and ops row, so any number can be traced to the run that produced it. - Failure tracking: an
on_failure_callbackrecords statusFAILED, the failed task, and the error inops.pipeline_runs. - Safe re-runs: Bronze appends idempotently; Silver and Gold use truncate-and-insert in one transaction;
max_active_runs=1stops two runs from overlapping. - Tested both paths: repeated successful runs (about 9 s each) and a deliberate failure (a hidden raw file) that stopped at the first task and left Gold intact.


// 07 · API
The API: question in, safe SQL out.
The NL-to-SQL engine was provided by the course as the consumer of my Gold layer — the brief was that it gives wrong answers if the pipeline is wrong. It’s a FastAPI service with one main endpoint, POST /api/analyze:
- 1. Generate: an LLM (temperature 0, JSON output) gets the Gold schema catalog and writes a SQL plan.
- 2. Guard: one statement only,
SELECT/WITHonly, no write keywords, and every table must be in thegoldschema. - 3. Execute: wrapped in a row limit with a 5-second statement timeout.
- 4. Repair: if the SQL fails, the LLM gets one bounded retry with the error context.
- 5. Chart: a deterministic planner picks line, bar, or no chart from the result’s column types — the LLM never writes plotting code.
What I added to put it online: it runs as a Vercel Python function against a Neon copy of Gold only (Bronze and Silver never leave my machine), through a database role that can only SELECT from gold. Benchmark questions are served without an LLM call; free-form questions use a free-tier LLM.
// 08 · UI
The UI: a chat that shows its work.
The course shipped a Streamlit UI. For this portfolio I rebuilt the chat in Next.js so it lives on the same site: every answer shows a short explanation, a chart when the data supports one, the result table, and the exact SQL that produced it — so a reader can check the answer instead of trusting it.
// 09 · Results
Results.
What the data says
- Net revenue is spread evenly across channels: Web 3.01M, Store 2.95M, Mobile app 2.94M, Marketplace 2.88M.
- Refund rates sit between 16.8% (Store) and 18.0% (Mobile app); 458 orders were fully refunded.
- Fashion (2.86M) and electronics (2.74M) lead category revenue; 416 product-days hit a stockout at one or more locations.
Honest limitations
- The dataset is synthetic. Every web session converts, so conversion rate is always 1.0.
- Each campaign spends on one channel but gets purchases attributed from three, which inflates ROAS (top campaigns land around 40×).
- The 25-question benchmark checks that queries run, not that answers are correct. Correctness comes from the 14 reconciliation checks in Gold.
- LLM-written SQL can still be wrong. That’s why the UI always shows the SQL.