removed unused docs

This commit is contained in:
shafi54 2026-10-10 10:11:34 +05:30
parent 8017b27eb1
commit f17faccc4b
9 changed files with 0 additions and 2073 deletions

View file

@ -1,162 +0,0 @@
# Dead Code Report — branch `DEAD_CODE_CLEAN`
> **Status: EXECUTED.** The dead code listed below has been removed (see "Removal status" at the bottom). The one exception is the Drizzle relation exports, which were kept after verification.
Static-analysis sweep for reachable-code / caller-less code across the monorepo.
**Method:** ripgrep-based caller search + manual verification.
- **tRPC endpoints:** every procedure in `admin`/`user`/`common` routers was enumerated, then searched for callers (`trpc.<path>` and `trpcClient.<path>`) in `apps/admin-ui`, `apps/user-ui`, `apps/web-ui`, `apps/admin-web`, `apps/fallback-ui`, `apps/info-site`.
- **Methods/functions:** exported + local `function`/`const` definitions in `apps/backend/src` and `packages/db_helper_sqlite/src` were searched repo-wide; classified as *truly uncalled* only when they appear nowhere except their definition (and pure re-export files).
- **Files:** inbound-reference scan by module name.
- Excludes `node_modules`, `dist`, `.wrangler`, `.output`, `.expo`, `.turbo`, `.tanstack`.
> Caveats at the bottom — some of these may be intentional (manual tooling, external API consumers, planned features). Verify before deleting.
---
## 1. Dead tRPC endpoints (15)
No caller in any client app (native or web). Each is still registered on the router, so it is reachable over HTTP but unused by this repo.
| Endpoint | File | Line | Note |
|---|---|---|---|
| `trpc.admin.coupon.validate` | `apps/backend/src/trpc/apis/admin-apis/apis/coupon.ts` | 265 | Admin coupon validation |
| `trpc.admin.vendorSnippets.getById` | `.../admin-apis/apis/vendor-snippets.ts` | 184 | Single snippet fetch |
| `trpc.admin.vendorSnippets.getVendorOrders` | `.../admin-apis/apis/vendor-snippets.ts` | 464 | Vendor orders |
| `trpc.admin.slots.getSlotsProductIds` | `.../admin-apis/apis/slots.ts` | 138 | Dup of product.* variant |
| `trpc.admin.slots.updateSlotProducts` | `.../admin-apis/apis/slots.ts` | 194 | Dup of product.* variant |
| `trpc.admin.slots.getSlots` | `.../admin-apis/apis/slots.ts` | 387 | Only `trpc.user.slots.getSlots` is used |
| `trpc.admin.slots.deleteSlot` | `.../admin-apis/apis/slots.ts` | 583 | No delete-slot UI |
| `trpc.admin.product.updateSlotProducts` | `.../admin-apis/apis/product.ts` | 392 | Duplicate router entry |
| `trpc.admin.product.getSlotsProductIds` | `.../admin-apis/apis/product.ts` | 462 | Duplicate router entry |
| `trpc.admin.staffUser.getUsers` | `.../admin-apis/apis/staff-user.ts` | 79 | `admin.user.getAllUsers` is the used one |
| `trpc.admin.staffUser.getUserDetails` | `.../admin-apis/apis/staff-user.ts` | 104 | `admin.user.getUserDetails` is used |
| `trpc.admin.staffUser.updateUserSuspension` | `.../admin-apis/apis/staff-user.ts` | 128 | `admin.user.updateUserSuspension` is used |
| `trpc.admin.user.createUserByMobile` | `.../admin-apis/apis/user.ts` | 29 | No caller |
| `trpc.common.product.getDashboardTags` | `.../common-apis/common.ts` | 144 | Home reads tags from `products.json`, not this |
| `trpc.hello` | `apps/backend/src/trpc/router.ts` | 14 | Scaffold sample endpoint |
**Notable:** the `slots` ↔ `product` routers have **four duplicated** procedures (`getSlotsProductIds`, `updateSlotProducts`) — both copies are dead. The `staffUser` router duplicates three user-management procedures that are only ever called via the `admin.user` router.
---
## 2. Dead backend functions / constants (truly uncalled)
Defined/exported but never referenced anywhere else in the repo.
### Env / config
| Symbol | File |
|---|---|
| `getJwtSecret` | `apps/backend/src/lib/env-exporter.ts` |
| `getRedisUrl` | `apps/backend/src/lib/env-exporter.ts` |
| `getPhonePeBaseUrl` | `apps/backend/src/lib/env-exporter.ts` |
| `getPhonePeClientId` | `apps/backend/src/lib/env-exporter.ts` |
| `getPhonePeClientVersion` | `apps/backend/src/lib/env-exporter.ts` |
| `getPhonePeClientSecret` | `apps/backend/src/lib/env-exporter.ts` |
| `getPhonePeMerchantId` | `apps/backend/src/lib/env-exporter.ts` |
| `READABLE_ORDER_ID_KEY` | `apps/backend/src/lib/const-strings.ts` |
| `WELCOME_MESSAGE` | `apps/backend/src/lib/const-strings.ts` |
| `defaultRole` | `apps/backend/src/lib/roles-manager.ts` |
### Notifications / jobs
| Symbol | File | Note |
|---|---|---|
| `sendPushNotificationsMany` | `apps/backend/src/lib/expo-service.ts` | Whole file has no importers (see §4) |
| `sendOrderPlacedNotification` | `apps/backend/src/lib/notif-job.ts` | Only an unused import + a commented call in `user-apis/order.ts` |
| `sendOrderCancelledNotification` | `apps/backend/src/lib/notif-job.ts` | Same — imported, call commented |
| `sendPaymentFailedNotification` | `apps/backend/src/lib/notif-job.ts` | No reference |
| `sendOrderOutForDeliveryNotification` | `apps/backend/src/lib/notif-job.ts` | No reference |
| `sendRefundInitiatedNotification` | `apps/backend/src/lib/notif-job.ts` | No reference |
*(Alive: `sendAdminNotification` via `queue-consumer.ts` ← `worker.ts`; `sendOrderPackagedNotification` and `sendOrderDeliveredNotification` via admin order api; `scheduleNotification` via those.)*
### Stores / cache / misc
| Symbol | File |
|---|---|
| `getOrderDetailsWrapper` | `apps/backend/src/dbService.ts` |
| `clearAllCache` | `apps/backend/src/lib/cloud_cache.ts` |
| `getAllBanners` | `apps/backend/src/stores/banner-store.ts` |
| `getTagById` | `apps/backend/src/stores/product-tag-store.ts` |
| `getAllTags` | `apps/backend/src/stores/product-tag-store.ts` |
| `getProductSlots` | `apps/backend/src/stores/slot-store.ts` |
| `getAllProductsSlots` | `apps/backend/src/stores/slot-store.ts` |
| `getUserNegativity` | `apps/backend/src/stores/user-negativity-store.ts` |
| `createTRPCRouter` | `apps/backend/src/trpc/trpc-index.ts` (alias re-export, unused) |
---
## 3. Dead exports in `db_helper_sqlite`
| Symbol | File | Note |
|---|---|---|
| `mergeDuplicateProducts` | `packages/db_helper_sqlite/src/admin-apis/merge-duplicate-products.ts` | Exported via index + `sqliteImporter`, but **no code calls it** (function had a "how to use manually" doc comment → manual utility). **Removed.** |
`productSkusRelations`, `productMarketStatsRelations`, `skuFeaturesRelations`, `productCombosRelations` (`src/db/schema.ts`) looked unreferenced but are **NOT dead** — Drizzle registers relation exports via `import * as schema` in `db_index.ts`, and `db.query.*.findMany({ with: … })` depends on them. **Kept.**
Used only inside their own file (helpers of live code — **not dead**): `parseDuplicateProductsMd` (deleted with the merge utility), `splitQuantityFeature`, `cleanFeatureValue`, `productTypeEnum`.
---
## 4. Dead / unreachable files & endpoints
| Item | File | Note |
|---|---|---|
| Expo push service | `apps/backend/src/lib/expo-service.ts` | No module imports it; its only export is uncalled |
| `av-router` | `apps/backend/src/apis/admin-apis/apis/av-router.ts` | Mounted at `/api/v1/av` but registers **zero routes** (staff-auth middleware only) |
| REST product summary | `apps/backend/src/apis/common-apis/apis/common-product.controller.ts` (`getAllProductsSummary`) | Reachable at `/api/v1/cm/products/summary`, but **no client calls it** (apps use tRPC) |
`/api/test` (`test-controller.ts`) is referenced only by `apps/fallback-ui/src/routes/demo.tsx` (a demo page).
---
## 5. Unused imports that point at dead code
| File | Unused import | Reality |
|---|---|---|
| `apps/backend/src/trpc/apis/user-apis/apis/order.ts` | `sendOrderPlacedNotification` (line 29) | Call is commented out (line 235) |
| `apps/backend/src/trpc/apis/user-apis/apis/order.ts` | `sendOrderCancelledNotification` (line 30) | Call is commented out (line 598) |
---
## 6. Commented-out / unreachable code blocks
Not "callers-less" but unreachable. Many "Old implementation" blocks were kept across the backend; the most notable registered-looking ones:
- `apps/backend/src/trpc/apis/common-apis/common.ts:160-176` — `getStoresSummary` and `healthCheck` procedures inside a `/* … */` block (NOT registered; the live ones are in `common-trpc-index.ts`).
- `apps/backend/src/main-router.ts` — `// router.route('/av', avRouter)` (route disabled).
- Numerous `// Old implementation - direct DB queries:` blocks in `admin-apis/*`, `user-apis/*`, and db helpers (historical only).
---
## 7. Checked and NOT dead (for reference)
- `apps/admin-ui` / `user-ui` / `web-ui` exports: **0 truly-unused**. 18 shared exports (`AdminOrderItemCore`, `SkuFlagCore`, `UserStoreSummaryCore`, …) are referenced only within their own file to compose other types — that's normal, not dead.
- Backend functions used only inside their own file (e.g. `cloud_cache` internals `createProductsFileInternal`, `constructCacheUrl`, `clearUrlCache`; `slot-store` `transformSlotToStoreSlot`/`extractSlotInfo`/`fetchAllTransformedSlots`; `trpc-index` `createCallerFactory`) — all reachable via their parent functions, **not dead**.
- `queue-consumer.ts` — although it imports only-in-backend, it IS used by `worker.ts`, so alive.
---
## Caveats
1. **Static analysis only.** A tRPC procedure can still be called by an external/undisclosed client (mobile build, partner integration). Confirm before removing public procedures.
2. **`mergeDuplicateProducts`** and **`expo-service`** look intentionally kept for manual/one-off use — decide whether to delete or document.
3. The `admin-web` tree is present on disk but **untracked** on this branch; it was included in the caller search.
4. Some "dead" management procedures (`staffUser.*`, duplicated `slots`/`product` entries) may be leftovers from older UI screens; safe to remove once confirmed.
## Removal status (executed)
**Removed — 15 tRPC procedures:** `admin.coupon.validate`; `admin.vendorSnippets.getById`, `getVendorOrders`; `admin.slots.getSlotsProductIds`, `updateSlotProducts`, `getSlots`, `deleteSlot`; `admin.product.updateSlotProducts`, `getSlotsProductIds`; `admin.staffUser.getUsers`, `getUserDetails`, `updateUserSuspension`; `admin.user.createUserByMobile`; `common.product.getDashboardTags`; `trpc.hello`.
**Removed — backend functions/constants:** `getJwtSecret`, `getRedisUrl`, `getExpoAccessToken`, `getPhonePeBaseUrl/ClientId/ClientVersion/ClientSecret/MerchantId`, `READABLE_ORDER_ID_KEY`, `WELCOME_MESSAGE`, `defaultRole`, `getOrderDetailsWrapper`, `clearAllCache`, `getAllBanners`, `getTagById`, `getAllTags`, `getDashboardTags`, `getProductSlots`, `getAllProductsSlots`, `getUserNegativity`, `createTRPCRouter`, `createCallerFactory`, and the notification senders `sendOrderPlacedNotification`, `sendPaymentFailedNotification`, `sendOrderOutForDeliveryNotification`, `sendOrderCancelledNotification`, `sendRefundInitiatedNotification` + their message constants.
**Removed — DB helper functions orphaned by the procedures above (from BOTH `db_helper_sqlite` and `db_helper_postgres`, plus their barrel exports and `sqliteImporter` re-exports):**
`createUserByMobile`, `deleteSlotById`, `getVendorOrders`, `updateSlotProducts`, `getSlotsProductIds` (the five behind the deleted endpoints) **and** `getActiveSlots`, `getAllUsers`, `getUserWithDetails`, `validateCoupon`, `checkUnitExists`, `getProductImagesById`, `replaceProductTags` (same class, missed by the first scan because their names also exist in the parallel package).
**Removed — files:** `apps/backend/src/lib/expo-service.ts`, `apps/backend/src/middleware/staff-auth.ts` (only used by the empty `av-router`), `apps/backend/src/apis/admin-apis/apis/av-router.ts` (empty router), `packages/db_helper_sqlite/src/admin-apis/merge-duplicate-products.ts`.
**Removed — wiring:** `avRouter` import/route from `main-router.ts` + `v1-router.ts`; `mergeDuplicateProducts` exports from `db_helper_sqlite/index.ts` and `sqliteImporter.ts`; unused `sendOrder*Notification` import + commented calls in `user-apis/order.ts`; orphaned imports in all touched files.
**Kept (false positives / intentional):** the four Drizzle relation exports (implicitly registered); `mergeDuplicateProducts` was deleted per §3.
**Verification:** `tsc` clean for `apps/backend`, `packages/db_helper_sqlite`, `apps/web-ui`, `apps/admin-ui`, `apps/user-ui`, `apps/admin-web`. (`apps/fallback-ui` has one pre-existing `vite.config.ts` error unrelated to this change.)

View file

@ -1,55 +0,0 @@
# Dependency Audit — packages/ui (common-ui)
Audited 2026-08-16. Packages listed below are declared in `package.json` but **never imported** anywhere in this package's own source (`src/`, `hooks/`, `index.ts`).
## Never used in this package
- `@react-native-google-signin/google-signin`
- `@react-native-picker/picker`
- `@react-navigation/bottom-tabs`
- `@react-navigation/drawer`
- `@react-navigation/elements`
- `buffer`
- `dayjs`
- `expo`
- `expo-blur`
- `expo-dev-client`
- `expo-device`
- `expo-font`
- `expo-haptics`
- `expo-linear-gradient`
- `expo-linking`
- `expo-notifications`
- `expo-router`
- `expo-splash-screen`
- `expo-symbols`
- `expo-system-ui`
- `formik`
- `jwt-decode`
- `react-dom`
- `react-hook-form`
- `react-native-gesture-handler`
- `react-native-pager-view`
- `react-native-phonepe-pg`
- `react-native-razorpay`
- `react-native-reanimated`
- `react-native-safe-area-context`
- `react-native-screens`
- `react-native-tab-view`
- `react-native-toast-message`
- `react-native-web`
- `react-native-webview`
- `yup`
## Caveats
- Several of the above (`react-native-gesture-handler`, `react-native-reanimated`, `react-native-safe-area-context`, `react-native-screens`, `react-navigation/*`, `expo-router`, etc.) are runtime peer/transitive requirements of `@react-navigation/native` and the consuming Expo apps, which declare them in their own `package.json`. They are unused in `packages/ui` but not removable from the workspace if the apps rely on hoisting.
- `expo` (base) is not imported directly but is required by the `expo-*` modules that are used.
- Safest candidates for removal (not used by apps either): `expo-dev-client`, `react-native-phonepe-pg`.
## Imported but not declared (opposite problem)
The package imports these without listing them in `package.json`; they currently resolve via hoisting:
- `expo-auth-session`
- `react-native-svg`

