Skip to content

Commit b3f3785

Browse files
committed
feat: DineLoop growth P0 (consented CRM, loyalty, spin wheel, review funnel, campaigns)
- Guest phone capture with a DPDP notice, separate unticked opt-ins and an append-only consent ledger; one-tap opt-out link - Customer CRM with visits, spend, last visit and new/regular/lapsed segments - Loyalty stamps per paid visit; spin the wheel once per paid visit for a next-visit coupon; coupons applied before GST - Review funnel: 4-5 stars to the Google review link setting, 1-3 stars to a private owner alert - WhatsApp campaigns and bill updates through a simulated adapter writing to an outbox, marketing only to opted-in customers - Owner dashboard card for repeat rate and campaign results; customers, campaigns and settings screens - Docs: README run and demo guide, AGENTS code section, APP_URL https://dineloop.craftlayer.store
1 parent 7fabd81 commit b3f3785

45 files changed

Lines changed: 5780 additions & 81 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎AGENTS.md‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ Rules for anyone (people or coding agents) changing this repository.
44

55
## What this is
66

7-
TableTap, a QR table-ordering prototype for Indian restaurants. Read [README.md](README.md) for how to run it and [PLAN.md](PLAN.md) for the product plan and milestones. Current milestone: M0 done, M1 next.
7+
TableTap, a QR table-ordering prototype for Indian restaurants. Read [README.md](README.md) for how to run it and [PLAN.md](PLAN.md) for the product plan and milestones. Current state: M1 (Postgres, auth, QR tokens, menu editor) and the DineLoop growth P0 (CRM, consent, loyalty, wheel, review funnel, simulated WhatsApp campaigns) are built; SSE, RLS and M2 payments are next.
88

99
## Ground rules
1010

@@ -23,9 +23,21 @@ TableTap, a QR table-ordering prototype for Indian restaurants. Read [README.md]
2323
- Table state is derived (`deriveTableState`), never stored.
2424
- Route handlers stay thin: parse and validate input (`src/server/http.ts`), call the store, return JSON. Errors that the user should see are `StoreError` with an HTTP status.
2525
- The guest is untrusted. Prices, totals and amounts are always computed on the server from the menu and orders, never taken from the request.
26+
- Data access lives in `src/server/store/`; route handlers never import `db/` directly. Every query filters by `restaurant_id`, and every staff/owner route calls `requireStaff(permission)` (`src/server/session.ts`) before touching the store. Permissions are defined in `src/domain/roles.ts`.
27+
- Schema changes: edit `src/server/db/schema.ts`, run `pnpm db:generate`, commit the SQL in `drizzle/`. Never edit an applied migration.
28+
- Guest phone numbers: keep the DPDP notice, separate unticked opt-ins, the consent ledger (`consent_records`, append-only) and the opt-out link. Marketing goes only to customers whose latest marketing consent is granted.
29+
- Messaging goes through `src/server/messaging.ts`. Only the simulated adapter exists; no third-party network calls or API keys.
2630
- UI: plain CSS in `src/app/globals.css`, mobile first, brand colours ink `#101828`, accent `#465FFF`, light accent `#8A99FF`, canvas `#F7F8F5`. Every control needs an accessible name; keep touch targets at least 36 px.
2731
- Be honest in copy and docs: no invented customers, metrics or market numbers. Demo data must be labelled as demo.
2832

33+
## Code
34+
35+
Structure: `src/domain/` (pure rules, unit tests), `src/server/db/` (schema, client), `src/server/store/` (use cases, integration tests on in-memory PGlite), `src/server/{session,http,parse,rate-limit,messaging}.ts`, `src/app/` (pages and thin routes), `src/components/` (client screens), `drizzle/` (migrations).
36+
37+
Commands: `pnpm dev`, `pnpm test`, `pnpm typecheck`, `pnpm lint`, `pnpm build`, `pnpm db:generate`, `pnpm db:migrate`, `pnpm db:seed`, `pnpm db:reset`. Local dev servers use a port from 3101 to 3199; stop them when done.
38+
39+
Config: `APP_URL` (QR and share links; production `https://dineloop.craftlayer.store`), `DATABASE_URL` (optional Postgres), `SESSION_SECRET`, `DEMO_OTP`. See `.env.example`.
40+
2941
## Commits
3042

3143
- Conventional-style subjects (`feat:`, `fix:`, `docs:`, `test:`, `chore:`).

