freshyo/change-log.txt
2026-10-07 13:36:48 +05:30

767 lines
45 KiB
Text

[2026-10-07 13:00:00] BACKEND per-region storefront cache generation (fixed contract; UI clients done by a second agent).
Planned diffs (backend + db_helper only; NO UI app touched; NO migration run; NO tests):
packages/shared/types/region.types.ts
- Add RegionCacheVersions { regionId, cacheVersion, availabilityVersionNum, slotsVersionNum }.
packages/db_helper_sqlite/src/db/schema.ts
- New table regionCacheVersions (region_id NOT NULL UNIQUE FK->regions.id,
cache_version / availability_version_num / slots_version_num NOT NULL DEFAULT 1).
packages/db_helper_sqlite/drizzle/0008_region_cache_versions.sql (new, NOT run)
- CREATE TABLE IF NOT EXISTS + UNIQUE index + INSERT seed row per existing region.
packages/db_helper_sqlite/drizzle/meta/_journal.json
- Append journal entry idx 8 -> 0008_region_cache_versions.
packages/db_helper_sqlite/src/lib/region-cache-versions.ts (new)
- getRegionCacheVersions(regionId) (auto-creates row when missing),
incrementRegionCacheVersion / incrementRegionAvailabilityVersionNum /
incrementRegionSlotsVersionNum. Global key_val_store counters untouched.
packages/db_helper_sqlite/index.ts — export the four helpers.
packages/db_helper_sqlite/src/stores/store-helpers.ts
- regionId FIRST param on getAllProductsForCache, getAvailabilityForCache,
getAllStoresForCache, getAllDeliverySlotsForCache, getAllSpecialDealsForCache,
getAllProductTagsForCache, getAllTagsForCache, getAllTagProductMappings,
getAllSlotsWithProductsForCache, getAllBannersForCache
(+ getAllProductCombosForCache, same treatment — needed so combo rows stay
in-region; not in the contract list, reported).
- SQL where region_id on region-owned tables; JS-filter SKU-linked rows via the
parent product_info.region_id; banner skuIds / slot skuIds / tag relatedStores
filtered to in-region ids.
packages/db_helper_sqlite/src/user-apis/stores.ts
- getStoreSummaries(regionId, ...), getStoreDetail(regionId, storeId) (null
outside region), getStoresSummary(regionId).
packages/db_helper_sqlite/src/user-apis/banners.ts — getActiveBanners(regionId).
packages/db_helper_sqlite/src/user-apis/slots.ts
- getActiveSlotsList(regionId), getProductAvailability(regionId, in-region SKUs).
packages/db_helper_sqlite/src/user-apis/product.ts
- getSuspendedSkuIds(regionId); new getSkuRegionId/getSkuRegionIds (server-side
SKU->region resolution for region-less live user endpoints; no client trust).
apps/backend/src/sqliteImporter.ts — re-export new/changed helpers.
apps/backend/src/trpc/apis/common-apis/common.ts
- scaffoldProducts(regionId): reads scoped DB helper directly (NOT the
in-memory product-store); nextDeliveryDate = latest in-region slot per SKU
(matches old DESC semantics); tags/mappings scoped; images signed.
- scaffoldAvailability(regionId). getAllProductsSummary keeps no-input shape
for admin UIs (untouched apps) by aggregating per-region scaffolds (reported).
apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
- scaffoldEssentialConsts(regionId): global consts + region's three versions +
assetsDomain/apiCacheKey + regionId + regionSettings via
getEffectiveRegionSettings. essentialConsts now REQUIRES {regionId} input
(UI callers cannot be updated here — reported for the client agent).
- getStoresSummary endpoint keeps no-input shape via per-region aggregation
(reported).
apps/backend/src/trpc/apis/user-apis/apis/stores.ts
- scaffoldStores(regionId), scaffoldStoreWithProducts(regionId, storeId)
(404/NOT_FOUND outside region).
apps/backend/src/trpc/apis/user-apis/apis/slots.ts
- scaffoldSlotsWithProducts(regionId) via scoped DB helper directly
(slot-store NOT keyed by region); getSlots endpoint aggregates per region.
apps/backend/src/trpc/apis/user-apis/apis/banners.ts — scaffoldBanners(regionId).
apps/backend/src/trpc/apis/user-apis/apis/product.ts + cart.ts (live, region-less)
- Resolve region server-side per requested SKU ids, then call region-keyed
in-memory stores (no client-region trust).
apps/backend/src/stores/product-store.ts + slot-store.ts
- regionId FIRST param on initialize*/getAll*/get*/getMultipleProductsSlots.
apps/backend/src/stores/product-tag-store.ts + banner-store.ts
- initialize*(regionId).
apps/backend/src/lib/gen-store.ts
- KV key `essential_consts:{regionId}`; refreshGenKv(regionId?) (no-arg =
all regions, kept for seed/flash/const callers); readEssentialConstsFromKv
requires regionId (throws when missing — no silent global fallback).
apps/backend/src/lib/cloud_cache.ts
- createRegionCacheFiles(regionId) writing ONLY per-region paths
({key}/regions/{id}/v-{cv}/products|stores|banners|essential-consts.json +
stores/{storeId}.json, regions/{id}/av-{av}/availability.json,
regions/{id}/slots/v-{sv}/slots.json); per-region purge + KV mirror.
- createAllCacheFiles(regionId?) iterates all regions (or one); GLOBAL file
generation REMOVED (all known consumers are the UI cache hooks being migrated
by the client agent; backend tests also read them — reported, not updated).
- createSlotsCacheFile(regionId, refresh) / createAvailabilityCacheFile(regionId,
refresh) — admin slots/product routers pass ctx.staffUser region.
apps/backend/src/stores/store-initializer.ts
- initializeAllStores(regionId?) resolves target regions (one or all) and
inits each; scheduleStoreInitialization(regionId?) forwards region to the DO.
apps/backend/src/jobs/cache-creator.ts (CacheCreator DO)
- schedule(regionId?) accumulates pendingRegions; alarm drains them (all-region
when empty). No global mutable current-region.
apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts
- create: fire-and-forget createRegionCacheFiles(newRegion.id) with error log.
apps/backend/src/trpc/apis/admin-apis/apis/{store,banner,product,slots}.ts
- Pass ctx.staffUser region into scheduleStoreInitialization /
createSlotsCacheFile / createAvailabilityCacheFile.
In-memory store decision: scaffolds read the scoped DB helpers directly; the
in-memory stores (product/slot) are keyed by region (regionId first param) and
live region-less user endpoints resolve the region server-side from SKU ids.
Global-files: REMOVED (see above).
Typecheck: tsc --noEmit for db_helper_sqlite + backend; fix own errors.
[2026-10-07 00:34:48] sqlite drizzle query logging — enable SQL logging on the current D1 instance.
File: packages/db_helper_sqlite/src/db/db_index.ts
Diff plan:
- Add isQueryLoggingDisabled() helper reading (globalThis as any).ENV?.DRIZZLE_LOG
?? (globalThis as any).process?.env?.DRIZZLE_LOG (safe on Workers, no direct
process.env access). Logging is ON unless flag is false/'false'/'0'.
- Add queryLogger = { logQuery(query, params) } printing `[drizzle] <query>` + params
via console.log.
- Pass `logger` into drizzle(database, { schema, logger }) in initDb so every query
through the current instance is logged. Set DRIZZLE_LOG=false to silence.
[2026-10-07 10:11:12] Phase 1 (superadmin) — regions, bounds, bound settings, superadmin identities.
New migration 0006 plus a new superadmin API channel and superadmin UI. Planned diffs:
packages/db_helper_sqlite/src/db/schema.ts
- Add RegionGeoJson interface and tables regions, region_bounds,
region_bound_settings (region_id + bound_id + key + value), superadmins.
- Add relations for the above.
packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql (new)
- Create the four tables + unique indexes.
- Seed region "Mahabubnagar"; two bounds (Mbnr-1 priority 1, Mbnr-2 priority 2)
with exact GeoJSON; 11 bound settings rows per bound; bootstrap superadmin.
packages/db_helper_sqlite/drizzle/meta/_journal.json
- Append journal entry idx 6 -> 0006_regions_and_superadmins.
packages/db_helper_sqlite/src/superadmin-apis/regions.ts (new)
- Region/bound/settings persistence + effective-bound (lowest priority).
packages/db_helper_sqlite/src/superadmin-apis/auth.ts (new)
- Superadmin lookup.
packages/db_helper_sqlite/index.ts
- Export the new persistence helpers.
packages/shared/types/region.types.ts (new), superadmin.types.ts (new)
packages/shared/types/index.ts
- Re-export the new types.
apps/backend/src/trpc/trpc-index.ts
- Add superadmin context field and superadminProcedure guard.
apps/backend/src/app.ts
- Resolve superadmin identity from token (identityType/superadminId).
apps/backend/src/trpc/router.ts
- Register superadmin router.
apps/backend/src/trpc/apis/superadmin-apis/apis/{auth,regions,superadmin-trpc-index}.ts (new)
apps/backend/src/sqliteImporter.ts
- Re-export new superadmin/region helpers.
apps/superadmin-ui/src/lib/trpc-client.ts
- Use a separate superadmin_token storage key.
apps/superadmin-ui/src/lib/auth-context.tsx
- Authenticate via superadmin.auth (login/me).
apps/superadmin-ui/src/routes/login.tsx
- Superadmin username/password copy.
apps/superadmin-ui/src/routes/regions.tsx (new)
apps/superadmin-ui/src/routes/dashboard.tsx, src/components/AppShell.tsx
- Add Regions navigation.
apps/superadmin-ui/src/routeTree.gen.ts
- Register the /regions route (normally regenerated by the router plugin).
[2026-10-07 10:49:25] Phase 2 (staff/admin) — per-bound regional settings in admin-ui.
apps/admin-ui/components/context/staff-auth-context.tsx
- Extend the session `Staff` shape with optional `regionId: number | null`
(login already returns it); expose `regionId` on the auth context value.
- Capture regionId from the login response (setStaff(data.staff)).
- Non-breaking: existing consumers of `staff` keep working.
apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx
- Replace the single global constants form with one tab per region bound
(admin.region.bounds, ascending priority). Each tab shows the bound
description (or "Bound #id") + priority and marks the lowest-priority
bound as "Effective" (its settings apply to checkout).
- Selected bound loads admin.region.getBoundSettings and renders the 11
regional keys as editable inputs (reuse ConstantInput; add a
`allowSectionNavigation` prop so popularItems/allItemsOrder become inline
comma-separated inputs instead of links to the global editors).
- Save via admin.region.updateBoundSettings with only changed keys
(string|null values). Default-select lowest-priority bound; reinitialize
the form (Formik enableReinitialize + key) so drafts do not leak between
tabs. Loading / error / "no bounds configured" states.
- Keep the existing global constants form reachable via a top-level
"Regional Settings" / "Global Constants" switch (admin.const.* unchanged).
- Show the current region name (admin.region.current) in the header.
- No staff-account creation UI exists in admin-ui (createStaffUser/
getRoles are unused); nothing to remove.
[2026-10-07 10:51:16] Phase 3 (user-ui) — browsing region store, selection UI, switch/reset, address region, regional checkout + history labels.
New files:
- apps/user-ui/src/store/regionStore.ts (new)
- zustand store persisted via zustand/middleware `persist` + `createJSONStorage`
over common-ui `StorageServiceCasual`. State: `selectedRegionId: number | null`,
`selectedRegion: RegionSummary | null`, monotonic `regionGeneration` marker
(race guard). Actions: `setRegion(region)`, `clearRegion()`. Persist key
`freshyo-region`, version 1.
- apps/user-ui/src/lib/region-switch.ts (new)
- Centralized `confirmRegionSwitch(region, queryClient)`: clears regular+flash
local carts (clearLocalCart), resets quick-delivery selected slot, address
selection, slot/store stores and flash-cart/flash-navigation state, calls
regionStore.setRegion, then invalidates all react-query caches.
- apps/user-ui/src/components/RegionSelector.tsx (new)
- Lists trpc.common.listRegions. `mode='gate'` renders a full-screen first-run
chooser; `mode='switch'` is dialog content and opens an Alert confirmation
stating the whole cart will be cleared, then runs confirmRegionSwitch.
- apps/user-ui/src/components/RegionGate.tsx (new)
- Hydration-aware gate: waits for persisted region, validates the saved region
against common.listRegions (clears stale ids), renders RegionSelector until a
region exists, otherwise children.
Modified files:
- packages/shared/types/app-common.types.ts
- Add optional `regionId?: number` to AddressFormProps.initialValues.
- apps/user-ui/src/components/AddressForm.tsx
- Query common.listRegions; required inline region dropdown; new addresses
default to the browsing region while edits keep the stored region unless
explicitly changed; include `regionId` in create/update payloads + Yup rule.
- apps/user-ui/components/CheckoutAddressSelector.tsx
- Region-aware selection: cross-region address prompts confirmation, runs
confirmRegionSwitch and routes home; default auto-select only for the current
region; attach-location update now sends regionId.
- apps/user-ui/components/QuickDeliveryAddressSelector.tsx
- Same cross-region address handling (confirmation + centralized switch +
navigate home); shows a switch prompt when the selected/default address
belongs to another region.
- apps/user-ui/app/(drawer)/(tabs)/me/addresses/index.tsx
- Carry regionId on the edit view-model/initialValues and include it in the
set-default updateAddress payload.
- apps/user-ui/components/PaymentAndOrderComponent.tsx
- Read selectedRegionId from regionStore, block submit without a region, and
pass `regionId` to user.order.placeOrder; surface backend errors safely.
- apps/user-ui/app/(drawer)/(tabs)/me/my-orders/index.tsx
- Render `regionName` badge on each order (list stays account-wide).
- apps/user-ui/app/(drawer)/(tabs)/me/my-orders/[id].tsx
- Show order region label in the detail header.
- apps/user-ui/components/FirstUserWrapper.tsx
- Wrap children in RegionGate so a user with no saved region is prompted.
- apps/user-ui/app/(drawer)/(tabs)/me/index.tsx
- Add a "Delivery Region" entry that opens RegionSelector in switch mode.
[2026-10-07 10:54:56] Phase 1 follow-up — backend region wiring + migrations 0006/0007.
packages/db_helper_sqlite/src/db/schema.ts
- region_id added (nullable, app-enforced) to product_info, staff_users,
store_info, vendor_snippets, product_tag_info, product_group_info,
delivery_slot_info, coupons, home_banners, addresses, orders.
- ordersRelations gains region relation.
packages/db_helper_sqlite/drizzle/0007_region_columns_backfill.sql (new)
- ALTER TABLE add nullable region_id + backfill all rows to Mahabubnagar + indexes.
packages/db_helper_sqlite/drizzle/meta/_journal.json
- journal entry idx 7 -> 0007_region_columns_backfill.
packages/db_helper_sqlite/src/admin-apis/staff-user.ts
- createStaffUserWithRegion(); getAllStaff now returns regionId.
packages/db_helper_sqlite/src/user-apis/address.ts
- createUserAddress/updateUserAddress accept and persist regionId; mapUserAddress returns regionId.
packages/db_helper_sqlite/src/user-apis/order.ts
- OrderWithRelations gains regionId/region; order reads include region relation.
packages/shared/types/user.ts
- UserAddress.regionId; UserOrderSummary.regionId/regionName.
apps/backend/src/trpc/apis/superadmin-apis/apis/staff.ts (new)
- superadmin.staff.list/roles/create (region required).
apps/backend/src/trpc/apis/admin-apis/apis/region.ts (new)
- admin.region.current/bounds/effective/getBoundSettings/updateBoundSettings (staff region scoped).
apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
- common.listRegions + common.regionSettings (public).
apps/backend/src/trpc/apis/user-apis/apis/address.ts
- createAddress/updateAddress require regionId.
apps/backend/src/trpc/apis/user-apis/apis/order.ts
- placeOrder requires regionId; address/region mismatch rejected; order stores region; history returns regionName.
apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts
- staff login returns staff.regionId.
apps/backend/src/sqliteImporter.ts
- re-export createStaffUserWithRegion and region helpers.
apps/admin-ui, apps/user-ui: region-aware screens per the two UI workstreams
(bound tabs + staff region; region store/selector/switch + address region + history labels).
Typecheck: db_helper_sqlite, backend and superadmin-ui all pass (tsc --noEmit). No migrations run, no tests run, no git.
[2026-10-07 11:12:00] Phase 1 addendum — 0007 now rebuilds the region FK subgraph with region_id NOT NULL.
packages/db_helper_sqlite/drizzle/0007_region_columns_backfill.sql
- After the nullable ADD COLUMN + backfill, rebuild every table in the region_id
FK subgraph (31 tables incl. product_skus, order_items, orders, staff_notif_creds,
coupon_* etc.) per docs/recreate-referenced-tables.md: create __new parent-first,
copy all columns, drop leaves-first, rename parents-first, recreate indexes.
- region_id is now NOT NULL (FK to regions) in the rebuilt tables.
- CHECK on product_reviews written unqualified.
Schema note: Drizzle schema keeps region_id nullable to avoid breaking existing
insert call sites; the DB is stricter. Remaining admin create paths (product, store,
banner, coupon, tag, group, slot) must be updated to supply the staff region.
[2026-10-07 11:24:00] Wire regionId into all region-owned create paths (region is required, no defaults).
DB helpers (packages/db_helper_sqlite/src):
- admin-apis/product.ts: createProduct(input, regionId), createProductTag(input, regionId),
createProductGroup(..., regionId) now write region_id.
- admin-apis/store.ts: createStore(input, products, regionId).
- admin-apis/banner.ts: createBanner(input, regionId).
- admin-apis/vendor-snippets.ts: createVendorSnippet({..., regionId}).
- admin-apis/slots.ts: createSlotWithRelations(input, regionId); snippet inserts inherit region.
- admin-apis/coupon.ts: createCouponWithRelations(..., regionId),
createReservedCouponWithProducts(..., regionId), generateCancellationCoupon(..., regionId),
createCouponForUser(..., regionId).
- admin-apis/staff-user.ts: createStaffUser(..., regionId).
- user-apis/coupon.ts: redeemReservedCoupon copies reservedCoupon.regionId into the coupon.
- schema.ts + 0007: reserved_coupons is now region-owned too (ALTER + backfill + rebuild NOT NULL + index).
- Removed all `?? 1` fallbacks; regionId is mandatory and must be supplied by the caller.
Routers (apps/backend/src/trpc/apis/admin-apis/apis):
- product.ts / store.ts / banner.ts / vendor-snippets.ts create procedures now use staffProcedure
and pass ctx.staffUser.regionId.
- slots.ts / coupon.ts / staff-user.ts pass ctx.staffUser.regionId (and order.regionId for
cancellation coupons).
Typecheck: db_helper_sqlite and backend pass.
[2026-10-07 11:27:35] Fix 0007 migration failure (FOREIGN KEY constraint failed).
Root cause (proven on a copy of the local D1 DB, statement-by-statement):
- The drop/rebuild ordering was correct; the real problem is legacy DATA written
before FK enforcement that violates the FKs the rebuilt tables declare:
* 5 orders.address_id values no longer exist in addresses.
* 11 payments rows whose order no longer exists (ALL payment rows are orphans).
The __new_orders copy (statement #75) and later __new_payments copy (#83) fail
on these live orphan rows.
- Additionally the first partial run had already committed phase 1 (ALTERs +
backfill + 19 __new_ copies), so re-running the file as-is would fail on duplicate columns.
Planned diff for packages/db_helper_sqlite/drizzle/0007_region_columns_backfill.sql:
- Remove the ALTER-ADD-COLUMN + backfill phase entirely. region_id is added by the
rebuild itself, computed at DB level in each copy SELECT
((SELECT id FROM regions WHERE name='Mahabubnagar')). No app-level defaults.
- Add a repair phase before the copy:
* DELETE FROM payments WHERE order_id NOT IN (SELECT id FROM orders);
* remove the 5 orphan orders AND their dependents: delete their
payments/order_items/order_status/refunds, null out coupon_usage.order_id /
coupon_usage.order_item_id / complaints.order_id / user_incidents.order_id.
- Drop the pre-rebuild region indexes (created after rename only).
- Journal entry unchanged (idx 7).
- After migration: user resets local D1 state and re-runs 0006 + 0007;
verify with PRAGMA foreign_key_check and row counts.
[2026-10-07 11:41:00] 0007 repair extended + proof harness run (read-only, on a COPY of the local DB).
- Repair phase also deletes order_status and refunds of the 5 orphan orders
(their copies would otherwise fail FK to __new_orders first).
- Proof harness on a copy of the actual local D1 DB (freshyo-dev, FK enforcement ON,
statement-by-statement like wrangler):
* All statements pass; PRAGMA foreign_key_check = 0 violations; zero __new_ leftovers.
* Row deltas exactly as intended: orders -5, order_items -19, order_status -5,
payments -11 (all), refunds -2; every other table unchanged.
* region_id NOT NULL enforced and FK rejection verified post-rename (writes rejected).
* All 13 original unique indexes recreated (4 table-prefixed + 9 unique_*).
- Important: wrangler runs the file in one transaction — the earlier failed run left
NO partial state, so the fixed 0007 can simply be re-run (0006 already applied).
[2026-10-07 11:45:00] Superadmin staff-user CRUD (regions reassignment + removal).
- admin-apis/staff-user.ts (db_helper_sqlite): add updateStaffUserRegion(staffId, regionId)
and deleteStaffUser(staffId). Delete removes staff_notif_creds rows, clears nullable
references (user_incidents.added_by), and refuses when the staff still owns a store
or created coupons / reserved coupons (NOT NULL dependent FKs would break).
- export both helpers from packages/db_helper_sqlite/index.ts and re-export them in
apps/backend/src/sqliteImporter.ts.
- superadmin-apis/apis/staff.ts: add superadmin.staff.update (reassign region) and
superadmin.staff.remove (delete with blockedBy reason).
- superadmin-ui: new routes/staff.tsx CRUD screen (list, add with role+region, region
reassignment, delete w/ confirmation + blocked-reason display); AppShell nav entry
"Admin Users"; routeTree.gen.ts registers /staff.
[2026-10-07 11:41:17] Enable Maestro MCP server in project opencode.jsonc.
- Ran: opencode mcp add maestro -- maestro mcp
(registers local stdio MCP server "maestro" running `maestro mcp`,
Maestro 2.11.0 built-in MCP server, project-local config).
[2026-10-07 12:03:54] Phase 4 (admin-web) — per-bound regional settings port from admin-ui.
Planned diffs:
apps/admin-web/src/components/context/staff-auth-context.tsx
- Extend session `Staff` shape with optional `regionId: number | null`
(login already returns it); expose `regionId` on the auth context value.
- Non-breaking: existing consumers of `staff` keep working.
apps/admin-web/src/routes/dashboard.customize-app.tsx
- Replace the single global constants form with one tab per region bound
(admin.region.bounds, ascending priority). Each tab shows the bound
description (or "Bound #id") + priority and marks the lowest-priority
bound as "Effective" (its settings apply to checkout).
- Selected bound loads admin.region.getBoundSettings and renders the 11
regional keys as editable inputs (ConstantInput gains an
`allowSectionNavigation` prop so popularItems/allItemsOrder become inline
comma-separated inputs instead of links to the global editors).
- Save via admin.region.updateBoundSettings with only changed keys
(string|null values). Default-select lowest-priority bound; reinitialize
the form (Formik enableReinitialize + key) so drafts do not leak between
tabs. Loading / error / "no bounds configured" states.
- Keep the existing global constants form reachable via a top-level
"Regional Settings" / "Global Constants" switch (admin.const.* unchanged).
- Show the current region name (admin.region.current) in the header.
- No staff-account creation UI exists in admin-web (createStaffUser/
getRoles unused); nothing to remove.
[2026-10-07 $(date +%H:%M:%S)] Phase 4 (web-ui) — port browsing-region features from user-ui (Expo) to web-ui (TanStack Start).
New files:
- apps/web-ui/src/lib/stores/region-store.ts (new)
- zustand `persist` store over an SSR-safe localStorage wrapper (web equivalent
of Expo's StorageServiceCasual). Same shape as user-ui regionStore:
selectedRegionId / selectedRegion / regionGeneration + setRegion / clearRegion.
Persist key `freshyo-region`, version 1.
- apps/web-ui/src/lib/region-switch.ts (new)
- Centralized `confirmRegionSwitch(region, queryClient)`: clears regular+flash
local carts (localStorage + react-query cart keys), resets quick-delivery
selected slot, address selection, slot store ids, cart-store added product,
flash-cart product, flash-navigation flag, clears central product/slot
snapshots, persists the new region, then invalidates all react-query caches.
Callers must confirm with the user before invoking.
- apps/web-ui/src/components/RegionSelector.tsx (new)
- Lists trpc.common.listRegions. mode='gate' full-screen first-run chooser
(direct select, no cart exists yet); mode='switch' dialog content with an
inline "entire cart will be cleared" confirmation before confirmRegionSwitch.
- apps/web-ui/src/components/RegionGate.tsx (new)
- Hydration-aware gate: waits for persisted region, validates saved region
against common.listRegions (clears stale ids), renders children until
hydrated (SSR-safe, avoids hydration mismatch) then a blocking overlay with
RegionSelector until a region exists.
Modified files:
- apps/web-ui/src/routes/__root.tsx
- Wrap app children in RegionGate (inside trpc/Auth providers).
- apps/web-ui/src/components/AddressForm.tsx
- Required region <select> from common.listRegions; new addresses default to
the browsing region, edits keep the stored region; regionId in
create/update payloads + Yup required rule.
- apps/web-ui/src/hooks/checkout-hooks.ts (useCheckoutAddress)
- Default auto-select only for current-region addresses; expose cross-region
helper data (addresses carry regionId).
- apps/web-ui/src/components/CheckoutAddressSelector.tsx
- Cross-region tap -> confirm (entire cart cleared) -> confirmRegionSwitch ->
navigate home; same-region selection preserves cart.
- apps/web-ui/src/routes/home.checkout.tsx + flash.checkout.tsx
- Same cross-region address handling; placeOrder payloads gain regionId;
backend mismatch errors surfaced.
- apps/web-ui/src/components/PaymentAndOrderComponent.tsx
- Reads selectedRegionId, blocks submit without a region, passes regionId to
placeOrder, surfaces backend mismatch message.
- apps/web-ui/src/routes/me.orders.tsx + me.orders.$id.tsx
- Account-wide history (no region filter) with regionName labels.
- apps/web-ui/src/routes/me.addresses.tsx
- Address view-model carries regionId; edit initialValues keep stored region;
set-default payload includes regionId (blocked with a message when missing).
- apps/web-ui/src/routes/me.tsx
- "Delivery Region" menu entry opening RegionSelector in switch mode.
- Query keys: same as Expo (version-keyed global catalog caches, no region in
keys); region switch clears central stores + invalidates all queries so no
stale cross-region snapshots survive.
Typecheck: `npx tsc --noEmit --project apps/web-ui/tsconfig.json` from repo root.
[2026-10-07 12:14:52] Browser verification fix — allow localhost:4176 in backend CORS.
apps/backend/src/app.ts
- CORS origin list gains 'http://localhost:4176' (admin-web auto-bumps to 4176
when superadmin-ui already holds 4175; without this the browser blocks API calls).
[2026-10-07 12:18:39] Browser verification (Playwright MCP): web-ui region gate + admin-web bound tabs.
- web-ui :4174 region gate renders with Mahabubnagar; selection dismisses gate.
- admin-web :4176 staff login (uitest/test1234, regionId 1) works; customize-app shows
Region: Mahabubnagar, Mbnr-1 P1 EFFECTIVE / Mbnr-2 P2 tabs, all 11 settings loaded.
- E2E save verified twice in D1 (deliveryCharge 20->25, minRegularOrderValue 300->350
on bound 1 only; bound 2 untouched), then restored to seeded values via SQL.
- test staff row 'uitest' left in local D1 for reuse (region 1, role admin).
- Note: backend CORS already included :4176. One benign console error (numberOfLines prop).
[2026-10-07 12:20:40] Isolation test fixtures in LOCAL dev D1 only (not app code).
- Region 2 'Testnagar' + 1 bound (priority 1, square GeoJSON) + 11 settings rows
(deliveryCharge 30 / minRegularOrderValue 500 to distinguish from Mahabubnagar).
- Staff 'uitest2' (region 2, role admin, password test1234) for cross-region API tests.
- All fixture rows are test-only and removable.
[2026-10-07 12:24:46] Region-scope CATALOG admin read paths (staff sees own region only).
Planned diffs:
packages/db_helper_sqlite/src/admin-apis/product.ts
- getAllProducts(regionId), getProductById(regionId, id),
getAllProductTags(regionId), getAllProductTagInfos(regionId),
getProductTagInfoById(regionId, tagId), getProductTagById(regionId, tagId),
getProductReviews(regionId, productId, limit, offset),
getAllProductGroups(regionId): regionId as FIRST param; list endpoints add
eq(<table>.regionId, regionId); single-ID reads use and(id, regionId) and
return null outside the region; reviews scoped via product_info.region_id
join (reviews + count). checkProductExistsByName /
checkProductTagExistsByName stay GLOBAL. Writes, price/stock mutations,
respondToReview untouched.
packages/db_helper_sqlite/src/admin-apis/store.ts
- getAllStores(regionId), getStoreById(regionId, id); add `and` import.
packages/db_helper_sqlite/src/admin-apis/banner.ts
- getBanners(regionId), getBannerById(regionId, id); add `and` import.
apps/backend/src/trpc/apis/admin-apis/apis/product.ts, store.ts, banner.ts
- Read procedures keep protectedProcedure (no auth restructure) and pass
ctx.staffUser!.regionId, including read-before-write existence checks in
updateStore / updateProductTag / deleteProductTag.
apps/backend/src/stores/banner-store.ts
- getBannerById wrapper threads regionId through (dead code, no callers;
updated only for typecheck).
apps/backend/src/stores/product-tag-store.ts
- getTagsByStoreId resolves the store's own regionId via storeInfo and
scopes getAllProductTags to it; user-apis callers untouched (stay working).
Typecheck: tsc --noEmit for packages/db_helper_sqlite + apps/backend.
[2026-10-07 12:24:34] Region-scope OPERATIONAL admin read paths (slots, snippets, coupons, orders, users, complaints).
Planned diffs (regionId added as FIRST param of each read helper; lists filter by
region; single-ID reads constrain by region and return null outside it; writes,
check*Exists validators, superadmin/user/region/const paths untouched):
packages/db_helper_sqlite/src/admin-apis/slots.ts
- getActiveSlotsWithProducts(regionId, limit): where isActive + region_id.
- getSlotsAfterDate(regionId|null, afterDate): region filter when non-null
(null = global, used only by the public vendor getUpcomingSlots link).
- getSlotByIdWithRelations(regionId, id): and(id, region_id), null outside.
- getSlotDeliverySequence(regionId, slotId): and(id, region_id), null outside.
packages/db_helper_sqlite/src/admin-apis/vendor-snippets.ts (add `and` import)
- getVendorSnippetById(regionId, id): and(id, region_id).
- getVendorSnippetByCode(regionId|null, code): region-verified when non-null
(null = global public vendor order-list links).
- getAllVendorSnippets(regionId): where region_id.
- getProductsByIds(regionId|null, skuIds): empty->[]; when region set, keep only
SKUs whose parent product is in-region (columns gain product.regionId).
- getVendorSlotById(regionId|null, slotId): region-verified when non-null.
- getVendorOrdersBySlotId(regionId|null, slotId): and(slot, region) when non-null.
packages/db_helper_sqlite/src/admin-apis/coupon.ts (add `sql`/`SQL` imports)
- getAllCoupons(regionId, cursor, limit, search): push region condition.
- getCouponById(regionId, id): and(id, region_id).
- getReservedCoupons(regionId, cursor, limit, search): push region condition.
- getOrderWithUser(regionId, orderId): and(id, region_id).
- getUsersForCoupon(regionId, search, limit, offset): EXISTS in-region order filter
(users scoped via orders.region_id, not addresses).
packages/db_helper_sqlite/src/admin-apis/order.ts (import deliverySlotInfo)
- getOrderDetails(regionId, orderId): and(id, region_id).
- getSlotOrders(regionId, slotId): verify slot in-region first (else empty list);
then and(slot, region) on orders.
- getAllOrders(regionId, input): seed whereCondition with region equality.
packages/db_helper_sqlite/src/admin-apis/user.ts (add `and`/`or`/`isNull` imports)
- getUnresolvedComplaintsCount(regionId): unresolved AND (orderless OR order in-region).
- getAllUsersWithFilters(regionId, limit, cursor, search): EXISTS in-region order.
- getOrderCountsByUserIds / getLastOrdersByUserIds(regionId, userIds): AND region.
- getSuspensionStatusesByUserIds(regionId, userIds): param added for uniformity;
no filter (user_details has no region; callers pass in-region users only).
- getUserBasicInfo(regionId, userId): null unless >=1 in-region order.
- getUserOrders(regionId, userId): and(user, region).
- getOrderStatusesByOrderIds / getItemCountsByOrderIds(regionId, orderIds):
prefetch in-region order ids, query only those.
- searchUsers(regionId, search): EXISTS in-region order (both branches).
- getUserIncidentsWithRelations(regionId, userId): keep orderless or in-region-order
incidents (JS filter on joined order.regionId).
packages/db_helper_sqlite/src/admin-apis/complaint.ts (add `and`/`or`/`isNull`, orders import)
- getComplaintById(regionId, id): null when order-backed and order out-of-region/missing.
- getComplaints(regionId, cursor, limit): left-join orders, keep orderless OR
in-region-order complaints (+ cursor).
apps/backend/src/trpc/apis/admin-apis/apis/{slots,vendor-snippets,coupon,order,user,complaint}.ts
- Thread ctx.staffUser.regionId (staffProcedure where imported, else
protectedProcedure + ctx.staffUser!.regionId) into every scoped helper call.
- Public vendor endpoints (getOrdersBySnippet, getOrdersBySnippetAndSlot,
getUpcomingSlots) pass null = deliberately global vendor links (no staff region).
- slots.getDeliverySequence gains the missing staff guard (needed for region).
- complaint.resolve's pre-check becomes region-scoped (write helper untouched).
- payments.ts: stub, no order reads -> no change.
- Writes (updates/deletes/invalidates/suspends), check*Exists validators, notif-cred
reads, and non-admin callers unchanged by design; residual cross-region write
paths noted in final report, not altered.
Typecheck: npx tsc --noEmit --project packages/db_helper_sqlite/tsconfig.json AND
apps/backend/tsconfig.json; fix introduced errors. No tests, no git, no migrations.
[2026-10-07 12:31:10] Region-scope admin UPDATE/DELETE-by-ID paths + cross-region relationship validation on creates.
Planned diffs (regionId as FIRST param on helpers; single-ID mutations constrain with
and(id, regionId) and return null/false outside the region; creates validate related
IDs resolve to in-region rows and throw Error('... belongs to a different region')):
packages/db_helper_sqlite/src/admin-apis/product.ts
- deleteProduct(regionId, id), updateProduct(regionId, id, input: region-scoped
pre-read + update where; cross-region combo skuIds + storeId rejected.
- createProduct: storeId must resolve to an in-region store; combo-item skuIds
must resolve via parent product_info.region_id (validation BEFORE the
generic try/catch so the message surfaces).
- createProductTag: relatedStores must be in-region stores.
- replaceTagProducts(regionId, tagId, productIds): tag must be in-region; skuIds
must be in-region (via parent product).
- updateProductTag(regionId, tagId, input) -> null outside region; validates
relatedStores in-region. deleteProductTag(regionId, tagId) -> boolean.
- createProductGroup/updateProductGroup: productIds (SKU ids) validated in-region.
- updateProductGroup(regionId, ...), deleteProductGroup(regionId, ...) scoped.
- updateProductPrices(regionId, updates): out-of-region SKUs reported as invalidIds.
- toggleProductOutOfStock(regionId, productId): null outside region.
- respondToReview(regionId, reviewId, ...): null when the review's product is
out-of-region. check*Exists validators stay global.
packages/db_helper_sqlite/src/admin-apis/store.ts
- updateStore(regionId, id, input, products?), deleteStore(regionId, id) scoped
(delete/update throw 'Store not found' when outside region, as before).
- createStore/updateStore: owner staff must be in-region; product SKU ids must
resolve to in-region products.
packages/db_helper_sqlite/src/admin-apis/banner.ts
- updateBanner(regionId, id, input) -> Banner|null; deleteBanner(regionId, id)
-> boolean. createBanner/updateBanner: skuIds validated in-region.
packages/db_helper_sqlite/src/admin-apis/slots.ts
- updateSlotWithRelations(regionId, input), updateSlotCapacity(regionId, ...),
updateSlotDeliverySequence(regionId, ...) scoped (null outside region).
- createSlotWithRelations/updateSlotWithRelations: skuIds + snippet skuIds +
groupIds validated in-region. staleSlotsCleanup left global (maintenance).
packages/db_helper_sqlite/src/admin-apis/vendor-snippets.ts
- updateVendorSnippet(regionId, id, updates) -> null outside region; new slotId +
skuIds validated in-region. deleteVendorSnippet(regionId, id) scoped.
- createVendorSnippet: slotId + skuIds validated in-region.
- updateVendorOrderItemPackaging left global (public vendor link, no staff ctx).
packages/db_helper_sqlite/src/admin-apis/coupon.ts
- updateCouponWithRelations(regionId, id, ...) -> null outside region; new
applicableProducts validated in-region. invalidateCoupon(regionId, id) ->
Coupon|null. createCouponWithRelations/createReservedCouponWithProducts:
applicableProducts validated in-region. generateCancellationCoupon verifies
the order's region matches. createCouponForUser unchanged (note).
packages/db_helper_sqlite/src/admin-apis/order.ts
- updateOrderNotes/updateOrderPackaged/updateOrderDelivered/removeDeliveryCharge/
cancelOrder/deleteOrderById(regionId, ...) scoped (null/false/order_not_found
outside region). updateOrderItemPackaging(regionId, ...) resolves the parent
order's region first. updateAddressCoords(regionId, ...) constrains
addresses.regionId. rebalanceSlots(regionId, slotIds) only touches in-region
slots/orders. deleteOrdersWithRelations left global (note: caller is the
global lib/delete-orders cleanup path).
packages/db_helper_sqlite/src/admin-apis/user.ts — untouched (upsertUserSuspension
account-global, createUserIncident no region needed — noted only).
packages/db_helper_sqlite/src/admin-apis/complaint.ts — resolveComplaint(regionId,
id, response) -> boolean, constrained via the getComplaintById region pattern.
apps/backend/src/trpc/apis/admin-apis/apis/{product,store,banner,slots,
vendor-snippets,coupon,order,complaint}.ts — thread ctx.staffUser.regionId
(staffProcedure where imported, else protectedProcedure + ctx.staffUser!.regionId)
into every changed helper; map null/false to NOT_FOUND (no cross-region leak);
create-validation Errors surface as-is.
Typecheck: npx tsc --noEmit --project packages/db_helper_sqlite/tsconfig.json AND
apps/backend/tsconfig.json; fix introduced errors. No tests, no git, no migrations.
[2026-10-07 12:52:57] Region isolation testing — two-region (Mahabubnagar + Testnagar) verification.
API (26/26 checks pass):
- Creates in both regions via admin API: stores, tags, products, slots, coupons, banners.
- Lists isolated: staff1 sees R1-only tags, staff2 sees R2-only tags.
- Cross-region reads 404 without leaking (tag by id both ways; order details both ways).
- Cross-region updates rejected (store update, slot capacity); own-region update works.
- Cross-region create validation: R1 product with R2 store rejected.
- Address saves regionId; mismatched checkout (region 1 order + region 2 address) rejected.
- Region-2 order placed end-to-end (id 2454, regionId 2); staff1 list/detail exclude it,
staff2 list/detail include it; user history carries regionName labels.
- Duplicate (region_id, priority) rejected by unique index (proven at DB level).
Browser (Playwright MCP):
- web-ui gate lists both regions; switch Testnagar->Mahabubnagar with seeded cart:
confirm dialog clears cart 1->0; cancel preserves cart + region.
- admin-web customize bound tabs + E2E save verified earlier.
- staff2 bounds endpoint returns Test-1 only; staff1 returns Mbnr-1/2 only.
Left in LOCAL dev D1 (test-only, removable): region Testnagar + bound + settings,
staff uitest/uitest2, ISO stores/tags/products/slots/coupons/banners, test address 875,
order 2454. Temp scripts removed from repo.
NOT covered: superadmin Regions/Staff UI pages (need superadmin password);
storefront browsing still serves the global cache (per-region cache files pending).
[2026-10-07 13:05:00] Region-aware storefront catalog (user-ui + web-ui) against the FIXED backend contract.
Planned diffs (frontend only; backend untouched — another agent implements the contract):
apps/user-ui/src/hooks/prominent-api-hooks.ts
- useGetEssentialConsts reads selectedRegionId from regionStore and calls
trpc.common.essentialConsts with { regionId } (cast for forward-compat;
current backend ignores the extra input at runtime). Enabled only when a
region is selected; persisted discovery key becomes per-region
(essential_consts_r<regionId>) so regions never share snapshots.
- Regional URL builders from discovery data (effectiveSettings.regionId with
selectedRegionId fallback):
products/stores/per-store files:
{assetsDomain}{apiCacheKey}/regions/{regionId}/v-{cacheVersion}/{file}
availability:
{assetsDomain}regions/{regionId}/av-{availabilityVersion}/availability.json
slots:
{assetsDomain}regions/{regionId}/slots/v-{slotsVersion}/slots.json
Null regionId -> null URL -> catalog queries stay disabled (gate covers
the no-region case).
- New useRegionalConsts(): discovery data with the 5 delivery/minimum fields
(deliveryCharge, freeDeliveryThreshold, flashDeliveryCharge,
flashFreeDeliveryThreshold, minRegularOrderValue) overridden from
effectiveSettings.settings (numeric parse, global fallback). Display-only;
backend stays authoritative for the actual charge.
apps/user-ui/src/lib/region-switch.ts
- confirmRegionSwitch additionally drops old-region react-query catalog
snapshots (removeQueries on all-products/stores/slots/availability/
store-with-products) before setRegion + invalidateQueries refetches
discovery and catalog for the new region. Central stores cleared as before.
Cancel path unchanged.
apps/user-ui/components/{cart-page,checkout-page,floating-cart-bar}.tsx
- Delivery-charge/threshold messaging reads useRegionalConsts() (regional
effective settings first, global fallback).
apps/web-ui/src/hooks/prominent-api-hooks.ts
- Mirror of the user-ui hook changes above (localStorage persisted catalog
caches stay version-gated; the versioned URL now contains the region so no
cross-region placeholder can match). Banners go through the regional URL.
apps/web-ui/src/lib/region-switch.ts
- Mirror of the user-ui switch extension.
apps/web-ui/src/components/{PaymentAndOrderComponent,FloatingCartBar}.tsx
- Delivery-charge/threshold display prefers effectiveSettings via
useRegionalConsts(); submit logic (regionId payload) untouched.
Admin apps: grep apps/admin-ui + apps/admin-web for essentialConsts/cache-file
consumers — report only, no edits.
Typecheck: npx tsc --noEmit --project apps/user-ui/tsconfig.json AND
apps/web-ui/tsconfig.json. No tests, no git, no migrations.
[2026-10-07 13:06:59] Per-region storefront cache phase — backend + clients implemented, pending 0008.
Backend: region_cache_versions table + 0008 migration (NOT run); all *ForCache
helpers + scaffolds region-first; KV essential_consts:{regionId}; regional paths
regions/{id}/...; createRegionCacheFiles/createAllCacheFiles(regionId?);
essentialConsts now REQUIRES {regionId}; CacheCreator DO drains per-region queue.
Clients (user-ui + web-ui): discovery passes browsing regionId; regional URL builders;
switch refetches discovery+catalog; checkout display uses effectiveSettings.
Verified: all 4 typechecks pass; new code live on :8787 (regionId required; versions
query fails until 0008 applied — expected).
NEXT: user runs 0008 on dev D1, then per-region generation is triggered and verified.
[2026-10-07 13:13:31] Per-region storefront verified end-to-end.
- 0008 applied by user; per-region generation triggered (store updates) — all
counters 1->2 in both regions; regional files live on CDN.
- File partition proven: r1 products.json 150 rows incl ISOProdR1, tags ISOTagR1 only;
r2 1 row (ISOProdR2), tags ISOTagR2 only; zero cross-leaks either way.
- Browser (web-ui): Testnagar storefront shows ISOTagR2+ISOProdR2, no R1 leaks;
Mahabubnagar shows ISOTagR1, no R2 leaks. (ISOProdR1 below render window;
present in-file; its tag mapping empty by fixture design.)
- Cross-region tag mapping rejected: 'Product 152 belongs to a different region'.