View file

@ -1,254 +0,0 @@
# Plan — Part 1/2: Backend + Admin UIs (three-table consts model)
Part 1 of 2. Covers the DB model, KV, migration, backend, and the **admin UIs**
(`apps/admin-ui`, `apps/admin-web`, `apps/superadmin-ui`). Part 2 covers `apps/user-ui`
(see `consts-three-tables-part2-user-ui.md`). Supersedes `three-table-consts-model.md`.
## 0. Decisions
- Scope Part 1: backend + admin-ui + admin-web + superadmin-ui.
- `allItemsOrder` is **region-scoped** (one row per region in `region_consts`), grouped with
`popularItems`.
- Leftover keys stay in `key_val_store`: `platformFeePercent`, `taxRate`, `tester`,
`minOrderAmountForCoupon`, `maxCouponDiscount`, `flashDeliverySlotId`, `readableOrderId`,
`tagsOrder`.
- `region_cache_versions` + `region_bound_settings` are dropped after data copy.
- Precomputed flat JSON per bound in the KV gen namespace (§2) — consumed by user-ui (Part 2).
- AGENTS.md: do NOT run migrations (user runs), do NOT run the test suite, do NOT use git.
Append planned diffs + timestamp to `change-log.txt` before editing non-`.md`/`.txt` files.
## 1. Data model
New tables (`packages/db_helper_sqlite/src/db/schema.ts`):
```
global_consts (key TEXT PRIMARY KEY, value TEXT)
region_consts (region_id INTEGER FK->regions.id, key TEXT, value TEXT, PK(region_id,key))
region_bound_consts (bound_id INTEGER FK->region_bounds.id, region_id INTEGER FK->regions.id,
key TEXT, value TEXT, PK(bound_id,key))
```
| Table | Keys |
|---|---|
| `global_consts` | `versionNum`, `playStoreUrl`, `appStoreUrl`, `internalAppVersion` |
| `region_consts` | `products_version_num` (was `cache_version`), `availability_version_num`, `slots_version_num`, `popularItems`, `allItemsOrder`, `isFlashDeliveryEnabled`, `supportMobile`, `supportEmail`, `welcomeMessage` |
| `region_bound_consts` | `minRegularOrderValue`, `freeDeliveryThreshold`, `deliveryCharge`, `flashFreeDeliveryThreshold`, `flashDeliveryCharge` |
| `key_val_store` (kept) | `platformFeePercent`, `taxRate`, `tester`, `minOrderAmountForCoupon`, `maxCouponDiscount`, `flashDeliverySlotId`, `readableOrderId`, `tagsOrder` |
- Region-level keys are one row per region (no bound precedence). Bound-level keys stay per bound.
- Version counters (`products_version_num`/`availability_version_num`/`slots_version_num`) live in
`region_consts`, auto-created default 1.
- `allItemsOrder`: exactly one row per region; identical for every bound in that region.
## 2. KV model
- Key `essentialConsts_{boundId}` in `freshyo_gen`/`freshyo_gen_dev`. Flat value =
`{ ...global, ...region, ...bound, assetsDomain, apiCacheKey, regionId, boundId, webviewHtml, isWebviewClosable }`.
- Numbers/booleans coerced (`Number()` / boolean) at build time; other values raw strings.
## 3. Migration (author only — user runs)
`packages/db_helper_sqlite/drizzle/0009_three_const_tables.sql` + journal idx 9
(`0009_three_const_tables`). Steps: CREATE the 3 tables; copy `global_consts` (4 keys) from
`key_val_store`; copy `region_consts` version counters from `region_cache_versions` and region
business keys (incl. `allItemsOrder`) from each region's lowest-priority bound's
`region_bound_settings`; copy the 5 bound keys into `region_bound_consts`; DELETE the migrated keys
from `key_val_store` (keep the 8 leftovers); DROP `region_bound_settings` + `region_cache_versions`.
(full SQL is in `docs/consts-three-tables-changes.md` §2.2 — reuse it verbatim.)
## 4. Backend
### 4.1 `packages/db_helper_sqlite`
- **`src/db/schema.ts`**: add `globalConsts`, `regionConsts`, `regionBoundConsts`; remove
`regionCacheVersions` + `regionBoundSettings` and their relations.
- **`src/lib/const-keys.ts`**: add `GLOBAL_CONST_KEYS`, `REGION_CONST_KEYS`, `BOUND_CONST_KEYS`,
`LEGACY_CONST_KEYS`; keep merged `CONST_KEYS` + labels/types/visibility/defaults; add
`products_version_num`; add `CONST_SCOPE` (`global|region|bound|legacy`).
- **`src/admin-apis/const.ts`**:
- add `getAllGlobalConsts()`, `upsertGlobalConsts(rows)`, `getRegionConsts(regionId)`,
`upsertRegionConsts(regionId, rows)`, `getBoundConsts(boundId)`,
`upsertBoundConsts(boundId, regionId, rows)`, `getLegacyConsts()`, `upsertLegacyConsts(rows)`.
- keep `getAllConstants`/`upsertConstants` working: `getAllConstants()` = merged
global+legacy (+ `CONST_DEFAULTS`); `upsertConstants(rows, regionId?)` routes by `CONST_SCOPE`.
- remove the dead global counters (`get/incrementCacheVersion`, availability, slots).
- **`src/lib/region-cache-versions.ts`**: back it with `region_consts`
(`products_version_num`/`availability_version_num`/`slots_version_num`), auto-create rows;
public signatures/return type unchanged (`cloud_cache.ts` untouched).
- **`src/superadmin-apis/regions.ts`**:
- `getBoundSettings(boundId)` → `region_bound_consts` only (5 keys), `Record<string,string|null>`.
- `upsertBoundSettings(boundId, settings)` → `region_bound_consts` (look up regionId from bound).
- add `getRegionConstants(regionId)` / `upsertRegionConstants(regionId, rows)`.
- `getEffectiveRegionSettings(regionId)` → merged region + effective bound (shape unchanged).
- add `getEffectiveBoundId(regionId)`; `getAllRegions()` → add `effectiveBoundId`.
- `createRegionWithBounds`/`createRegionBound` → seed default rows + version counters (1/1/1).
- **`src/db/seed.ts` + `src/db/seed.sql`**: seed the 3 tables (incl. per-region `allItemsOrder`);
leftovers keep going to `key_val_store`.
- **`index.ts`**: export the new helpers; drop removed ones.
### 4.2 `packages/shared`
- **`types/region.types.ts`**: `RegionSummary.effectiveBoundId?: number | null`.
- **`types/const.types.ts`**: unchanged (`Constant`, `ConstantUpdateResult`); optional add
`GlobalConstKey`/`RegionConstKey`/`BoundConstKey` union types if useful to the UIs.
### 4.3 `apps/backend` core
- **`src/lib/const-keys.ts`**: mirror the four key groups (`allItemsOrder` in `REGION_CONST_KEYS`).
- **`src/lib/const-store.ts`**: `getGlobalConstValues()`, `getRegionConstValues(regionId)`,
`getBoundConstValues(boundId)`; `getConstant(key)` (tagsOrder) stays on `key_val_store`.
- **`src/lib/gen-store.ts`**: `GEN_KV_KEY='essentialConsts'`, `genKvKeyForBound(boundId)`,
`refreshGenKv(boundId?)`, `refreshGenKvForRegion(regionId)`, `readEssentialConstsFromKv(boundId)`.
- **`src/trpc/apis/common-apis/common-trpc-index.ts`**: `scaffoldEssentialConsts(boundId)`;
`essentialConsts` input `{ boundId }`; `listRegions` returns `effectiveBoundId`; `regionSettings`
merged.
- **`src/lib/cloud_cache.ts`**: `refreshGenKvForRegion(regionId)`; essential-consts CDN file uses the
effective bound.
- **`src/lib/flash-delivery-cron.ts`**: `isFlashDeliveryEnabled` now region-level → write
`region_consts` for all regions, then `refreshGenKv()`.
- **`src/lib/seed.ts`**: new db seeds + `refreshGenKv()`.
- **`src/sqliteImporter.ts`**: re-export new helpers.
### 4.4 tRPC endpoint surface (new / repointed)
Keep old `admin.const.getConstants`/`updateConstants` as **backward-compat aliases** (tests at
`apps/backend/tests/helpers/consts.ts` + any stragglers). Add clean, scoped endpoints:
| Endpoint | Kind | Scope | Notes |
|---|---|---|---|
| `admin.const.getGlobalConstants` / `updateGlobalConstants` | query/mutation | staff | `global_consts` (4 keys) |
| `admin.const.getLegacyConstants` / `updateLegacyConstants` | query/mutation | staff | `key_val_store` leftovers (`tagsOrder`, coupons, etc.) |
| `admin.const.getConstants` / `updateConstants` | query/mutation | staff | **alias**: merged global+legacy; update routes by scope |
| `admin.region.getRegionConstants` / `updateRegionConstants` | query/mutation | staff region | `region_consts` for `ctx.staffUser.regionId` |
| `admin.region.getBoundSettings` / `updateBoundSettings` | query/mutation | staff region | `region_bound_consts` (5 keys); add `refreshGenKvForRegion` after write |
| `superadmin.const.getGlobalConstants` / `updateGlobalConstants` | query/mutation | superadmin | NEW router (fixes the current `admin.const` guard mismatch) |
| `superadmin.const.getLegacyConstants` / `updateLegacyConstants` | query/mutation | superadmin | leftovers |
| `superadmin.regions.getRegionConstants` / `updateRegionConstants` | query/mutation | superadmin | `{ regionId }` + constants |
| `superadmin.regions.boundSettings` / `updateBoundSettings` | query/mutation | superadmin | repointed to `region_bound_consts`; `refreshGenKvForRegion` |
- `update*` handlers validate keys against their group (`GLOBAL_CONST_KEYS` / `REGION_CONST_KEYS` /
`BOUND_CONST_KEYS` / `LEGACY_CONST_KEYS`) and refresh KV for the affected scope.
- `admin.region.updateRegionConstants` and `superadmin.regions.updateRegionConstants` taking
`isFlashDeliveryEnabled`/etc. must `refreshGenKvForRegion(regionId)`.
- Version-counter keys (`products_version_num`, etc.) are **not** editable via these endpoints
(read-only in `getRegionConstants`, ignored on write).
### 4.5 `apps/backend` routers to edit
- `src/trpc/apis/admin-apis/apis/const.ts` — new global/legacy procedures + alias.
- `src/trpc/apis/admin-apis/apis/region.ts` — `getRegionConstants`/`updateRegionConstants`;
`getBoundSettings`/`updateBoundSettings` → bound table + KV refresh.
- `src/trpc/apis/superadmin-apis/apis/regions.ts` — bound settings repoint + region constants +
`refreshGenKvForRegion`.
- new `src/trpc/apis/superadmin-apis/apis/const.ts` (`superadminConstRouter`) +
register in `superadmin-apis/superadmin-trpc-index.ts`.
- `src/trpc/apis/admin-apis/apis/admin-trpc-index.ts` — const router still mounted; nothing new
needed beyond procedure additions.
## 5. Admin UI — `apps/admin-ui`
All key maps are **local** in `app/(drawer)/dashboard/customize-app/index.tsx`
(`CONST_LABELS` 11–33, `CONST_VISIBILITY` 35–58, `BOUND_KEY_TYPES` 61–75, `REGIONAL_KEYS` 77,
`parseBoundValue` 80–102, `serializeBoundValue` 105–120, local `ConstantInput` 122–261).
### 5.1 `customize-app/index.tsx`
- Replace the 2-way switch (`mode: 'bounds' | 'global'`, line 265) with **3 tabs**:
**Global** / **Region** / **Bound**.
- **Global tab** → `admin.const.getGlobalConstants`/`updateGlobalConstants`; rows = the 4
`GLOBAL_CONST_KEYS` (visibility-controlled) + a "Legacy" subsection for
`admin.const.getLegacyConstants` (only if you want `tagsOrder`/coupon keys exposed; otherwise omit).
- **Region tab** → `admin.region.getRegionConstants`/`updateRegionConstants`; rows =
`REGION_CONST_KEYS` minus the 3 version counters (display-only). `popularItems` / `allItemsOrder`
keep `allowSectionNavigation` links to their editors (§5.2).
- **Bound tab** → keep the existing per-bound tabs + Formik, but `REGIONAL_KEYS` shrinks to the 5
`BOUND_CONST_KEYS` (`minRegularOrderValue`, `freeDeliveryThreshold`, `deliveryCharge`,
`flashFreeDeliveryThreshold`, `flashDeliveryCharge`) via
`admin.region.getBoundSettings`/`updateBoundSettings`. Remove the 6 region-level keys from
`BOUND_KEY_TYPES`.
- Rebuild `CONST_LABELS`/`CONST_VISIBILITY`/type maps from the key groups (or import a small shared
keys module — see §5.5); keep the local `ConstantInput` (incl. `allowSectionNavigation`).
### 5.2 `customize-app/popular-items.tsx` + `all-items-order.tsx`
- These are now **region-scoped** (`region_consts`): switch reads/writes from `admin.const.*` to
`admin.region.getRegionConstants`/`updateRegionConstants` (same `{ key, value:number[] }` payload;
keep the array-or-CSV parse). Invalidate `region.getRegionConstants`.
### 5.3 `product-tags/order.tsx`
- `tagsOrder` stays a **global leftover** in `key_val_store` → switch to
`admin.const.getLegacyConstants`/`updateLegacyConstants` (payload unchanged; still triggers
`scheduleStoreInitialization()` server-side).
### 5.4 `components/OrderOptionsMenu.tsx`
- `welcomeMessage` is now in `region_consts` → read it from `admin.region.getRegionConstants`
instead of `admin.const.getConstants`.
### 5.5 (optional) shared keys module
- Consider extracting the key groups + labels into a small `apps/admin-ui/src/constants/const-keys.ts`
to stop the label/visibility drift; not required.
## 6. Admin UI — `apps/admin-web`
Mirror of admin-ui (single file `src/routes/dashboard.customize-app.tsx`: `CONST_LABELS` 14–35,
`CONST_VISIBILITY` 37–59, `BOUND_KEY_TYPES` 64–76, `REGIONAL_KEYS` 78, local `ConstantInput` 123–256).
- `dashboard.customize-app.tsx`: 3 tabs (Global/Region/Bound) as §5.1; `handleBoundSubmit`
(323–354) writes the 5 bound keys; `handleGlobalSubmit` (356–383) writes global (+ legacy).
- `dashboard.customize-app.popular.tsx` (110–204) and `.ordering.tsx` (97–183): switch to
`admin.region.getRegionConstants`/`updateRegionConstants`; invalidate that key.
- `dashboard.product-tags.order.tsx` (90–174): switch to `admin.const.getLegacyConstants`/
`updateLegacyConstants`.
- Keep the local `ConstantInput` + `allowSectionNavigation`.
## 7. Admin UI — `apps/superadmin-ui`
- **`src/routes/constants.tsx`**: currently calls `admin.const.*` under a **superadmin** token,
which is `protectedProcedure` → UNAUTHORIZED. Switch to the new `superadmin.const.*`
(`getGlobalConstants`/`updateGlobalConstants` + `getLegacyConstants`/`updateLegacyConstants`).
Split the single form into Global (+ Legacy) sections; drop the region/bound keys from this screen
(they move to the Regions page).
- **`src/routes/regions.tsx`**: `SETTING_KEYS` (18–30) currently mixes region keys + bound keys.
Split into:
- **Region constants** editor (new `RegionConstantsEditor`) using
`superadmin.regions.getRegionConstants`/`updateRegionConstants({ regionId })` for the region
keys (popularItems, allItemsOrder, isFlashDeliveryEnabled, supportMobile, supportEmail,
welcomeMessage).
- **Bound constants** editor (`BoundSettingsEditor`, 383–436) uses `SETTING_KEYS` reduced to the
5 bound keys via `superadmin.regions.boundSettings`/`updateBoundSettings`.
- Keep the `EFFECTIVE` badge logic (bounds sorted by priority; effective = first).
## 8. Out of scope (Part 1)
- `apps/user-ui` — Part 2.
- `apps/web-ui` storefront — still calls `common.essentialConsts({ regionId })` and will fail input
validation once the input becomes `{ boundId }`. Not migrated here; flagged. (Optional follow-up:
accept `{ regionId }` and map via `getEffectiveBoundId(regionId)`.)
## 9. Verification
0. Append planned diffs + timestamp to `change-log.txt` first.
1. Typecheck: `npx tsc --noEmit --project packages/db_helper_sqlite/tsconfig.json`,
`... apps/backend/tsconfig.json`, `... apps/admin-ui/tsconfig.json`,
`... apps/superadmin-ui/tsconfig.json`, `... apps/admin-web/tsconfig.json`
(admin-web package has its own `typecheck` script).
2. After migration 0009: verify the three tables populated, `key_val_store` keeps the 8 leftovers,
exactly one `allItemsOrder` per region.
3. Endpoints: `admin.const.getGlobalConstants` (4 keys), `admin.region.getRegionConstants` (9 keys,
versions read-only), `admin.region.getBoundSettings` (5 keys); `superadmin.const.*` works with a
superadmin token; writes refresh KV (`essentialConsts_{boundId}` in `freshyo_gen`).
4. Admin smoke: Global/Region/Bound tabs save to the correct tables; popular/all-items edits hit
`region_consts`; tagsOrder edit still triggers cache regeneration.
## 10. Checklist
1. `change-log.txt` — append planned diffs.
2. `packages/db_helper_sqlite`: schema, `0009` migration + journal, const-keys, admin-apis/const,
region-cache-versions, superadmin-apis/regions, seed, index exports.
3. `packages/shared`: `region.types.ts` (`effectiveBoundId`).
4. `apps/backend`: const-keys, const-store, gen-store, common-trpc-index, cloud_cache,
flash-delivery-cron, seed, sqliteImporter, admin const/region routers, superadmin regions router,
new superadmin const router.
5. `apps/admin-ui`: customize-app (3 tabs), popular-items, all-items-order, product-tags/order,
OrderOptionsMenu.
6. `apps/admin-web`: customize-app (3 tabs), popular, ordering, product-tags/order.
7. `apps/superadmin-ui`: constants.tsx (superadmin.const.*), regions.tsx (region + bound editors).
8. Typecheck all five projects; fix self-introduced errors.