‎PLAN.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
TableTap is a QR-at-the-table ordering and payment system for Indian restaurants and cafes. Guests scan a code on the table, order from their own phone, follow their food, call a waiter, split the bill and pay at the table. Staff, kitchen and owner each get a live screen.
44

5-
This document is the plan. The repository also holds milestone M0, a working prototype (see [README.md](README.md)).
5+
This document is the plan. The repository holds the MVP: M0, most of M1 and the DineLoop growth P0 (see [README.md](README.md)).
66

77
Nothing here claims customers, revenue, traction or market size. We have none yet. Numbers below are either computed by the prototype or explicitly marked as hypotheses.
88

@@ -124,7 +124,7 @@ Table state on the floor map is derived, never stored: no open session is free;
124124
## 7. Realtime approach
125125

126126
- M0 (this repo): every screen polls a JSON endpoint every 2.5 s (owner every 5 s) and pauses while the tab is hidden. Simple and good enough for a demo on one machine.
127-
- M1: Postgres plus server-sent events (SSE). Each mutation writes the change and publishes an event on a per-restaurant channel (Postgres `LISTEN/NOTIFY` to start; a hosted pub/sub only if we outgrow it). Staff and kitchen screens hold one SSE connection; guest pages subscribe to their own session only. Clients still refetch on reconnect, so a missed event never leaves a screen stale.
127+
- M1 (deferred, screens still poll): Postgres plus server-sent events (SSE). Each mutation writes the change and publishes an event on a per-restaurant channel (Postgres `LISTEN/NOTIFY` to start; a hosted pub/sub only if we outgrow it). Staff and kitchen screens hold one SSE connection; guest pages subscribe to their own session only. Clients still refetch on reconnect, so a missed event never leaves a screen stale.
128128
- Why SSE over WebSockets: updates flow server to client; writes are normal HTTP POSTs. SSE works through most proxies and is simpler to host.
129129

130130
## 8. Multi-tenancy
@@ -164,8 +164,8 @@ Rules:
164164

165165
| Milestone | Scope | Exit criteria |
166166
| --- | --- | --- |
167-
| M0 prototype (done, this repo) | Domain module with tests, in-memory store, guest/staff/kitchen/owner screens, polling, simulated payments, CI | `pnpm typecheck`, `pnpm lint`, `pnpm test`, `pnpm build` pass in CI; full table visit works end to end in the demo |
168-
| M1 database and auth | Postgres schema above, migrations, row-level security, staff login with roles, menu editor for owners, table QR tokens and printable QR sheet, SSE instead of polling, per-item station status, rate limits, error tracking | All M0 flows work against Postgres across restarts and multiple server instances; role checks on every staff action; seed script for demo data |
167+
| M0 prototype (done) | Domain module with tests, in-memory store, guest/staff/kitchen/owner screens, polling, simulated payments, CI | `pnpm typecheck`, `pnpm lint`, `pnpm test`, `pnpm build` pass in CI; full table visit works end to end in the demo |
168+
| M1 database and auth (mostly done: Postgres via Drizzle, migrations, seed, OTP login with roles, menu editor, QR tokens and sheet, rate limits; still open: RLS, SSE, per-item station status, error tracking) | Postgres schema above, migrations, row-level security, staff login with roles, menu editor for owners, table QR tokens and printable QR sheet, SSE instead of polling, per-item station status, rate limits, error tracking | All M0 flows work against Postgres across restarts and multiple server instances; role checks on every staff action; seed script for demo data |
169169
| M2 payments | Gateway integration (test mode first), webhooks, staff-confirmed cash and transfer, refunds path, email receipts through a transactional email provider, GST-correct receipts | A test-mode payment for a split bill completes end to end; no secrets in the repo; webhook replay is idempotent |
170170
| M3 pilot with one real restaurant | Real menu and photos, QR codes printed for every table, staff training, Hindi menu text if the restaurant wants it, monitoring, daily backup | One restaurant runs real service on TableTap for an agreed period (target: two weeks); we collect their feedback and our own measurements of order and payment times |
171171

‎README.md‎

Lines changed: 71 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -2,87 +2,98 @@
22

33
Scan, order, track and pay at the table. TableTap is a QR-at-the-table ordering system for Indian restaurants and cafes: guests open the menu from a QR code (no app), order from their phone, follow their food, call a waiter, split the bill, tip and pay by UPI, card, cash or bank transfer, then leave a one-tap review. Staff get a live floor map, the kitchen gets a station display with timers, and the owner sees today's numbers.
44

5-
> **Status: prototype (milestone M0). In-memory, not production.** All data lives in server memory and resets on restart. Payments are simulated: nothing is charged and no email is sent. "Juniper Kitchen" is a made-up demo restaurant.
5+
TableTap is the ordering module of **DineLoop** ([product plan](https://github.com/craftLayer-studio/dineloop)), which adds the guest-revenue layer on top: consented phone capture, a customer CRM, loyalty stamps, a spin-the-wheel reward, a Google review funnel and WhatsApp campaigns. Production URL (not deployed yet): <https://dineloop.craftlayer.store>. Company site: <https://craftlayer.store>.
66

7-
The plan, data model, payments approach and milestones are in [PLAN.md](PLAN.md).
8-
9-
## What works in the prototype
7+
> **Status: MVP, demo data, simulated messaging and payments.** Data is stored in Postgres (PGlite locally). Payments are simulated: nothing is charged. WhatsApp, SMS and email are simulated: messages are written to an outbox shown to the owner and never leave the server. "Juniper Kitchen" is a made-up demo restaurant in Pune; every name and phone number in the demo is invented.
108
11-
- `/` overview with links to every demo view.
12-
- `/t/t1` … `/t/t6` guest view: menu by category with photo placeholder, price, half/full sizes, allergens, spice level, veg mark, deals and sold-out items; veg-only and allergen filters; cart with notes; place order; order status with progress and estimated time; call waiter; bill with GST, tip presets and even split; pay share by share (UPI deep link, card, cash, bank transfer, simulated); review after paying.
13-
- `/staff` live floor map (free, ordering, eating, needs help, bill requested), service requests, incoming orders with "Send to kitchen", cancel and "Mark served", reset demo.
14-
- `/kitchen` orders by station with elapsed timers and late highlighting, start cooking, mark ready.
15-
- `/owner` tables in use, orders, items sold, money collected, tips, average rating, top dishes and latest reviews since midnight IST.
16-
17-
Screens poll the API every 2.5 seconds (owner every 5). Open a table on your phone or in one tab and `/staff` and `/kitchen` in others to see updates move between them.
9+
The plan, data model, payments approach and milestones are in [PLAN.md](PLAN.md).
1810

1911
## Run it
2012

21-
Requirements: Node.js 20.9 or newer and pnpm (the version is pinned in `package.json` under `packageManager`).
13+
Requirements: Node.js 20.9 or newer and pnpm (pinned in `package.json` under `packageManager`).
2214

2315
```bash
2416
pnpm install
25-
pnpm dev # http://localhost:3000
17+
cp .env.example .env.local # optional; set APP_URL=http://localhost:3101 for local QR codes
18+
pnpm dev --port 3101 # http://localhost:3101
2619
```
2720

28-
Other commands:
21+
The first request creates a PGlite database in `./.data/pglite`, runs the migrations in `./drizzle` and seeds the demo restaurant. Set `DATABASE_URL` to use a real Postgres instead (node-postgres). Tests use an in-memory PGlite.
2922

30-
```bash
31-
pnpm test # Vitest unit tests (domain rules and store flow)
32-
pnpm typecheck # next typegen, then tsc --noEmit
33-
pnpm lint # ESLint (next core-web-vitals + typescript)
34-
pnpm build # production build
35-
pnpm start # serve the production build
36-
```
23+
| Command | What it does |
24+
| --- | --- |
25+
| `pnpm test` | Vitest: domain unit tests and store integration tests on in-memory PGlite |
26+
| `pnpm typecheck` | `next typegen`, then `tsc --noEmit` |
27+
| `pnpm lint` | ESLint (next core-web-vitals + typescript) |
28+
| `pnpm build` / `pnpm start` | production build (webpack) / serve it |
29+
| `pnpm db:generate` | generate a SQL migration after changing `src/server/db/schema.ts` |
30+
| `pnpm db:migrate` | apply migrations (and seed an empty database) |
31+
| `pnpm db:seed` | seed the demo if the database is empty |
32+
| `pnpm db:reset` | wipe all data and seed the demo again |
33+
34+
Stop the dev server before `db:*` commands: a PGlite file database can be opened by one process at a time. If you upgrade from an older checkout, run `pnpm db:reset` once so the demo staff and customers exist.
35+
36+
`dev` and `build` use webpack (`--webpack`) because some development machines cannot load the native SWC/Turbopack binaries.
3737

38-
`dev` and `build` use webpack (`--webpack`) because one of our development machines cannot load the native SWC/Turbopack binaries.
38+
## Demo walkthrough
3939

40-
To try it from a phone on the same Wi-Fi, run `pnpm dev -H 0.0.0.0` and open `http://<your-computer-ip>:3000/t/t1`.
40+
1. Open `/` and pick a table. The link is the table's QR URL, `/t/{token}`, with a random token.
41+
2. As the guest: filter the menu, add dishes, place the order. Optionally save a phone number on the Bill tab, with two separate, unticked opt-ins (bill updates; offers).
42+
3. Open `/login` in another tab and tap **Sign in as waiter**. The one-time code is shown on screen (demo). On `/staff`, press **Send to kitchen**. Sign in as kitchen for `/kitchen` (start cooking, mark ready).
43+
4. Back on the guest tab: get the bill (enter a coupon if you have one), pay a share (simulated). After paying: one stamp on the loyalty card, one spin of the wheel (the prize is a coupon for the next visit), and a review. 4-5 stars shows a "Post a Google review" button; 1-3 stars goes privately to the owner.
44+
5. Sign in as owner. `/owner` shows today's numbers plus **Guests coming back**: repeat rate, customers, opt-ins, campaign redemptions and revenue, and private feedback to follow up.
45+
6. `/owner/customers`: CRM with visits, spend, last visit, stamps, consent and segment (new, regular, lapsed). **Record STOP** withdraws marketing consent.
46+
7. `/owner/campaigns`: pick a template, audience and offer, preview, send. Only marketing-consented customers receive it; each gets a personal coupon and an opt-out link (`/u/{token}`). Messages appear in the outbox.
47+
8. `/owner/menu` (edit categories, dishes, sizes, prices, deals, availability), `/owner/qr` (printable QR sheet, re-issue a table's code, add a table), `/owner/settings` (Google review link). **Reset demo** is at the bottom of `/owner`.
48+
49+
Demo staff (made-up numbers, code shown on screen): owner +91 98000 00001, manager +91 98000 00002, waiter +91 98000 00003, kitchen +91 98000 00004.
50+
51+
## Features
52+
53+
Built:
54+
55+
- Guest QR page: menu with sizes, allergens, spice, veg mark, deals, sold out, filters; cart with notes; live order status with ETA; call waiter; GST bill, tip, even split; pay per share (UPI intent link, simulated card, cash, bank transfer); review.
56+
- Staff floor map and order confirmation, kitchen display by station with timers, owner day summary.
57+
- Postgres via Drizzle with SQL migrations and a seed; one open session per table (partial unique index); every query scoped by restaurant.
58+
- Random, rotatable table QR tokens and a printable QR sheet (built from `APP_URL`).
59+
- Staff and owner phone + OTP sign-in (demo code on screen), signed httpOnly session cookie, server-side role checks (owner, manager, waiter, kitchen).
60+
- Owner menu editor: categories, dishes, sizes and prices, deals, availability.
61+
- In-memory rate limits on guest writes and sign-in.
62+
- Guest phone capture with a DPDP notice and separate opt-ins (service, marketing), an append-only consent ledger and one-tap opt-out.
63+
- Customer CRM: profiles, visits, spend, last visit, segments new / regular / lapsed.
64+
- Loyalty stamps (one per paid visit; five earn ₹150 off), spin-the-wheel (one play per paid visit, coupon for the next visit), coupons applied before GST.
65+
- Review funnel: 4-5 stars to the Google review link setting, 1-3 stars to a private owner alert.
66+
- WhatsApp campaigns (win-back, weekday offer, new dish, event) through a simulated adapter writing to an outbox; bill updates as utility messages to service-consented guests; campaign results (sent, skipped, redeemed, revenue) and repeat rate on the owner dashboard.
67+
68+
Planned (see PLAN.md and the DineLoop plan): server-sent events instead of polling (screens poll every 2.5 s), row-level security, OTP verification of guest phone numbers, real payment gateway with webhooks (M2), real WhatsApp/SMS adapters, menu import from CSV/photo, birthday campaigns, direct online ordering, POS integrations, Hindi menus.
4169

4270
## Folder map
4371

4472
```
73+
drizzle/ SQL migrations (generated by drizzle-kit, committed)
74+
scripts/db.ts db:migrate / db:seed / db:reset
4575
src/
46-
domain/ Pure business rules, no framework code. Unit tested.
47-
money.ts Paise helpers and INR formatting (Indian digit grouping)
48-
menu.ts Menu, items, variants, allergens, spice, stations, deals
49-
cart.ts Cart editing and validated order items (price snapshots)
50-
order.ts Order state machine, status events, estimated ready time
51-
table.ts Tables, sessions and derived floor-map state
52-
service.ts Call-waiter / bill requests and reviews
53-
bill.ts Bill totals, GST, tip, even split with exact paise, share payments
54-
upi.ts UPI intent link builder
55-
report.ts Owner's day summary
56-
time.ts IST start of day
76+
domain/ Pure business rules, unit tested (money, menu, cart, order, bill, table, roles, phone,
77+
menu-edit, growth: consent, segments, loyalty, coupons, wheel, review funnel, templates)
5778
server/
58-
seed.ts Demo restaurant "Juniper Kitchen", 6 tables, menu
59-
store.ts In-memory store (replaced by Postgres in M1)
79+
db/ schema.ts (Drizzle), client.ts (PGlite file / in-memory / pg)
80+
store/ Data access and use cases: table-service, admin (tables, menu), auth (OTP, sessions),
81+
growth (CRM, consent, loyalty, coupons, wheel, campaigns); tests on in-memory PGlite
82+
seed.ts, seed-db.ts Demo data and seeder
83+
session.ts Staff cookie and role checks for routes and pages
84+
messaging.ts Messaging adapter interface and the simulated WhatsApp adapter (outbox)
85+
rate-limit.ts In-memory limiter
6086
http.ts, parse.ts JSON handling and input validation for route handlers
61-
app/
62-
api/ Route handlers (tables, orders, requests, staff, owner, demo reset)
63-
t/[tableId]/ Guest page
64-
staff/ kitchen/ owner/ Restaurant screens
87+
app/ Pages and thin route handlers (api/t/{token}/..., api/owner/..., api/auth/...)
6588
components/ Client components for each screen
6689
lib/live.ts Polling hook, clock, POST helper
67-
PLAN.md Product and technical plan
68-
AGENTS.md Rules for contributors and coding agents
6990
```
7091

71-
## API (prototype)
72-
73-
| Method | Path | Body |
74-
| --- | --- | --- |
75-
| POST | `/api/tables/{tableId}/join` | none; returns `{ sessionId }` |
76-
| GET | `/api/tables/{tableId}?session={sessionId}` | guest view |
77-
| POST | `/api/tables/{tableId}/orders` | `{ sessionId, cart: [{ itemId, variantId, qty, note? }] }` |
78-
| POST | `/api/tables/{tableId}/requests` | `{ sessionId, kind: "waiter" \| "bill" }` |
79-
| POST | `/api/tables/{tableId}/bill` | `{ sessionId, tipPercent, splitCount }` |
80-
| POST | `/api/tables/{tableId}/bill/pay` | `{ sessionId, partIndex, method, receiptEmail? }` |
81-
| POST | `/api/tables/{tableId}/review` | `{ sessionId, rating, comment? }` |
82-
| GET | `/api/staff` | floor, active orders, open requests |
83-
| POST | `/api/orders/{orderId}/status` | `{ to }` |
84-
| POST | `/api/requests/{requestId}/resolve` | none |
85-
| GET | `/api/owner` | today's summary |
86-
| POST | `/api/demo/reset` | none; re-seeds the demo |
87-
88-
There is no authentication in the prototype. Do not expose it on the public internet with real data.
92+
## Security notes
93+
94+
- Guests are untrusted: prices, totals, discounts and amounts are computed on the server.
95+
- Set `SESSION_SECRET` (32+ random characters) anywhere other than your own machine; without it a development secret is used and a warning is logged.
96+
- `DEMO_OTP=on` shows sign-in codes on screen. Turn it off once a real SMS adapter exists.
97+
- Rate limits are per process; use a shared store once there are several instances.
98+
99+
Contact: hello@craftlayer.store (general), dineloop@craftlayer.store (product support).

0 commit comments

Comments
 (0)