View file

@ -1,122 +0,0 @@
# Plan — Part 2/2: user-ui (consume the per-bound flat JSON)
Part 2 of 2. Adapts **`apps/user-ui`** to request the precomputed flat JSON by `boundId` and read
the flat shape. Backend + admin UIs are Part 1
(`consts-three-tables-part1-backend-admin.md`) and must land first (the client depends on
`{ boundId }` input, `listRegions.effectiveBoundId`, and the flat payload).
## 0. Decisions
- user-ui **sends `boundId`** (persisted client-side) and reads the flat JSON.
- Scope: `apps/user-ui` only. `apps/web-ui` stays on the old contract (breaks; see §4).
- AGENTS.md: no test runs, no migrations, no git; log planned diffs to `change-log.txt` before
editing non-`.md`/`.txt` files.
## 1. Flat JSON contract (from Part 1)
`common.essentialConsts({ boundId })` returns the union of global + region + bound rows plus
identity/env:
```jsonc
{
"versionNum": "1.1.0", "playStoreUrl": "...", "appStoreUrl": "...", "internalAppVersion": 1,
"products_version_num": 2, "availability_version_num": 2, "slots_version_num": 2,
"popularItems": "[]", "allItemsOrder": "[]", "isFlashDeliveryEnabled": true,
"supportMobile": "...", "supportEmail": "...", "welcomeMessage": "...",
"minRegularOrderValue": 300, "freeDeliveryThreshold": 300, "deliveryCharge": 20,
"flashFreeDeliveryThreshold": 500, "flashDeliveryCharge": 69,
"assetsDomain": "...", "apiCacheKey": "...", "regionId": 1, "boundId": 7,
"webviewHtml": null, "isWebviewClosable": true
}
```
- `allItemsOrder` is the region's value (identical across bounds of the same region).
- The nested `effectiveSettings`/`regionSettings` block is gone.
- `EssentialConstsApiType` (`@backend/trpc/router`) already reflects this (derived from
`scaffoldEssentialConsts`).
## 2. Region-bound state (client must know its boundId)
Today the client knows only `regionId` (persisted in `regionStore`); the resolved bound is
transient. Changes:
### 2.1 `src/store/regionStore.ts`
- Add `selectedBoundId: number | null`.
- `setRegion(region: RegionSummary, boundId?: number | null)` persists both; include
`selectedBoundId` in `partialize`; extend the no-op guard to compare boundId.
### 2.2 `src/hooks/useRegion.ts`
- Expose `boundId` (from the store) on `UseRegionResult`.
- On a successful `resolveRegionByLocation`, persist
`setRegion(resolved.region, resolved.bound.id)` (instead of region-only).
### 2.3 `src/lib/region-switch.ts`
- `confirmRegionSwitch(region, queryClient, boundId?)` forwards the boundId to
`regionStore.setRegion` (manual picks get the region's effective bound id).
### 2.4 `src/components/RegionSelector.tsx`
- `listRegions` now returns `effectiveBoundId` per region → pass it through
`confirmRegionSwitch` so a manually chosen region still has a `boundId`.
## 3. Consuming the flat JSON
### 3.1 `src/hooks/prominent-api-hooks.ts`
- **`useGetEssentialConsts`**
- read `boundId` from `useRegion()` (not `regionId`);
- `trpc.common.essentialConsts.useQuery({ boundId }, { refetchInterval: 60000, enabled: isReady && boundId != null, placeholderData: initialData })`;
- persist under `` `essential_consts_b${boundId}` `` (was `essential_consts_r{regionId}`).
- **URL builders** (rename to the new keys):
- `useCacheUrl` / `useStoreWithProducts` → `products_version_num` (was `cacheVersion`);
- `useAvailabilityCacheUrl` → `availability_version_num`;
- `useSlotsCacheUrl` → `slots_version_num`;
- region id in URLs → `data.regionId` (via `useDiscoveryRegionId`, now reading the flat
`regionId` with `useRegion().regionId` fallback).
- **`useRegionalConsts`** → thin passthrough of the flat data (delivery values are already
top-level). Keep the exported function so `cart-page`, `checkout-page`, `floating-cart-bar`, and
`PaymentAndOrderComponent` need no edits.
- Remove the `effectiveSettings`/`regionSettings` fallback fields from `DiscoveryData` and the now
unused `discoverySettings` helper.
### 3.2 Unchanged (verify only)
- `cart-page.tsx`, `checkout-page.tsx`, `floating-cart-bar.tsx`, `PaymentAndOrderComponent.tsx`
keep reading `deliveryCharge` / `flashDeliveryCharge` / `freeDeliveryThreshold` /
`flashFreeDeliveryThreshold` / `minRegularOrderValue` (now flat).
- `AddToCartDialog.tsx` (`isFlashDeliveryEnabled`), `flash-delivery/_layout.tsx`
(`isFlashDeliveryEnabled`), `NextOrderGlimpse.tsx` (`supportMobile`),
`me/complaints/index.tsx` (`supportMobile`/`supportEmail`), `UpdateChecker.tsx`
(`internalAppVersion`), `HealthTestWrapper.tsx` (`versionNum`/`playStoreUrl`/`appStoreUrl`),
`WebViewWrapper.tsx` (`webviewHtml`/`isWebviewClosable`) — field names unchanged in the flat JSON.
- `LocationBar.tsx`, `LocationTestWrapper.tsx`, `FirstUserWrapper.tsx` — region-only; unaffected.
## 4. Out of scope / consequences
- **`apps/web-ui`** (`src/hooks/prominent-api-hooks.ts`) still calls
`common.essentialConsts({ regionId })` and reads `cacheVersion`/`availabilityVersionNum`/
`slotsVersionNum` → will fail input validation and show no data until migrated. Not in this plan.
- If the hard break must be avoided, Part 1 can add a `regionId` fallback (server maps to
`getEffectiveBoundId(regionId)`); then web-ui keeps working read-only. Decide before shipping.
## 5. Verification
0. Append planned diffs + timestamp to `change-log.txt` first.
1. Typecheck: `npx tsc --noEmit --project apps/user-ui/tsconfig.json`.
2. Smoke (after Part 1 is deployed + migration 0009 applied):
- Pick/auto-resolve a region → `boundId` persisted in `freshyo-region`.
- `common.essentialConsts` called with `{ boundId }`; payload cached under
`essential_consts_b{boundId}`.
- Catalog URLs contain `products_version_num` / `availability_version_num` /
`slots_version_num` and the correct `regionId`.
- Cart/checkout show the selected bound's delivery values; switching region updates them.
- Flash gate (`isFlashDeliveryEnabled`), update gate (`internalAppVersion`/`versionNum`),
support links, and webview notice all still work.
## 6. Checklist
1. `change-log.txt` — append planned diffs.
2. `src/store/regionStore.ts` — `selectedBoundId` + persist.
3. `src/hooks/useRegion.ts` — expose `boundId`; persist on resolve.
4. `src/lib/region-switch.ts` — forward boundId.
5. `src/components/RegionSelector.tsx` — use `effectiveBoundId`.
6. `src/hooks/prominent-api-hooks.ts` — `{ boundId }` input, per-bound cache key, renamed
version fields, simplified `useRegionalConsts`, drop `effectiveSettings` fallbacks.
7. Typecheck `apps/user-ui`; fix self-introduced errors.

View file

@ -1,141 +0,0 @@
# Duplicate / Same-Product Products in `local_8_aug.sql`
**Source:** `apps/backend/dumps/local_8_aug.sql` · **product_info rows:** 135 · **SKUs:** 135 (each product currently has exactly one SKU in this dump)
> These are products that represent the **same underlying item** but were entered as separate
> `product_info` rows (each with its own SKU) — only the pack size, weight, cut or naming differs.
> In a proper multi-SKU setup, each group below should be **one product with multiple SKUs**.
---
## 🔴 Clear duplicates (same product, different pack/weight)
### 1. Tomato
Exact same name — only the pack quantity differs.
| product_info id | name | quantity | store |
|---|---|---|---|
| 17 | `Tomato` | 1.0 Kg | Vegetables |
| 45 | `Tomato` | 0.5 Kg | Vegetables |
### 2. Mutton Curry Cut (Regular)
Same product — two weights (500 g vs 750 g).
| product_info id | name | quantity | store |
|---|---|---|---|
| 98 | `Mutton Curry Cut (Regular)– 500 g` | 0.5 Kg | Meat Store |
| 99 | `Mutton Curry Cut (Regular) – 750 g` | 0.75 Kg | Meat Store |
### 3. Mutton Boneless
Same cut — regular pack vs mini pack.
| product_info id | name | quantity | store |
|---|---|---|---|
| 28 | `Mutton Boneless` | 0.5 Kg | Meat Store |
| 34 | `Mutton Boneless – Mini Pack` | 0.25 Kg | Meat Store |
### 4. Chicken Breast
Same cut — 500 g pack vs mini pack.
| product_info id | name | quantity | store |
|---|---|---|---|
| 2 | `Chicken Breast 500 g` | 0.5 Kg | Meat Store |
| 42 | `Chicken Breast Boneless - Mini Pack` | 0.25 Kg | Meat Store |
### 5. Chicken (regular cut)
Same cut of chicken — small pieces vs large pieces.
| product_info id | name | quantity | store |
|---|---|---|---|
| 23 | `Chicken ( regular cut )- Small pieces` | 0.5 Kg | Meat Store |
| 40 | `Chicken (regular cut) Large pieces` | 0.5 Kg | Meat Store |
### 6. Coriander Leaves (Kothimeer)
Same product listed twice — one entry named "small 1".
| product_info id | name | quantity | store |
|---|---|---|---|
| 76 | `Coriander Leaves (Kothimeer)` | 1.0 Pc | Vegetables |
| 101 | `Coriander Leaves (Kothimeer) small 1` | 1.0 Pc | Vegetables |
### 7. Pineapple
Same product — regular vs "Large".
| product_info id | name | quantity | store |
|---|---|---|---|
| 57 | `Pineapple` | 1.0 Pc | The Fruit Store |
| 96 | `Pineapple – Large` | 1.0 Pc | The Fruit Store |
### 8. Carrot / Red Carrot
Indian carrots are red/orange — almost certainly the same vegetable at different weights.
| product_info id | name | quantity | store |
|---|---|---|---|
| 69 | `Carrot` | 0.25 Kg | Vegetables |
| 79 | `Red Carrot` | 0.5 Kg | Vegetables |
### 9. Mutton / Lamb Mutton
Same meat sold under two names.
| product_info id | name | quantity | store |
|---|---|---|---|
| 4 | `Mutton` | 1.0 Kg | Meat Store |
| 12 | `Lamb Mutton` | 1.0 Kg | Meat Store |
### 10. Raisins (kishmish)
Same product — regular vs black raisins.
| product_info id | name | quantity | store |
|---|---|---|---|
| 131 | `Raisins (kishmish)` | 0.25 Kg | Dry Fruits store |
| 134 | `black raisin ( kishmish)` | 0.25 Kg | Dry Fruits store |
### 11. Fig (Anjeer) / Dried Figs
Same fruit — fresh vs dried.
| product_info id | name | quantity | store |
|---|---|---|---|
| 26 | `Fig (Anjeer)` | 0.25 Kg | The Fruit Store |
| 132 | `Dried figs (Anjeer)` | 0.25 Kg | Dry Fruits store |
### 12. Country Chicken
Same bird sold as "Desi live" vs "Farm Raised".
| product_info id | name | quantity | store |
|---|---|---|---|
| 80 | `Country Chicken (Desi / Natu Kodi) live .` | 1.0 Kg | Meat Store |
| 128 | `Country Chicken (Farm Raised)` | 1.0 Kg | Meat Store |
---
## 🟡 Borderline — same family, but likely intentional (different varieties/parts)
These share a base name but are arguably distinct products (different variety, colour or cut).
Listed for completeness in case any should be merged.
| Group | product_info ids |
|---|---|
| Mango (generic) vs Kesari Mango vs Mallika Mango | 39, 125, 126 |
| Apple (pack of 3) vs Green Apple (pack 2) vs Irani Apple (pack of 4) | 6, 47, 100 |
| Grapes: Muscat / Green / Red Globe / Black Beauty | 55, 60, 61, 62 |
| Dragon Fruit: White vs Pink | 25, 63 |
| Cabbage vs Purple Cabbage | 66, 88 |
| Capsicum: green `Capsicun` vs Red & Yellow | 127, 93 |
| Prawns: Tiger (large) vs Medium (cleaned & deveined) | 81, 82 |
| Chicken parts: Liver, Lollipops, Leg piece, Leg with Thigh, Gizzard, Boneless, Whole | 1, 3, 10, 36, 15, 24, 21 |
| Mutton parts: Head, Brain, Paya, Chops, Soup Bones, Boti, Kheema | 20, 84, 85, 86, 87, 14, 35 |
| Brinjal vs Light Purple Brinjal | 27, 89 |
| Shahtoot (fruit) vs Shahtoot Malai (dessert) | 51, 119 |
| Fig (fruit) vs Fresh Fig Juice | 26, 105 |
---
## Notes
- The dump currently maps **1 product → 1 SKU → 1 `quantity` feature**, so every "duplicate" above
is a separate `product_info` row. Merging these into one product with multiple SKUs would also
require migrating `product_combos`, `product_group_membership`, `orders`/`order_items`,
`home_banners`, `delivery_slot_info.sku_ids`, `vendor_snippets.sku_ids` and `coupons.sku_ids`
references from the old SKU ids to the surviving ones.
- No price data exists in this dump's `product_skus`/`sku_features` (prices live elsewhere in the
current schema), so the comparison is based on name + quantity feature only.

View file

@ -1,467 +0,0 @@
# Regions: Code Change Specification
Date: 2026-10-07
Status: Implementation specification only
Companion: `docs/regions-proposal.md`
No application changes are made by this document. Examples specify intended contracts and behavior; adapt exact imports, field names, and existing helper signatures to the repository during implementation.
## 1. Schema changes
### 1.1 New entities
In `packages/db_helper_sqlite/src/db/schema.ts`, introduce these Drizzle tables:
```ts
regions = {
id: integer primary key autoIncrement,
name: required text,
description: nullable text,
createdAt: required timestampText default CURRENT_TIMESTAMP,
}
regionBounds = {
id: integer primary key autoIncrement,
regionId: required integer references regions.id,
description: nullable text,
geojson: required jsonText<PolygonFeatureCollection>,
priority: required numeric value,
}
// UNIQUE(region_id, priority)
regionBoundSettings = {
id: integer primary key autoIncrement,
boundId: required unique integer references regionBounds.id,
// Explicit delivery/checkout fields mapped from existing constants.
}
superadmins = {
id: integer primary key autoIncrement,
username: required unique text,
passwordHash: required text,
createdAt: required timestampText default CURRENT_TIMESTAMP,
}
```
Use SQL names `regions`, `region_bounds`, `region_bound_settings`, and `superadmins`; snake-case column names. Use the repository's JSON and timestamp helpers. Final bound-setting columns must be derived from existing delivery-charge, minimum-order, and flash-delivery code, not speculative defaults.
Define relations for regions → bounds, bounds → settings, and each region-owned root record → region. A nullable product `storeId` remains nullable.
### 1.2 Ownership columns
Add `regionId: integer('region_id').notNull().references(() => regions.id)` to root records identified in the proposal: products, staff, stores, snippets, tags, groups, slots, coupons, banners, zones, addresses, and orders.
Do not duplicate the column on every dependent table unnecessarily. For example, SKU ownership is resolved through its product, and order-item ownership through its order. Validate the SKU/order region match when inserting order items.
Add indexes for actual access patterns:
- Root record `region_id` filters.
- Region + order pagination/filter columns where supported by query plans.
- `order_items.order_id` and `order_status.order_id` relation lookups.
- Bound `(region_id, priority)` uniqueness/index.
Index existence must be checked against existing migration SQL as well as the Drizzle schema. Do not assume deployed indexes are absent merely because they are not declared in the current schema.
### 1.3 Migration code
Prepare, but do not run, a migration with this ordering:
1. Create regions and insert `Mahabubnagar` immediately.
2. Create bounds/settings and insert exact GeoJSON from both attached map files, priorities 1 and 2 respectively.
3. Populate both bounds' settings from current behavior.
4. Backfill ownership fields using the newly inserted region ID.
5. Enforce non-null ownership and rebuild SQLite tables if required, preserving foreign keys and data.
6. Create superadmins and immediately insert username `superadmin` with the supplied bcrypt hash from the proposal.
Do not hash the bootstrap hash again. Do not default all future inserts to Mahabubnagar: new root records must receive their region from an authorized creation path.
Update the supported PostgreSQL schema consistently, without switching the active backend or executing PostgreSQL migrations.
### 1.4 Required table-recreation guide
Follow `docs/recreate-referenced-tables.md` whenever migration changes require recreating a table. Do not use a naive single-parent create/copy/drop/rename sequence on populated referenced tables.
- Audit the complete recursive FK dependency subgraph, including grandchildren and objects outside the current Drizzle schema.
- Document mandatory read-only target preflight for legacy tables, views, triggers, and affected indexes. Preparing this document does not authorize remote database access.
- Derive replacement definitions from the actual migration target state, preserving all columns, IDs, defaults, constraints, and relations.
- Create/copy replacements parent-first; replacement foreign keys reference replacement names where required.
- Drop originals leaf-first only after no live original child references them.
- Rename replacements parent-first and recreate indexes after original index names have been released.
- Use unqualified CHECK column expressions so table promotion does not leave stale table-name references.
- Do not rely on toggling foreign-key enforcement to make D1 drops safe.
- Provide verification steps for preserved row counts, clean `foreign_key_check`, restored indexes, absence of replacement leftovers, and continued FK/CHECK/NOT NULL enforcement.
Prepare a populated-data, statement-by-statement proof harness following the guide when necessary, but do not run it without explicit authorization. Migration execution remains the user's responsibility.
## 2. Shared TypeScript contracts
Add `packages/shared/types/region.types.ts` and `superadmin.types.ts`, and export them through shared entry points.
Illustrative public contracts:
```ts
interface RegionSummary {
id: number
name: string
description: string | null
}
interface RegionBoundDto {
id: number
regionId: number
description: string | null
geojson: PolygonFeatureCollection
priority: number
}
interface EffectiveRegionSettings {
regionId: number
boundId: number
priority: number
// Existing delivery/checkout settings, explicitly typed.
}
interface StaffSession {
id: number
name: string
regionId: number
regionName: string
}
interface SuperadminSession {
id: number
username: string
}
```
Use a typed GeoJSON dependency if already available, or define the required FeatureCollection/Polygon structure locally. Preserve feature properties and holes; validate coordinate/ring structure at runtime.
Extend address DTOs and inputs with region ownership. Extend order summaries/details with region identity/name. Extend cache discovery contracts with region ID and regional URLs/versions. Do not expose `passwordHash` through shared public DTOs.
## 3. Identity and request context
### 3.1 Token separation
Use an explicit identity discriminator in newly issued JWT claims:
```ts
type IdentityClaims =
| { identityType: 'user'; userId: number }
| { identityType: 'staff'; staffId: number }
| { identityType: 'superadmin'; superadminId: number }
```
Resolve the referenced identity from the appropriate database table. Staff region is resolved from the staff row, not trusted from token/client input. Decide how old tokens are expired or supported during rollout; never treat an old staff token as superadmin authority.
### 3.2 tRPC context
Update `apps/backend/src/app.ts` and `src/trpc/trpc-index.ts`:
- Keep distinct `user`, `staffUser`, and `superadmin` context fields.
- Add staff `regionId` to the resolved identity.
- Introduce `userProcedure`, `staffProcedure`, and `superadminProcedure` guards.
- Keep public procedures for login and region discovery only where intended.
- Replace generic protected guards on privileged routers with the correct identity guard.
Conceptual staff middleware:
```ts
if (!ctx.staffUser) throw UNAUTHORIZED
return next({ ctx: { ...ctx, staffUser: ctx.staffUser } })
```
A user or superadmin identity does not automatically satisfy this guard. `Caller-Interface` is metadata, not authorization.
### 3.3 Superadmin auth
Implement username/password login backed exclusively by `superadmins`. Use the existing bcrypt library to compare plaintext login input against `password_hash`; issue a superadmin-typed token on success. Return a uniform authentication error on failure and avoid logging login credentials/hash values.
Update existing superadmin UI session handling to this channel. Namespace stored session credentials where needed so staff and superadmin clients cannot accidentally reuse the same identity.
## 4. Superadmin router contracts
Register a new `superadmin` root router in `apps/backend/src/trpc/router.ts`. Proposed procedure layout:
```text
superadmin.auth.login public login
superadmin.auth.me authenticated identity
superadmin.regions.list list regions
superadmin.regions.get region + bounds
superadmin.regions.create create region
superadmin.regions.update update name/description
superadmin.regions.createBound create validated bound
superadmin.regions.updateBound update geometry/description/priority
superadmin.staff.create create staff with required region
superadmin.staff.list administrative staff listing
superadmin.staff.update authorized staff/region management
```
These are proposed names; preserve established API naming conventions where appropriate. There is no region-delete procedure. Bound deletion is not required by the confirmed requirements; do not introduce it without deciding effective-settings safety.
Validate region existence, GeoJSON structure, and priority uniqueness. Map uniqueness violations to useful API errors. For priority swaps, use a safe atomic strategy compatible with D1 rather than assuming a multi-step update has transactional rollback.
Staff creation leaves the admin API and becomes superadmin-only. Keep roles/credentials consistent with existing staff login behavior.
## 5. Region-scoped persistence helpers
### 5.1 Explicit scope parameters
Change regional helper signatures so callers cannot omit trusted scope accidentally:
```ts
getAllOrders(regionId: number, input: GetAllOrdersInput)
getOrderDetails(regionId: number, orderId: number)
getProducts(regionId: number, input: ProductListInput)
updateProduct(regionId: number, productId: number, input: ProductUpdateInput)
```
Preserve actual helper names and result types. Admin router calls pass `ctx.staffUser.regionId`; do not accept an override from request input.
### 5.2 Scoped reads and writes
For root records, combine scope with existing predicates:
```ts
where: and(eq(orders.regionId, regionId), existingPredicate)
```
For updates/deletes, put region ownership in the mutation predicate, not merely in an earlier UI lookup. Return a consistent inaccessible/not-found response when no matching row is found.
For dependent records such as order items or SKU market stats, resolve or constrain ownership via joins/EXISTS against their root record. Do not mutate by dependent ID alone.
Every create/update connecting entities validates matching regions, including optional product stores, combos, slots, snippet membership, tags/groups, coupons, and order lines. Validate bulk operations too.
### 5.3 User visibility to staff
Build regional user listings using an EXISTS condition on orders:
```sql
EXISTS (
SELECT 1 FROM orders
WHERE orders.user_id = users.id
AND orders.region_id = :staff_region_id
)
```
Scope user-order details, item counts, last-order lookups, totals, and related complaints to the same region. An address in the region does not qualify a user without an order.
Account-global actions require an explicit authority decision; do not silently give regional staff cross-region suspension/deletion effects.
### 5.4 Existing D1 transaction caveat
`packages/db_helper_sqlite/src/db/db_index.ts` currently supplies a transaction-shaped wrapper that executes the callback without a real database transaction. Do not assume rollback protection when designing region switching, multi-record checkout validation, migration steps, or priority swaps. Use supported D1 atomic batching/constraints or another deliberate consistency strategy after auditing the existing helpers.
## 6. Effective bound settings
Introduce a helper such as:
```ts
getEffectiveRegionSettings(regionId: number): Promise<EffectiveRegionSettings>
```
Algorithm:
1. Validate region existence.
2. Fetch that region's bound ordered by priority ascending, limit 1.
3. Fetch the chosen bound's configured settings.
4. Fail clearly if either is missing.
Do not filter bounds by coordinates. Do not select another bound just because the lowest-priority bound is missing configuration. Do not borrow another region's values.
Use this helper as the authoritative source in checkout and payment calculations. Frontend estimates consume corresponding settings, but backend calculations remain authoritative.
Add staff-only read/update settings procedures. Identify bounds through a query constrained to `ctx.staffUser.regionId`. Editing another bound is allowed within the region; only the current lowest-priority bound affects calculations.
## 7. User API changes
### 7.1 Discovery and browsing
Expose a public region list returning safe summaries. Regional catalog/slot/store/banner/availability requests require `regionId` and validate it before reading data.
Common scaffold functions become explicit regional functions, for example:
```ts
scaffoldProducts(regionId: number)
scaffoldAvailability(regionId: number)
scaffoldSlotsWithProducts(regionId: number)
scaffoldStores(regionId: number)
scaffoldBanners(regionId: number)
```
Apply scope inside the DB readers as well as the router; background generation calls must not accidentally retrieve global records.
### 7.2 Addresses
Create/update inputs include a required region ID. Validate region existence and user ownership on editing. Coordinate containment is explicitly not required. Updating address region must be an explicit user action, not a hidden consequence of changing browsing region.
### 7.3 Checkout
Request includes the intended region along with selected items, address, slot choices, and coupon. Backend verifies:
- Authenticated user owns the address.
- Address region equals checkout region.
- Every SKU and slot belongs to checkout region.
- Requested slot availability and SKU membership are valid.
- Coupon eligibility and ownership match the region.
- Current prices and effective bound settings produce the authoritative total.
Reject mixed-region requests before creating orders/payments. Persist `orders.region_id`. Preserve existing order-item price snapshots rather than relying on future catalog prices for order history.
### 7.4 History
`getOrders` remains filtered by user ownership, not browsing region. `getOrderById` verifies user ownership and returns the order's region label. Do not require the currently browsed region to match a historical order.
## 8. Regional cache implementation
### 8.1 Path builders
Centralize region prefixes in `apps/backend/src/lib/cloud_cache.ts`:
```ts
const regionPrefix = (regionId: number) => `regions/${regionId}`
const catalogPath = (regionId: number, version: number, filename: string) =>
`${regionPrefix(regionId)}/v-${version}/${filename}`
```
Add equivalent availability/slot builders using existing filename constants and asset-domain/API-key prefixes. Use these same builders for writes, returned URLs, and cache purges so paths cannot drift.
### 8.2 Generation flow
Split orchestration into a region-specific generator and an all-region generator:
```ts
createRegionCacheFiles(regionId: number)
createAllRegionsCacheFiles()
```
The all-region function lists regions and invokes region generation with controlled concurrency. Region generation reads only its region, updates that region's versions, writes files, purges regional URLs, and refreshes the region's metadata mirror.
Do not update a successful-version pointer before required files are available. Plan failure recovery so clients do not discover partially published regional snapshots.
### 8.3 Invalidation and jobs
Namespace product/availability/slot version metadata by region. Mutations regenerate the affected region. Scheduled jobs iterate regions or receive explicit regional context. Order queue jobs derive region from the stored order and scope operational recipients accordingly.
Any process cache must be keyed by region. Avoid storing one mutable `currentRegion` in worker globals.
## 9. User UI state transitions
### 9.1 Region store
Add `apps/user-ui/src/store/regionStore.ts` with persisted selected-region ID and a validated loaded region summary. Keep it separate from user identity.
Proposed operations:
```text
initializeRegion() validate saved ID or show selection
requestRegionSwitch(target) open confirmation without modifying state
confirmRegionSwitch(target) perform centralized switch/reset
cancelRegionSwitch() preserve existing state
```
Use existing store/persistence conventions. Do not persist secrets. A missing/unavailable saved region leads to selection, not silent checkout fallback.
### 9.2 Confirmed-switch sequence
Centralize the reset so manual switching and address-triggered switching use the same behavior:
1. Block new checkout submissions and cancel/ignore stale regional fetch responses.
2. Clear normal cart, flash cart, quick-delivery state, selected slots, coupons, and checkout totals/selections.
3. Clear/update server-backed cart state if the existing cart implementation persists it remotely.
4. Update and persist selected region.
5. Reset or namespace regional product/slot/config stores and queries.
6. Fetch regional metadata and files.
7. For an address-triggered switch, navigate home rather than resume the old checkout.
Handle remote-clear failure explicitly instead of claiming the cart is cleared while stale server items remain. The final mechanism depends on the existing cart persistence audit.
### 9.3 Race protection
Use a region generation/version marker or query cancellation so an old-region response cannot overwrite new-region stores. Checkout captures the intended region and cart snapshot; region changes invalidate that attempt before any new submit.
If an already accepted backend order completes during switching, preserve access to it through all-region history rather than trying to undo it with client-side resets.
### 9.4 Address and history components
- `AddressForm.tsx`: load region choices; default only new addresses to browsing region.
- `CheckoutAddressSelector.tsx` and `QuickDeliveryAddressSelector.tsx`: stage selection; confirm cross-region changes before committing state.
- `checkout-page.tsx` and `PaymentAndOrderComponent.tsx`: use effective settings and explicit region; handle backend mismatch errors safely.
- Order list/details and `NextOrderGlimpse.tsx`: render region labels; remain account-wide.
Use common-ui primitives according to repository rules.
## 10. Admin and superadmin UI code
### 10.1 Superadmin
Update auth context, tRPC client, and login route to separate superadmin credentials. Add regions and staff routes using the proposed router contracts.
Region forms submit name/description; bound forms submit parsed GeoJSON, description, and numeric priority. Validate inputs client-side for feedback and again server-side for correctness. Show duplicate-priority errors and effective-bound status. Do not display a region-delete action.
Staff forms require region selection. Existing constants/notification screens must be audited and routed through explicit superadmin authority if retained. Regenerate the TanStack route tree through its normal tooling rather than manually editing generated output.
### 10.2 Admin
Extend `staff-auth-context.tsx` to expose region identity. Display it in the shell; do not let staff arbitrarily change it. Remove staff-create operations from admin screens.
Modify the existing `apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx` Customize App Constants screen rather than adding a new settings route:
- Fetch bounds belonging to the authenticated staff region and display one tab per bound, ordered by ascending priority.
- Label tabs with bound description (or bound ID when description is absent) and priority. Mark the lowest-priority bound as currently effective.
- Select the lowest-priority bound initially. Each tab displays only that bound's customizable constants.
- Change the current unscoped `admin.const.getConstants` / `updateConstants` flow to bound-scoped reads/writes, or use the proposed bound-settings procedures. Read input includes `boundId`; save input includes `boundId` and the changed constants/settings. Backend verifies that the bound belongs to the staff region.
- Keep existing `ConstantInput` controls and visibility rules where compatible with the audited per-bound settings model. Global infrastructure constants must not become editable per-bound values.
- Include `boundId` in query keys and form identity. Initialize the form from that bound's saved values, never from the previous tab's values.
- Save only the active bound's changes. Capture its ID when submitting so changing tabs cannot redirect an in-flight save to another bound.
- Isolate drafts by bound or confirm before discarding unsaved edits when changing tabs; never silently overwrite a draft. Disable conflicting interactions while saving where needed.
- Refetch/invalidate the saved bound and affected region's effective-settings/cache metadata after a successful update.
- Replace the existing claim that all changes take effect immediately: explain that only the lowest-priority bound's values currently affect checkout, regardless of address coordinates. Changes to other bounds are saved but not currently effective.
- Provide loading/error/retry states per selected bound and a clear no-bounds configuration state.
- Preserve existing non-constants customization navigation, subject to regional ownership checks.
There is no new `region-settings` UI route. The existing Customize App entry point remains the location for bound-specific constants.
Update existing screen contracts and inaccessible-record behavior. No UI region filter substitutes for backend scoping. Scope cache regeneration controls to the assigned region.
## 11. Error semantics
Use existing custom error and tRPC conventions:
- Unauthenticated/wrong identity: authorization error.
- Foreign-region ID: inaccessible/not-found without disclosing sensitive existence.
- Invalid/mixed region or malformed GeoJSON: validation error.
- Duplicate priority: conflict/validation error with a clear message.
- Missing effective bound/settings: explicit configuration error.
- Stale checkout state: clear retry/reselection guidance, with no partial order creation where avoidable.
Do not introduce broad catch blocks that hide failures. Ensure logging avoids credentials and password hashes.
## 12. Implementation order and validation
Implement in dependency order:
1. Shared schema/contracts and prepared migration.
2. Identity guards and superadmin APIs.
3. Scoped persistence helpers and all API entry points.
4. Effective settings and regional cache generation.
5. Superadmin/admin UI contracts.
6. User startup, switch/reset, address, checkout, and history flows.
7. Static review/typechecking and prepared test cases.
Validate foreign-region ID access, mixed-region relationships, regional user aggregates, generated file contents, duplicate priority, startup state, switch cancellation/confirmation, stale response races, and all-region order history.
Before any non-Markdown/non-text implementation edit, append its exact diff and current timestamp to the required change log. Do not execute migrations or run tests unless authorized under repository instructions. Do not perform git operations.
## 13. Remaining audit boundaries
The agreed behavior is settled, but implementation must establish the exact existing names and mechanisms for:
- Delivery/flash settings fields and current defaults.
- Server-backed versus local cart storage and reset behavior.
- Existing cache-version storage and URL-discovery consumers.
- Staff management UI route locations and retained superadmin capabilities.
- Account-global moderation permissions.
- D1 atomic operations and priority-reordering safety.
- Legacy REST routes, direct helper consumers, and deployed migration/index state.
Resolve these through source inspection rather than silently introducing new business requirements. Use the file-by-file map in `docs/regions-proposal.md` as the implementation checklist.

View file

@ -1,480 +0,0 @@
# Region Isolation Proposal
Date: 2026-10-07
Status: Proposed; no implementation included
## 1. Purpose
Introduce regions as the ownership boundary for catalogs, regional administration, delivery operations, and generated catalog files. Separate superadmin identities and APIs from staff-admin identities. Allow users to browse different regions while preventing mixed-region carts and checkouts.
This document records the agreed requirements and proposed implementation. It does not authorize running migrations or tests.
## 2. Confirmed decisions
- Every product must belong to a region. A product may still have no store.
- Every staff admin belongs to one region.
- Stores, vendor snippets, tags, product groups, delivery slots, coupons, banners, and delivery zones are region-owned.
- Regional admins can only access and change data belonging to their region.
- Regional admins can see users who have orders in their region. User-related order data shown to them must also be region-filtered.
- Only superadmins create staff accounts and assign their regions.
- Regions cannot be deleted.
- Users select a browsing region at startup and can change it later.
- Region switching requires a confirmation dialog. Confirming clears the entire cart.
- Addresses have an explicitly selected region. The browsing region is the default in the address form.
- Address coordinates do not need to fall within the selected region's bounds.
- Selecting a different-region address during checkout requires confirmation, switches the browsing region, clears the cart, and returns to the home page.
- User order history includes all regions, with region labels.
- Catalog and availability files are generated separately for every region, with the region ID in their URLs.
- Delivery charges, minimum order amounts, and similar business settings belong to individual bounds.
- Regional admins can configure all bounds in their own region.
- For now, use the region's lowest-numbered-priority bound settings regardless of address coordinates. Priority 1 is used when it is the lowest priority present; do not hard-code a requirement that priority 1 always exists.
## 3. Database design
### 3.1 `regions`
| Column | Proposed definition |
| --- | --- |
| `id` | Auto-increment integer primary key |
| `name` | Required text |
| `description` | Nullable text |
| `created_at` | Required timestamp with current-time default |
Provide create, list, detail, and update operations. Do not expose a delete operation. Protect against deletion through referenced ownership records as well.
### 3.2 `region_bounds`
| Column | Proposed definition |
| --- | --- |
| `id` | Auto-increment integer primary key |
| `region_id` | Required foreign key to `regions.id` |
| `description` | Nullable text |
| `geojson` | Required JSON text |
| `priority` | Required numeric value |
`region_id` is an addition to the originally listed columns, necessary to support multiple bounds per region.
Constraints and validation:
- Unique constraint on `(region_id, priority)`.
- Lower numeric priority takes precedence.
- Validate that priorities are finite numeric values.
- Store the supplied FeatureCollection structure without discarding feature properties.
- Initially validate polygon FeatureCollections, including coordinates and closed polygon rings. Additional geometry support is not required by the supplied examples.
- Use `ORDER BY priority ASC LIMIT 1` to choose effective business settings, without testing address coordinates.
- A region must have a configured bound before checkout can operate. If none exists, return a clear configuration error rather than borrowing another region's settings.
### 3.3 Bound-level business settings
Propose a `region_bound_settings` table with a required, unique `bound_id` foreign key. This keeps geometry and operational settings separate while providing one settings record per bound.
Map existing delivery and checkout constants to explicit settings fields, including:
- Delivery charges and any existing charge thresholds.
- Minimum order amount.
- Applicable flash-delivery configuration.
- Other region-specific checkout/business constants discovered during the implementation audit.
Preserve current calculation rules and numeric representations unless a change is explicitly required. Inventory existing constants before finalizing column names and defaults; do not invent new pricing rules.
Seed both Mahabubnagar bounds with current business settings so rollout preserves existing behavior. Infrastructure settings, credentials, and deployment configuration remain global.
### 3.4 Regional ownership
Add mandatory `region_id` ownership to the relevant root records:
- `product_info`
- Staff-user records
- Store records
- Vendor snippets
- Product-tag definitions
- Product-group definitions
- Delivery slots
- Coupons
- Banners
- Delivery zones
- Addresses
- Orders
Audit actual schema names before making changes. Addresses and orders need explicit regions in addition to catalog/admin ownership.
Derived ownership:
- `product_skus` inherit region through `product_info`.
- `product_market_stats`, `sku_features`, and SKU-level deals inherit their SKU's region.
- `order_items` inherit region through their order; their SKUs must belong to that same region.
- Tag memberships, group memberships, combo memberships, and snippet mappings must link entities in the same region.
- Reviews remain product-linked; regional admin visibility follows the product's region.
- Users are not assigned one exclusive region; they can browse and order across regions.
Enforce cross-entity consistency in backend writes and use database constraints where feasible. Foreign keys on individual IDs alone do not guarantee matching regions.
Add indexes matching regional filters and relation lookups. Review uniqueness rules individually: do not assume every currently global name becomes region-unique, or that login identifiers can be duplicated.
### 3.5 `superadmins`
Create a separate identity table, not a staff role or a row in `staff_users`.
Proposed minimum fields:
- `id`: primary key.
- `username`: required and unique.
- `password_hash`: required text.
- `created_at`: required timestamp.
The bootstrap account is inserted in the migration immediately after table creation:
- Username: `superadmin`
- Bcrypt password hash: `$2a$12$pDL1ooXdvmdpCFpeXgEnB.7eRot4ygtL/Z9lSmW8ApjRLAhTiuOCu`
The supplied value is already a hash. Store it directly, do not hash it again, and never return it through APIs or write it into application logs. Password login verifies the submitted password against this hash. No public superadmin registration endpoint is proposed.
## 4. Migration and existing data
Prepare migrations for the active SQLite/D1 database. Audit the PostgreSQL helper and keep schema definitions coherent where it remains supported; do not assume it is the active runtime database.
Migration sequence:
1. Create `regions`.
2. Immediately insert a region named **Mahabubnagar**.
3. Create bounds and bound-settings tables.
4. Insert two Mahabubnagar bounds containing the exact GeoJSON from:
- `apps/backend/src/map-assets/Mbnr-1.geojson`: priority **1**.
- `apps/backend/src/map-assets/Mbnr-2.geojson`: priority **2**.
5. Copy current business settings into each bound's settings.
6. Add regional ownership fields and assign all existing regional records, addresses, orders, and staff admins to Mahabubnagar.
7. Enforce required ownership and add relevant constraints/indexes after backfill. Account for SQLite table-rebuild requirements.
8. Create `superadmins` and immediately insert the bootstrap account.
Use the inserted region's actual ID rather than assuming a preexisting ID. Preserve existing records, IDs, foreign-key relationships, and order history. Do not automatically turn staff accounts into superadmins.
The user runs migrations. The agent must not execute them.
For any table recreation, follow `docs/recreate-referenced-tables.md`. Audit the complete recursive foreign-key subgraph and target schema, including legacy tables, views, and triggers. Plan copies parent-first, drops leaf-first, renames parent-first, and index recreation after original tables are dropped. Preserve explicit IDs and all columns; use unqualified CHECK expressions. Do not rely on disabling foreign-key enforcement as a D1 rebuild strategy. Document read-only target preflight and post-migration foreign-key/row-count verification for the user. Any proof-harness execution requires explicit authorization under the repository's test restrictions.
## 5. Backend API and authentication
### 5.1 Three authenticated channels
The existing root tRPC router exposes `user`, `admin`, and `common`. Add `superadmin` while retaining needed common/public discovery endpoints.
- `user`: user identity and ownership checks.
- `admin`: authenticated staff identity with its database-assigned region.
- `superadmin`: authenticated identity from `superadmins`.
Introduce dedicated authorization middleware for each identity. The existing generic protected procedure accepting either users or staff is not sufficient as the only guard for these channels.
Distinguish token identity types explicitly. Reject staff/user tokens on superadmin endpoints and superadmin tokens on staff-only endpoints unless an explicit permission is designed. Do not trust the UI's caller-interface header as an authorization boundary.
### 5.2 Superadmin operations
- Login and current-identity/session operations.
- Region create/list/detail/update, with no delete endpoint.
- Bound create/list/update and priority management.
- Staff-account creation, region assignment, and management required by the existing staff workflows.
- Adapt existing superadmin UI operations to genuine superadmin authorization rather than reusing staff credentials.
Avoid expanding superadmin permissions to unrelated operations without examining current functionality.
### 5.3 Staff-admin isolation
Resolve the staff region from authenticated database state. Do not allow a request's `region_id` to override it.
Apply scope to:
- Lists, searches, counts, details, exports, and aggregates.
- Create/update/delete operations on regional entities.
- Packaging, order status changes, refunds, cancellation actions, and slot reassignment.
- Product, SKU, pricing, tag, group, store, snippet, and availability operations.
- Bound business-setting operations.
- Cache regeneration triggered by regional changes.
ID-based endpoints must check ownership too; hiding another region's records in lists is insufficient. Avoid revealing whether an inaccessible foreign-region record exists.
Regional user visibility is based on the existence of an order in the staff region, not address ownership. Show only that region's user orders and order-derived totals/counts. Audit shared account-level actions so a regional admin cannot unintentionally affect unrelated regions.
### 5.4 User operations
- Provide region discovery before a browsing region has been selected.
- Validate selected region IDs for catalog, availability, slots, banners, stores, and other regional browsing requests.
- Validate address region on address creation and updates; coordinate containment is not required.
- Check checkout region against every item, SKU, slot, address, and applicable coupon.
- Determine business settings from the lowest-priority bound of that region.
- Store region ownership on resulting orders.
- Continue to enforce user ownership for all-region order history and individual order access.
Do not infer checkout region solely from client state. Reject malformed or mixed-region requests at the backend.
## 6. Generated files and background work
Current generation in `apps/backend/src/lib/cloud_cache.ts` uses global scaffolds and versioned product, availability, slot, banner, and store paths. Make scaffolds and generation region-aware.
Proposed path examples, retaining existing versioning semantics:
```text
regions/{regionId}/v-{cacheVersion}/products.json
regions/{regionId}/v-{cacheVersion}/stores.json
regions/{regionId}/v-{cacheVersion}/banners.json
regions/{regionId}/v-{cacheVersion}/stores/{storeId}.json
regions/{regionId}/av-{availabilityVersion}/availability.json
regions/{regionId}/slots/v-{slotsVersion}/slots.json
```
These are illustrative names; preserve actual `CACHE_FILENAMES` and any required URL prefix in implementation.
Requirements:
- Generate each regional file using only that region's records.
- Namespace cache metadata, query caches, version discovery, and KV mirrors by region.
- Prefer per-region version counters so a change in one region does not invalidate every region.
- Make region-scoped business settings available through the appropriate generated/config payloads; do not continue exposing global delivery settings as authoritative.
- Regenerate all regions for full-generation jobs, and only the affected region for targeted updates.
- Update cache purge URLs to the regional paths.
- Audit durable objects, scheduled jobs, queues, and notifications for regional context and avoid global mutable region state shared across concurrent requests.
- Ensure new regions have generated files before browsing relies on them, or return a clear not-ready state.
## 7. Superadmin UI
In `apps/superadmin-ui/`:
- Switch authentication to the new superadmin identity/channel.
- Add region listing, creation, and editing.
- Add bounds management with description, GeoJSON input, and priority validation.
- Explain priority ordering and show which bound currently supplies effective settings.
- Do not offer region deletion.
- Add staff creation and region assignment; remove reliance on staff-admin APIs for this capability.
- Keep password hashes out of UI payloads and displays.
## 8. Admin UI
In `apps/admin-ui/`:
- Include assigned region in staff session/profile data and display it clearly.
- Do not provide a region switcher allowing staff to escape their assignment.
- Scope all data through backend authorization, including existing order, user, product, store, slot, tag, group, snippet, coupon, and banner screens.
- Remove staff-account creation from regional-admin workflows; adapt remaining staff views to the authorized scope.
- Update the existing Customize App Constants screen with one tab per bound in the assigned region. Each tab edits that bound's customizable constants; do not introduce a separate settings screen.
- Clearly indicate that the lowest-priority bound's settings are currently effective, regardless of address coordinates.
## 9. User UI
### 9.1 Region selection
In `apps/user-ui/`, maintain a persisted browsing region independently from the user's account identity.
- On startup, validate any saved selection; prompt before regional browsing when none is selected.
- Offer a region switch control later.
- Show a confirmation dialog before switching, explaining that the entire cart will be removed.
- Cancel leaves region and cart unchanged.
- Confirm clears all cart state, selections, coupon state, and checkout-derived state, updates the region, invalidates regional queries, and loads the new regional files.
- Include region IDs in client query keys and persisted regional data to prevent stale cross-region results.
### 9.2 Addresses and checkout
- Add a required region dropdown to address creation/editing.
- Default new-address region to the browsing region.
- Existing addresses retain their stored region; editing must not silently reassign them to the browsing region.
- Same-region address selection preserves the cart.
- Different-region checkout address selection presents confirmation before changing state.
- On confirmation, switch browsing region, clear the whole cart and checkout state, and navigate home. Do not place the original cart's order under the new address region.
- Prevent stale in-flight checkout actions from completing against a switched cart/region.
### 9.3 Order history
- Show orders from all regions regardless of the browsing region.
- Add region labels to summaries and details.
- Keep order details tied to the order's stored region and user ownership.
- Do not let browsing-region filters hide historical orders.
## 10. Shared contracts and implementation areas
Update shared types and API contracts for region identities, bounds, effective settings, staff region, address region, order region, and regional cache metadata.
Known starting points:
- `packages/db_helper_sqlite/src/db/schema.ts`
- `packages/db_helper_postgres/src/db/schema.ts`
- `packages/shared/`
- `apps/backend/src/app.ts`
- `apps/backend/src/trpc/trpc-index.ts`
- `apps/backend/src/trpc/router.ts`
- `apps/backend/src/trpc/apis/`
- `apps/backend/src/lib/cloud_cache.ts`
- `apps/backend/src/lib/gen-store.ts`
- `apps/backend/src/jobs/`
- `apps/superadmin-ui/src/lib/auth-context.tsx`
- `apps/superadmin-ui/src/routes/`
- Relevant authentication, catalog, cart, address, checkout, and order screens/stores in admin-ui and user-ui.
This is an implementation map, not an exhaustive file inventory. Audit call sites before editing so legacy REST routes, direct helper calls, and background consumers are not missed.
## 11. Proposed rollout stages
1. Audit regional entities, existing auth, settings, cache contracts, and all API entry points.
2. Prepare schema changes, migrations, backfill, bootstrap account, and shared types.
3. Implement separate superadmin authentication and management APIs.
4. Enforce regional backend isolation and consistent relationships across all entry points.
5. Implement regional settings selection, file generation, version discovery, and background jobs.
6. Update superadmin and admin interfaces.
7. Update user region selection, cart switching, address handling, and history labels.
8. Validate and coordinate database/backend/client deployment so old clients cannot bypass region requirements or consume incompatible caches.
Do not expose partially isolated APIs in production. Define a compatibility or coordinated-release strategy during implementation.
## 12. Acceptance checks
Prepare checks covering:
- Existing records all belong to Mahabubnagar after backfill.
- Both supplied bounds are stored exactly, with priorities 1 and 2.
- Duplicate priorities within one region are rejected; the same priority across different regions is allowed.
- Products can omit a store but cannot omit a region.
- Regions cannot be deleted.
- The bootstrap superadmin authenticates through the separate identity table.
- Regional staff cannot create staff accounts or access another region's records by ID.
- Cross-region product/store, slot/SKU, tag/SKU, group/SKU, snippet/SKU, coupon, and checkout relationships are rejected.
- Regional user lists include only users with orders in that region, and aggregates do not leak other-region activity.
- Checkout always uses lowest-priority-bound settings, independent of coordinates.
- Switching cancellation preserves state; confirmation clears the complete cart.
- A different-region checkout address redirects home only after confirmation.
- User history retains orders across all regions and labels them.
- Generated URLs, contents, version metadata, and invalidations remain region-isolated.
- Staff/user tokens cannot access superadmin operations.
Typechecking and static review may be used during implementation. Do not run the test suite unless the user explicitly requests it. Do not run migrations, perform git operations, or implement application changes as part of writing this proposal.
## 13. Items requiring implementation-time audit
These are not changes to the confirmed requirements:
- Exact existing business-setting fields and defaults to move to bounds.
- Existing superadmin UI functions that need corresponding superadmin permissions.
- Account-global actions such as suspension/deletion and how regional staff authority should apply; do not silently grant cross-region effects.
- Whether bound removal/reassignment is needed; region deletion is forbidden, and any bound operation must preserve usable effective settings.
- Existing clients and deployment compatibility during mandatory region rollout.
## 14. File-by-file implementation map
Paths below are relative to the repository root. **New** marks proposed files, not files already created. Directory-level entries intentionally cover every applicable file in that directory; the implementation audit must enumerate their call sites before editing. This map describes responsibilities, not permission to implement them now.
### 14.1 Database and shared contracts
| File / directory | Planned change |
| --- | --- |
| `packages/db_helper_sqlite/src/db/schema.ts` | Define regions, bounds, bound settings, and superadmins; add regional ownership, relations, constraints, and indexes. Keep product store ownership nullable. |
| `packages/db_helper_postgres/src/db/schema.ts` | Mirror the intended ownership model where this helper remains supported, using PostgreSQL-appropriate types and constraints. |
| SQLite migration output directory configured by `packages/db_helper_sqlite/drizzle.config.ts` | **New migration:** create and seed Mahabubnagar, exact GeoJSON bounds, existing bound settings, and bootstrap superadmin; backfill existing regional data and enforce constraints. Prepare only; do not execute. |
| `packages/db_helper_sqlite/index.ts` | Export new regional/superadmin helpers and schema definitions through the package entry point. |
| `packages/db_helper_sqlite/src/admin-apis/*.ts` | Accept trusted staff-region scope; constrain lists, ID lookups, writes, aggregates, and related records. Restrict user visibility by regional orders. |
| `packages/db_helper_sqlite/src/user-apis/*.ts` | Scope catalog and checkout helpers; save address/order regions; preserve all-region user history while enforcing user ownership. |
| `packages/db_helper_sqlite/src/helper_methods/upload-url.ts` | Audit upload authorization where an upload is tied to regional records; prevent ID-based authorization gaps. |
| `packages/db_helper_sqlite/src/lib/*.ts` | Audit cache data readers, seed helpers, automated jobs, and order deletion for explicit regional scope. |
| `packages/db_helper_sqlite/src/superadmin-apis/regions.ts` — **New** | Region and bound persistence, priority validation, and effective-bound selection. |
| `packages/db_helper_sqlite/src/superadmin-apis/auth.ts` — **New** | Superadmin lookup and password verification support; never expose hashes. |
| `packages/db_helper_sqlite/src/superadmin-apis/staff.ts` — **New** | Create/manage staff accounts and validate assigned region. |
| `packages/shared/types/region.types.ts` — **New** | Region, bound, bound-settings, and effective-settings DTOs and inputs. |
| `packages/shared/types/superadmin.types.ts` — **New** | Public superadmin identity and management contracts without password hashes. |
| `packages/shared/types/staff-user.types.ts`, `admin.ts`, `inputs.types.ts` | Staff region and scoped administration contracts; separate staff creation from regional admin operations. |
| `packages/shared/types/user.ts`, `order.types.ts` | Address region and order region labels; retain all-region history response support. |
| `packages/shared/types/cache.types.ts`, `const.types.ts`, `app-common.types.ts` | Regional cache discovery/version contracts and effective bound business settings. |
| `packages/shared/types/index.ts`, `packages/shared/index.ts` | Export new and updated shared contracts. |
### 14.2 Backend authentication and API channels
| File / directory | Planned change |
| --- | --- |
| `apps/backend/src/app.ts` | Resolve distinct user/staff/superadmin identities; include trusted staff region in context; audit legacy route mounting and token validation. |
| `apps/backend/src/trpc/trpc-index.ts` | Define identity-specific procedures and trusted regional context; do not authorize all channels through the current generic user-or-staff guard. |
| `apps/backend/src/trpc/router.ts` | Register `superadmin` alongside existing channels; update inferred regional payload contracts. |
| `apps/backend/src/trpc/apis/superadmin-apis/superadmin-trpc-index.ts` — **New** | Aggregate superadmin auth, region/bounds, and staff-management routers. |
| `apps/backend/src/trpc/apis/superadmin-apis/auth.ts` — **New** | Separate superadmin login/session APIs and explicitly typed tokens. |
| `apps/backend/src/trpc/apis/superadmin-apis/regions.ts` — **New** | Region create/list/detail/update and bound management; no region deletion. |
| `apps/backend/src/trpc/apis/superadmin-apis/staff.ts` — **New** | Superadmin-only staff account creation and region assignment. |
| `apps/backend/src/trpc/apis/admin-apis/apis/admin-trpc-index.ts` | Register bound-settings APIs and ensure all child routers use staff-only authorization. |
| `apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts` | Remove regional staff-account creation authority; scope remaining staff visibility and authentication appropriately. |
| `apps/backend/src/trpc/apis/admin-apis/apis/product.ts`, `store.ts`, `vendor-snippets.ts` | Use trusted region for catalog ownership; validate same-region relationships, including tag/group/snippet mappings. |
| `apps/backend/src/trpc/apis/admin-apis/apis/order.ts`, `slots.ts`, `payments.ts` | Scope orders, slot management, packaging, cancellations, and financial actions to staff region. |
| `apps/backend/src/trpc/apis/admin-apis/apis/user.ts`, `complaint.ts` | Filter user access through regional orders and prevent cross-region history/aggregate disclosure; audit account-global actions. |
| `apps/backend/src/trpc/apis/admin-apis/apis/banner.ts`, `coupon.ts`, `const.ts` | Scope banners/coupons; move delivery business settings out of global constants while retaining genuinely global configuration. |
| `apps/backend/src/trpc/apis/admin-apis/apis/region-settings.ts` — **New** | Read/edit all bound settings in the authenticated staff region; return the effective lowest-priority bound. |
| `apps/backend/src/trpc/apis/user-apis/apis/address.ts` | Require and validate address region; do not require coordinate containment. |
| `apps/backend/src/trpc/apis/user-apis/apis/order.ts`, `payments.ts`, `cart.ts`, `coupon.ts` | Validate a consistent checkout region, apply lowest-priority-bound settings, and reject stale/mixed-region checkout requests. |
| `apps/backend/src/trpc/apis/user-apis/apis/product.ts`, `slots.ts`, `stores.ts`, `banners.ts` | Require validated browsing region for regional data and scaffold operations. |
| `apps/backend/src/trpc/apis/common-apis/common.ts`, `common-trpc-index.ts` | Regionalize catalog/config scaffolds and add public region discovery. |
| `apps/backend/src/dbService.ts`, `sqliteImporter.ts` | Re-export regional and superadmin persistence helpers without changing the active DB selection. |
| `apps/backend/src/main-router.ts`, `v1-router.ts`, `apis/` | Audit legacy REST entry points and enforce equivalent identity/region checks; do not leave unscoped bypasses. |
### 14.3 Generated files and background processing
| File / directory | Planned change |
| --- | --- |
| `apps/backend/src/lib/cloud_cache.ts` | Add region IDs to scaffold calls, object paths, metadata, and purge URLs; support all-region and targeted regeneration. |
| `apps/backend/src/lib/gen-store.ts` | Namespace generated version metadata/KV mirrors by region and publish region-aware discovery. |
| `apps/backend/src/stores/` | Audit in-memory data caches; key regional state by region rather than keeping one global regional snapshot. |
| `apps/backend/src/jobs/cache-creator.ts` | Schedule/coordinate regeneration per region and include regional settings data. |
| `apps/backend/src/jobs/`, `apps/backend/src/lib/flash-delivery-cron.ts` | Make delivery/availability jobs iterate or explicitly target regions; use effective bound settings. |
| `apps/backend/src/lib/queue-data-pusher.ts`, `queue-consumer.ts`, `post-order-handler.ts`, `notif-job.ts` | Carry or resolve region from the order; avoid cross-region operational reads/recipients. |
| `apps/backend/src/lib/worker-init.ts`, `apps/backend/worker.ts` | Audit worker/durable-object initialization and job entry points; never use one mutable global browsing region. |
| `apps/backend/src/map-assets/Mbnr-1.geojson`, `Mbnr-2.geojson` | Use exact contents as migration seed inputs. No geometry edits planned. |
| `apps/backend/src/lib/mbnr-geojson.ts`, `apps/backend/src/map-assets/mbnr-1.ts` | Audit hard-coded geography consumers; replace assumptions where they should use persisted regional bounds. |
### 14.4 Superadmin UI
| File / directory | Planned change |
| --- | --- |
| `apps/superadmin-ui/src/lib/auth-context.tsx` | Authenticate and persist the separate superadmin identity/session rather than a staff identity. |
| `apps/superadmin-ui/src/lib/trpc-client.ts` | Send superadmin session credentials and consume new channel contracts. |
| `apps/superadmin-ui/src/routes/login.tsx` | Use superadmin username/password login. |
| `apps/superadmin-ui/src/routes/__root.tsx`, `dashboard.tsx` | Add region/staff navigation and authenticated superadmin layout integration. |
| `apps/superadmin-ui/src/routes/regions.tsx` — **New** | Region list/create/edit and bounds management, including GeoJSON and unique priority validation. |
| `apps/superadmin-ui/src/routes/staff.tsx` — **New** | Staff account creation/management with required region assignment. |
| `apps/superadmin-ui/src/routes/constants.tsx`, `send-notifications.tsx` | Audit existing privileged operations and move them to appropriately authorized superadmin endpoints where retained. |
| `apps/superadmin-ui/src/routeTree.gen.ts` | Regenerate using the app's routing workflow after adding routes; do not hand-maintain generated output. |
### 14.5 Admin UI
| File / directory | Planned change |
| --- | --- |
| `apps/admin-ui/components/context/staff-auth-context.tsx` | Include assigned region in the authenticated staff profile/session. |
| `apps/admin-ui/src/trpc-client.ts` | Consume updated identity/contracts; invalidate stale session-scoped data when necessary. |
| `apps/admin-ui/app/(drawer)/` layouts and dashboard navigation | Display assigned region; retain existing Customize App navigation and remove staff-account creation access. |
| `apps/admin-ui/app/(drawer)/dashboard/manage-orders/orders/index.tsx` | Consume region-scoped order data and retain item packaging behavior. |
| `apps/admin-ui/app/(drawer)/dashboard/manage-orders/order-details/[id].tsx` | Handle scoped order lookups/actions and inaccessible records. |
| `apps/admin-ui/app/(drawer)/dashboard/manage-orders/delivery-sequences/index.tsx` | Use only assigned-region slots/orders/staff. |
| `apps/admin-ui/app/(drawer)/dashboard/user-management/[id].tsx` | Display only regional user-order history and aggregates. |
| `apps/admin-ui/app/(drawer)/dashboard/vendor-snippets/index.tsx` | Consume scoped snippets and same-region SKU/order selections. |
| Other catalog, stores, tags, groups, coupons, banners, user lists, complaints, and staff dashboard files | Update changed contracts/selectors; rely on backend isolation rather than passing arbitrary region overrides. Audit actual screen files before edits. |
| `apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx` | Replace the single global constants form with bound tabs, sorted by ascending priority. Fetch/save constants for the selected bound, retain reusable input controls, and identify the effective lowest-priority bound. Isolate drafts by bound and confirm before discarding unsaved edits. |
### 14.6 User UI
| File / directory | Planned change |
| --- | --- |
| `apps/user-ui/src/store/regionStore.ts` — **New** | Persist browsing region and coordinate confirmed switching, complete cart reset, and regional state invalidation. |
| `apps/user-ui/src/components/RegionSelector.tsx` — **New** | Startup selection and later region-switch UI with confirmation/cancel behavior. |
| `apps/user-ui/app/_layout.tsx` | Integrate saved-region validation and startup gating without blocking public region discovery. |
| `apps/user-ui/src/contexts/AuthContext.tsx` | Keep browsing-region selection separate from user identity; coordinate session/state resets where required. |
| `apps/user-ui/src/trpc-client.ts`, `utils/queryClient.ts` | Update regional request contracts and query-cache handling; include region in relevant query keys. |
| `apps/user-ui/src/store/centralProductStore.ts`, `centralSlotStore.ts`, `appStore.ts` | Fetch regional generated URLs/configuration and clear or namespace cached regional snapshots. |
| `apps/user-ui/src/store/cartStore.ts`, `flashCartStore.ts`, `quickDeliveryStore.ts` | Reset all normal/flash/quick-delivery cart and derived checkout state on confirmed switching. |
| `apps/user-ui/hooks/cart-query-hooks.tsx` | Prevent stale cart queries/mutations from repopulating the previous region after a switch. |
| `apps/user-ui/src/store/addressStore.ts` | Carry address region metadata and preserve explicitly selected address ownership. |
| `apps/user-ui/src/components/AddressForm.tsx` | Required region dropdown; browsing-region default for new addresses only. |
| `apps/user-ui/components/CheckoutAddressSelector.tsx`, `QuickDeliveryAddressSelector.tsx` | Confirm different-region address selection; switch, clear state, and navigate home only after confirmation. |
| `apps/user-ui/components/checkout-page.tsx`, `PaymentAndOrderComponent.tsx` | Consume effective bound settings, submit consistent regional checkout data, and block stale/in-flight actions after switching. |
| `apps/user-ui/components/SlotSpecificView.tsx`, `ProductCard.tsx`, `ProductDetail.tsx`, `components/stores/` | Consume region-specific catalog/availability/slot data and avoid stale cross-region selections. |
| `apps/user-ui/src/types/orders.ts` | Include order-region identity/labels in the UI view model. |
| `apps/user-ui/app/(drawer)/(tabs)/me/my-orders/index.tsx`, `[id].tsx` | Preserve all-region history and add region labels to orders/details. |
| `apps/user-ui/components/NextOrderGlimpse.tsx` | Preserve account-wide upcoming orders and identify their regions. |
| Region-switch entry points in tab/drawer/home layouts | Add access to the selector and show current browsing region; enumerate actual layouts during implementation. |
### 14.7 Validation and documentation
| File / directory | Planned change |
| --- | --- |
| `apps/backend/tests/` | Add/update fixtures and checks for region isolation, identity separation, backfill assumptions, priority settings, mixed-region checkout, and all-region history. Execute only if explicitly requested. |
| `apps/admin-ui/tests/`, `apps/user-ui/tests/` | Update regional fixtures and add region switching, address selection, history labels, and admin access UI checks. Execute only if explicitly requested. |
| `docs/regions-proposal.md` | Keep agreed design and implementation map current if requirements change. |
| `change-log.txt` | Before each non-Markdown/non-text edit, record the exact planned diff with a current timestamp per repository instructions. |
Build outputs such as `dist/`, dependency folders, and local worker database state are not manual-edit targets. Migration execution remains the user's responsibility.

View file

@ -1,210 +0,0 @@
# Test Plan — Region consts model + active bound + login walls
Verification plan for the consts three-table model, the active-bound model, and the
user-app flows built in this session. Uses **Maestro MCP**.
## Environments
| Env | Where | Id / URL |
|---|---|---|
| Backend | `wrangler dev` (local) | http://localhost:8787 (tunnel `devbackend.freshyo.in`) |
| Superadmin UI | Chromium (Maestro web) | http://localhost:4175 |
| User app (customer) | iOS simulator — `iphone 16 pr max - iOS 18.6` (`B1F98A94-9733-46A6-9EB2-76F33C15240D`) | appId `com.freshyotrial.app` |
## Fixtures
| Thing | Value |
|---|---|
| Region 1 | Mahabubnagar, bounds `Mbnr-1` (priority 1), `Mbnr-2` (priority 2) |
| Region 2 / 3 | Test regions as configured in dev (e.g. `Testnagar`, `Test-1`) |
| Staff (admin-ui, out of scope) | `uitest` / `uitest2`, password `test1234` |
| Superadmin | username `superadmin`, password **BLOCKER — unknown** |
## Blockers / prerequisites
| Id | Item | Status |
|---|---|---|
| P-1 | Superadmin password needed for every superadmin-UI case | blocker (must ask) |
| P-2 | Customer login = SMS OTP to a real phone — needs the physical device to read the OTP, or an already-logged-in test user on the simulator | blocker / workaround |
| P-3 | Metro dev server (`npx expo start`) must be running for the dev app; port 8081 was down | prereq |
| P-4 | User app must be installed on the simulator | to verify |
| P-5 | Migration `0007_addresses_bound_id` applied to the dev DB | user runs it |
---
## A. Superadmin UI (Chromium @ :4175)
### SU-1 Login with superadmin credentials
- Steps: open `/login` → username `superadmin` + password → submit.
- Expected: lands on the dashboard; no UNAUTHORIZED errors anywhere.
### SU-2 Regions page — region constants editor
- Steps: Regions → pick a region.
- Expected: **Region settings** editor shows the region keys (`Popular Items`, `All Items Order`,
`Tags Order`, `Enable Flash Delivery`, `Support Mobile`, `Support Email`, `Welcome Message`)
with the 3 version counters **hidden**.
### SU-3 Regions page — bound constants editor + effective badge
- Steps: select each bound tab.
- Expected: **Bound settings** editor shows ONLY the 5 bound keys
(`minRegularOrderValue`, `freeDeliveryThreshold`, `deliveryCharge`,
`flashFreeDeliveryThreshold`, `flashDeliveryCharge`); the lowest-priority bound shows the
**EFFECTIVE** badge.
### SU-4 Update bound settings → KV refreshed
- Steps: change `deliveryCharge` on a bound → Save.
- Expected: success; KV key `essentialConsts_{boundId}` reflects the new value
(`npx wrangler kv:key get "essentialConsts_1" --namespace-id <gen-ns>`).
### SU-5 Constants page — Global + Legacy (superadmin token)
- Steps: Constants → check Global section shows the 4 global keys and Legacy shows the 7 leftover
keys → change one global and one legacy value → Save each.
- Expected: saves succeed with a superadmin token (this was previously UNAUTHORIZED via
`admin.const.*`); entries persist after reload.
### SU-6 Update region constants (superadmin) → KV refreshed
- Steps: Regions → region editor → toggle `isFlashDeliveryEnabled` → Save region settings.
- Expected: success; `essentialConsts_{boundId}` for that region reflects it.
---
## B. User app (iOS simulator)
### U-1 Startup resolve — location granted
- Setup: app state cleared, location permission allowed, device fix inside bound **Mbnr-1**.
- Expected: spinner **"Finding your region..."** → app renders; location bar shows `Mahabubnagar`;
a (now commented-out) `<user-ui> essentialConsts boundId` log would have printed the containing bound.
### U-2 Startup resolve — location denied
- Setup: app state cleared, location permission **denied**.
- Expected: full-screen **region chooser** (`RegionSelector` gate) — pick `Mahabubnagar` → app renders.
### U-3 Active bound = least-priority bound of the user's addresses
- Setup: signed in, user has an address in region 1 with `bound_id` = the least-priority bound.
- Expected: consts (delivery charge / threshold) come from that address's bound — **not** the
device-location bound.
### U-3b No address in the region → effective bound
- Setup: signed in, user has **no** address in region 1.
- Expected: active bound = region's effective (least-priority) bound.
### U-4 Region switch clears the cart
- Steps: add items to cart → location bar → choose another region → confirm.
- Expected: confirmation dialog; on confirm the cart is emptied (both types) and the app shows the new region.
### U-5 Same-region bound change does NOT clear the cart
- Setup: cart with items; user in region 1.
- Expected: changing only the bound (where supported) keeps the cart.
### U-6 Cart login wall
- Setup: sign out.
- Steps: open the cart (regular and 1-hr variants).
- Expected: inline **"Please log in"** wall, no cart content; **Back** navigates out; **Log In** → login screen.
### U-7 Post-login returns to the gated page
- Steps: from the cart wall → Log In → sign in.
- Expected: lands back on the **cart** page (not home). Same for the **Me** tab wall → lands on Me.
### U-8 Cart items behaviour
- Expected: quantity stepper works; 0 shows a remove confirmation; per item, out-of-stock / no-slot /
not-flash-eligible warnings render; delete button removes the item.
### U-9 Delivery slot picking (regular, cart)
- Expected: slot dropdown lists slots; the **Delivery Slot Summary** sits right after items, groups by
slot with counts, and offers a merge suggestion when feasible.
### U-10 Coupons (cart)
- Expected: dropdown lists eligible coupons with savings labels; ineligible disabled; applied coupon
shows under Bill Details and can be removed.
### U-11 Delivery instructions input (cart)
- Expected: **Delivery Instructions** input exists **above** the address selector, above Bill Details;
the typed text is carried into the order (`userNotes`).
### U-12 Address selector position (cart)
- Expected: the selector renders **just above the Bill Details** section.
### U-13 Addresses: data model + first address default
- Steps: from the cart selector → add an address for a user with none → save.
- Expected: it becomes the user's **default** address automatically.
### U-14 "No Location is attached to address" + attach
- Steps: select an address with no coordinates.
- Expected: small text **"No Location is attached to address"** above **+ Attach Current Location**;
granting permission sets `latitude`/`longitude`.
### U-15 Checkout = read-only summary
- Setup: cart with items (regular), at least 2 different slots, a coupon, an address.
- Expected: checkout shows — **Items** grouped by slot with the **slot time pill** above each group,
**Coupon** card, **Address** card, **Bill** — and NO editable controls (no steppers, no slot
dropdowns, no coupon dropdown).
### U-16 Delivery charge vs. displayed bound
- Expected: the delivery charge / free-delivery threshold shown is the **active bound's** value, and
the order is charged the same (client sends `boundId = constsData.boundId`).
### U-17 Back to Cart
- Steps: on checkout tap **Back to Cart**.
- Expected: returns to the cart; nothing lost.
### U-18 Place order (COD)
- Steps: checkout → Place Order.
- Expected: order placed; redirected to order-success; cart cleared.
### U-19 Flash delivery flow
- Steps: flash section → add a flash-eligible item → flash cart → flash checkout → place.
- Expected: no slot summary in the cart; checkout groups items without slot headers; min-order uses
the flash constants (`flashFreeDeliveryThreshold` / `flashDeliveryCharge`).
### U-20 Cross-region checkout address
- Setup: user has an address in a **different** region than the browsing region.
- Steps: select it on the cart.
- Expected: confirmation dialog ("Switch region? ... clears your entire cart") → on confirm the region
switches, carts cleared, and the app lands on home.
### U-21 isFlashDeliveryEnabled gate (region consts)
- Setup: `isFlashDeliveryEnabled = false` for the active bound's region.
- Expected: flash delivery unavailable (403 from the backend; the app marks flash delivery off).
---
## C. Admin apps (admin-ui / admin-web)
Out of scope for this run (the admin mobile app is not installed; `apps/admin-ui` dev server is
stopped). Flagging for a later pass:
- customize-app: Region + Bound tabs only (no Global), region/bound saves reach the right tables,
region-scoped popular/all-items ordering, region-scoped `tagsOrder`, region-scoped `welcomeMessage`.
---
## Reporting
Each case gets: PASS / FAIL / BLOCKED / SKIPPED, with evidence (screenshot, Maestro Viewer link, KV
output, or backend log line).
## Results (2026-10-09)
| Case | Result | Evidence |
|---|---|---|
| SU-1 | ✅ PASS | Logged in as superadmin; Dashboard (Regions / Admin Users / App Constants) rendered |
| SU-2 | ✅ PASS | Region settings editor shows Popular Items / Tags Order / Enable Flash Delivery; "Availability Cache Version" NOT visible (counters hidden) |
| SU-3 | ✅ PASS | Bound settings editor shows only the 5 bound keys (Minimum Regular Order Value, Delivery Charge…); **EFFECTIVE** badge on the lowest-priority bound |
| SU-4 | 🔜 Partial | Verified server-side: `activeBound` returns boundId for region 1; KV UI-edit round-trip not driven from the browser (Maestro web can't target the inputs) |
| SU-5/SU-6 | 🔜 Same as above | Server-side `activeBound` sanity verified; UI drive pending |
| U-1 | ✅ PASS | Fresh install + GPS set to 16.7489,77.9856 (inside Mbnr-1) → Home shows "DELIVER TO Mahabubnagar", no gate needed; region auto-resolved |
| U-6 (Me tab wall) | ✅ PASS | Me tab renders the **Please log in** wall (lock, title, message, Log In) while tabs stay navigable |
| U-7 (login navigation) | ✅ PASS (up to credentials) | Wall → Log In → login screen (mobile step) → "other ways to login" → password step with the username prefilled; all navigation works |
| U-6/U-7 sign-in completion | 🚫 BLOCKED (test harness) | Maestro `inputText` does not land in the **secure** password field on the iOS Simulator (characters dispatched but RN state never updates; the non-secure mobile field typed fine). Simulator hardware-keyboard/secure-field quirk — manual typing on the simulator works; password login via device was NOT automated |
| — | 🔍 **B01** | (pre-B02) Home showed "No products available" + "Shop for ₹+" (threshold undefined) |
| — | ✅ **B02 root-cause + fix** | `common.activeBound` was protected + auth-gated, and the location-resolved bound was not propagated → signed-out users had `boundId = null` → consts disabled. Fixed: `activeBound` is now public (signed-out → effective bound) and `useRegion` propagates the location bound again. Verified: products + "₹300 more for FREE Delivery" on Home |
| U-10/U-11/U-13/U-15/U-18/U-19/U-20 | ⏳ Not run yet | Needs the sign-in round-trip (blocked above) and further flow driving |
### Notable environment findings
- `inspect_screen` / screenshot capture give blank or depth-overflow payloads once the screen has real
content on BOTH devices, so verification relied on `run` + `assertVisible` flows, simulator
screenshots, and point-tap driving.
- Chromium web flows must start with `openLink` (the `url:` header alone doesn't navigate).
- `scrollUntilVisible` is required on the admin Regions page: the region cards live below the fold.
- On the user app, text-node assertions (`assertVisible "Home"` etc.) failed even on clearly-rendered
screens; driving worked via `tapOn: { point: "x%, y%" }` coordinates taken from the screenshots.
- `launchApp` permission auto-grants are not supported for `location` on this Maestro build.

View file

@ -1,182 +0,0 @@
# Cart Management in `apps/user-ui` — Detailed Documentation
> How the customer cart works end-to-end: local storage, React Query hooks, the two cart types (regular + flash), pricing, slots, coupons, checkout handoff, and all edge cases.
---
## 1. Architecture Overview
The cart is **100% client-side / local-first**. There is **no server cart** — items live in local storage (SecureStore on native, localStorage on web via `StorageServiceCasual`), and are resolved against the cached product catalog + slot/availability data on the device.
```
AddToCartDialog / ProductCard / FloatingCartBar
│ useCartStore.setAddedToCartProduct() (trigger dialog)
▼
useAddToCart / useUpdateCartItem / useRemoveFromCart (cart-query-hooks.tsx)
│ mutations write to local storage
▼
StorageServiceCasual (key: "cart_items" | "flash_cart_items")
▲
useGetCart() (query reads local storage + merges product/availability data)
│
cart-page.tsx / floating-cart-bar.tsx / checkout-page.tsx
```
### Key files
| File | Role |
|---|---|
| `hooks/cart-query-hooks.tsx` | The core: local-storage CRUD + React Query hooks (`useGetCart`, `useAddToCart`, `useUpdateCartItem`, `useRemoveFromCart`, `clearLocalCart`). |
| `src/store/cartStore.ts` | Zustand: `addedToCartProduct` — which product opened the AddToCart dialog. |
| `src/store/flashCartStore.ts` | Zustand: `addedFlashProduct` — which product was routed to the flash flow. |
| `src/store/centralProductStore.ts` | Zustand: cached products + `productsById` map (from `useAllProducts`). |
| `src/store/centralSlotStore.ts` | Zustand: slots + `productSlotsMap` (per-product availability/out-of-stock/flash). |
| `components/cart-page.tsx` | The full cart screen (regular + flash via prop). |
| `components/floating-cart-bar.tsx` | Collapsible cart summary bar (count, total, free-delivery progress). |
| `src/components/AddToCartDialog.tsx` | Slot/quantity/flash chooser when adding/updating an item. |
| `components/checkout-page.tsx` | Reads cart via URL params (`slots=`, `coupons=`, `deliveryPrice=`) — the cart is passed by **reference**, not re-read. |
---
## 2. Data Model
### Local storage item (`LocalCartItem`)
```ts
{
id: number, // local incrementing id (max existing id + 1)
skuId: number, // the product/SKU id
quantity: number,
slotId: number, // delivery slot id; 0 = flash/unspecified
addedAt: string, // ISO timestamp
}
```
Stored under `cart_items` (regular) or `flash_cart_items` (flash) via `StorageServiceCasual` (SecureStore native / localStorage web).
### Computed cart (`CartData`)
```ts
{
items: CartItem[],
totalItems: number, // item count (not quantity)
totalAmount: number, // Σ(price × quantity)
}
```
`CartItem` = local item + `subtotal` (computed from `productBasic.price`).
### Product resolution
`useGetCart` builds `items` by looking up each `skuId` in `productsById` (central product store) **and** requiring `productSlotsMap[skuId]` to exist — **if either is missing, the item is silently dropped** from the cart view (not deleted from storage).
---
## 3. Flow: Add to Cart
1. **Trigger**: `ProductCard` / home / store / search call `useCartStore.setAddedToCartProduct({ productId, product })` → the `AddToCartDialog` opens (regular) OR `useFlashCartStore.setAddedFlashProduct` (flash).
2. **Dialog** (`AddToCartDialog.tsx`):
- Lists **available slots** for the product (from `useSlots()` → `productSlotIdsMap`, filtered to future `freezeTime`).
- Shows **"1 hr Delivery"** option if `productSlotsMap[id].isFlashAvailable` AND flash is enabled.
- Quantity via `Quantifier` (step 1 — not the product's `incrementStep`!).
- **Pre-fills** from existing cart item: if the product is already in the cart, it loads the existing quantity + slotId.
- "Add to Cart" / "Update Item" (if already in cart) / "Remove" (if updating).
3. **Mutation** (`useAddToCart` / `useUpdateCartItem`):
- `addToLocalCart`: if `skuId` exists → **merge quantity** (add to existing) + optionally update slotId; else push new item.
- Requires `slotId` (throws if null).
- `updateLocalCartItem`: set `quantity` on the item (by local `id`).
- `removeFromLocalCart`: filter out by local `id`.
4. **Flash special-case**: choosing "1 hr Delivery" sets `useFlashCartStore.setAddedFlashProduct(...)` and navigates to the flash products page — it does **NOT** add to the regular cart via the dialog; the flash cart is a separate local list.
---
## 4. Flow: Cart Page
`cart-page.tsx` (`isFlashDelivery` prop selects `cartType`):
- **Loading**: blocks on `useGetCart` loading + (regular only) `getCartSlots` loading.
- **Per-item**:
- Image, name, unit, `Quantifier` (step = product `incrementStep`).
- Quantity to **0** → confirmation alert → remove.
- **Slot selection** (regular only): `BottomDropdown` from `trpc.user.cart.getCartSlots({ productIds })`, filtered to future slots. Flash forces `slotId = 0`.
- Price: regular uses `product.price`; flash uses `product.flashPrice ?? product.price`.
- **Availability** logic per item:
- `productSlotInfo.isOutOfStock` → unavailable "Out of Stock".
- Flash: not flash-eligible → "Not available for flash delivery. Please remove".
- Regular: no slots → "No delivery slots available".
- **Auto-slot effect**: on `slotsData`/`cartItems` change, auto-selects each item's slot (keeps existing if still valid, else first upcoming; flash = 0).
- **Coupons**: `trpc.user.coupon.getEligible` → eligible list; min-order + usage-limit filtering client-side; discount = percent (capped at `maxValue`) or flat (capped at total); applied coupon id passed to checkout via URL.
- **Bill**: Item Total → Product Discount → Coupon Applied → Delivery Fee (0 if `finalTotal >= threshold`) → To Pay. Free-delivery nudge + "You saved ₹X" banner.
- **Checkout handoff**: builds `slots=<slotId>:<itemId,itemId>;...` + `coupons=<id>` + `deliveryPrice=<charge>` URL params → navigates to `/home/checkout` or `/flash-delivery/checkout`.
- **Guard**: if no available items → alert (all OOS / none flash-eligible / missing slots) and blocks checkout.
---
## 5. Flow: Floating Cart Bar
- Reads `useGetCart` for the active cart type; shows count + `totalCartValue` + free-delivery progress (regular vs flash thresholds).
- **Expanded dialog**: list with `MiniQuantifier` (0 = remove), per-item slot dropdown (regular), subtotal, "Go to cart" → cart page.
- **Slot-reassignment effect** (runs once on mount): for regular items whose `slotId` is no longer in `productSlotsMap[skuId].slots`, it **removes + re-adds** the item with the nearest slot (`removeFromCart.mutate` + `addToCartHook.addToCart`). (Note: `addToCart(item.skuId, item.quantity, nearestSlotId)` — passing `quantity` as the *quantity* arg.)
---
## 6. Checkout integration
- Checkout does **not** re-read local storage directly — it receives the cart items **by URL params** (`slots=`, `coupons=`, `deliveryPrice=`) from the cart page.
- This means the checkout's item set/quantities/slots are **frozen at navigation time**; if the cart changes after, checkout uses the snapshot.
---
## 7. Edge Cases & Observations
### Data / storage
1. **Missing product or slot data → item dropped from view** (`useGetCart` returns `null` for items lacking `productBasic` or `productAvailability`). The item stays in storage but is invisible — potential "phantom cart" if product is later removed from catalog.
2. **Duplicate add merges quantity** (same `skuId` → `quantity +=`). No separate line items.
3. **`slotId: 0` sentinel** for flash — 0 is not a real slot; code must treat 0 as "flash/unspecified".
4. **Local `id` generation** = `max(existing ids) + 1`. Deleting the highest-id item then adding reuses ids (fine) — but concurrent adds (two rapid taps) could race since id is computed from the read-then-write sequence (no lock).
5. **Storage failures** (`StorageServiceCasual.setItem` error) are caught by the service and return false — the mutation still resolves, but the write may not have persisted (silent data loss risk).
### Slot / availability
6. **Auto-slot reassignment**: if a cart item's saved slot becomes invalid, the cart page picks the first upcoming slot silently; the floating bar instead does remove+re-add. Two different behaviors for the same situation.
7. **Slot changes in cart page are local-only** (`selectedSlots` state) — they're NOT written back to `LocalCartItem.slotId` until checkout builds the URL. (The `useEffect` reads `cartData` slotId but the dropdown only updates `selectedSlots`.) → **If the user leaves the cart without checking out, the new slot choice is lost.**
8. **`AddToCartDialog` requires a slot** — if a product has no future slots, the dialog can't add it (button disabled). Good, but the flash path can bypass via "1 hr Delivery".
9. **Flash eligibility** is from `productSlotsMap[id].isFlashAvailable` — but the flash cart page also checks `flashEligibleProductIds` (derived from `products` + `productSlotsMap`). Two sources that should agree.
10. **Out-of-stock mid-cart**: if a product becomes OOS after adding, cart page shows "Out of Stock" and excludes it from totals/checkout, but does NOT auto-remove it.
### Quantity / pricing
11. **Dialog step = 1** vs **cart page step = product.incrementStep** — inconsistent stepping between the two add/update UIs. (A product with 500g increment could be set to any integer in the dialog.)
12. **`baseTotalPrice` (coupon eligibility) uses `product.price`** (not flash price) even in flash cart — coupon min-order check may be wrong for flash.
13. **`totalPrice` filters OOS items** — good — but the `Quantifier` still shows them; quantity edits on OOS items are allowed.
14. **Flash pricing**: `flashPrice ?? price` — if `flashPrice` is `0` or `null`, falls back to base price; if `flashPrice` is a valid string, used. (Floating bar + cart page consistent.)
15. **Discount cap for flat coupons**: `Math.min(flatDiscount, maxValue || totalPrice)` — reasonable; percent capped at `maxValue || Infinity`.
### Coupons
16. **Usage-limit coupons are filtered out entirely** from the dropdown (`.filter(coupon => coupon.ineligibilityReason !== "Usage limit exceeded")`) — a used-up coupon disappears rather than showing "used up".
17. **Min-order coupons show disabled** with reason — good.
18. **Selected coupon is only applied to available items' total** — matches backend intent (coupon applies to non-OOS items).
19. **Coupon passed by id to checkout** — checkout re-validates on the backend; client discount is a preview.
### Checkout / navigation
20. **Cart is snapshotted into URL params** — long carts → long URLs; quantities/slots frozen at navigation.
21. **`availableItems.length === 0` guard** produces specific alerts (all OOS / none flash-eligible / missing slots) — good UX.
22. **Partial availability**: if only some items are available, checkout proceeds with only the available ones — the unavailable ones stay in the cart (not removed).
23. **Cart type switcher** navigates between regular/flash flows, but does NOT move items — each cart type is independent.
### Flash-specific
24. **Flash cart items have `slotId: 0`** — the cart page forces `selectedSlots[item.id] = 0` for flash.
25. **Adding via "1 hr Delivery" in the dialog does NOT add to the regular cart** — it sets `addedFlashProduct` and navigates to flash products; the actual add happens on the flash page. (If the user abandons the flash page, nothing was added.)
26. **`isFlashDeliveryEnabled` gate** — flash option only shows if the const is true.
### Concurrency / timing
27. **`useGetCart` enabled only when `productsById` is populated** — before the central product store loads, the cart query is disabled (no stale empty cart flash). Good.
28. **`refetchOnWindowFocus`** default true → returning to the app refreshes cart totals (from local storage) but prices come from cached products — price updates in the catalog reflect on next product refetch.
29. **Floating bar slot-reassignment runs once (`[]` deps)** — on mount only; slot validity isn't re-checked on later slot-data changes.
30. **Remove-then-add in floating bar** for invalid slots changes the local item `id` (new id) — any UI holding the old id could mismatch.
---
## 8. Potential improvements (suggestions, not required)
- **Persist slot changes**: write `selectedSlots` back to `LocalCartItem.slotId` so slot choices survive leaving the cart.
- **Unify quantity step** (dialog step=1 vs cart incrementStep).
- **Fix flash coupon min-order** to use flash price.
- **Handle "phantom items"**: purge local cart entries whose product no longer exists (or show them as unavailable).
- **Serialize add-to-cart writes** (mutex/queue) to avoid id races on rapid taps.
- **Surface storage write failures** instead of silently succeeding.
---
*Documentation based on code reading of `cart-query-hooks.tsx`, `cartStore.ts`, `flashCartStore.ts`, `centralProductStore.ts`, `centralSlotStore.ts`, `cart-page.tsx`, `floating-cart-bar.tsx`, `AddToCartDialog.tsx`, and `checkout-page.tsx`.*