[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'.

[2026-10-07 13:39:44] Closed loop: region-1 product verified rendered in UI.
  - web-ui search 'ISOProdR1' while browsing Mahabubnagar: 1 result (ISOProdR1,
    Rs 100, 500g), no ISOProdR2. Screenshot verified then removed.
  - Earlier home-page absence explained: new SKU shows Out of Stock (no
    availability/stock row), so it never surfaces in the purchasable list.
    Not a region issue.

[2026-10-07 13:45:12] user-ui location bar on all top-level tabs.
  - src/components/LocationBar.tsx (new): pin + region name row; tap opens
    BottomDialog with RegionSelector mode=switch (lazily mounted; sheet handles
    its own cart-clear confirmation). Rendered inside scroll content so it
    scrolls out instead of sticking.
  - Insert at top of scroll content: home listHeader, order-again ScrollView,
    FlashDeliveryProducts ListHeader, stores ListHeader, me ScrollView.

[2026-10-07 13:49:26] home: LocationBar vertically first — moved static SearchBar into
  the FlatList header below LocationBar so both scroll out together.

[2026-10-07T14:07:48+05:30] Home: scroll location away and stick the second (search) section header.
--- apps/user-ui/app/(drawer)/(tabs)/home/index.tsx
+++ apps/user-ui/app/(drawer)/(tabs)/home/index.tsx
@@ -1,5 +1,5 @@
 import React, { useState, useCallback, useMemo, memo, useRef, useEffect } from "react";
-import { View, Dimensions, Image, RefreshControl } from "react-native";
+import { View, Dimensions, Image, RefreshControl, SectionList } from "react-native";
 import { ScrollView } from "react-native-gesture-handler";
 import { useRouter } from "expo-router";
 import {
@@ -653,8 +653,6 @@
   ], [pageTint]);
 
   const listHeader = useMemo(() => (
-    <>
-      <LocationBar />
     <ListHeader
       dashboardTags={dashboardTags}
       activeTagId={activeTagId}
@@ -666,7 +664,6 @@
       storesData={storesData}
       sortedSlots={sortedSlots}
     />
-    </>
   ), [dashboardTags, activeTagId, productsByTagId, expandedByTagId, handleToggleExpand, handleProductPress, storesData, sortedSlots]);
 
   const listContentContainerStyle = useMemo(() => [
@@ -698,34 +695,52 @@
   return (
     <TabLayoutWrapper style={{ backgroundColor: '#FFFFFF' }}>
       <View style={pageTintStyle}>
-        <View
-          style={searchBarContainerStyle}
-        >
-          <SearchBar
-            testID="home-search"
-            value={""}
-            onChangeText={() => { }}
-            onPress={handleSearchPress}
-            editable={false}
-            containerStyle={tw`bg-white`}
-            onSubmitEditing={() => {
-              if (inputQuery.trim()) {
-                router.push(`/(drawer)/(tabs)/home/search-results?q=${encodeURIComponent(inputQuery.trim())}`);
-              }
-            }}
-            returnKeyType="search"
-          />
-        </View>
-
-        <MyFlatList
-          data={displayedProducts.slice(0, visibleCount)}
-          keyExtractor={(item) => item.id.toString()}
-          numColumns={3}
+        <SectionList
+          sections={[{ data: [[], ...Array.from(
+            { length: Math.ceil(Math.min(displayedProducts.length, visibleCount) / 3) },
+            (_, index) => displayedProducts.slice(index * 3, Math.min(index * 3 + 3, visibleCount))
+          )] }]}
+          keyExtractor={(row, index) => row.length ? row.map((item) => item.id).join('-') : 'catalog-header'}
+          stickySectionHeadersEnabled
           style={{ backgroundColor: '#FFFFFF' }}
           contentContainerStyle={listContentContainerStyle}
-          columnWrapperStyle={staticStyles.columnWrapper}
-          renderItem={renderProductItem}
-          ListHeaderComponent={listHeader}
+          ListHeaderComponent={<LocationBar />}
+          renderSectionHeader={() => (
+            <View style={searchBarContainerStyle}>
+              <SearchBar
+                testID="home-search"
+                value={""}
+                onChangeText={() => { }}
+                onPress={handleSearchPress}
+                editable={false}
+                containerStyle={tw`bg-white`}
+                onSubmitEditing={() => {
+                  if (inputQuery.trim()) {
+                    router.push(`/(drawer)/(tabs)/home/search-results?q=${encodeURIComponent(inputQuery.trim())}`);
+                  }
+                }}
+                returnKeyType="search"
+              />
+            </View>
+          )}
+          renderItem={({ item: row, index }) => index === 0 ? (
+            <>
+              {listHeader}
+              {displayedProducts.length === 0 && (
+                <View style={tw`items-center py-8`}>
+                  <MyText style={tw`text-gray-500`}>No products available</MyText>
+                </View>
+              )}
+            </>
+          ) : (
+            <View style={[staticStyles.columnWrapper, { flexDirection: 'row' }]}>
+              {row.map((item) => (
+                <React.Fragment key={item.id}>
+                  {renderProductItem({ item })}
+                </React.Fragment>
+              ))}
+            </View>
+          )}
           ListFooterComponent={
             hasMore ? (
               <View style={tw`items-center py-4`}>
@@ -748,11 +763,6 @@
               colors={[theme.colors.brand500]}
             />
           }
-          ListEmptyComponent={
-            <View style={tw`items-center py-8`}>
-              <MyText style={tw`text-gray-500`}>No products available</MyText>
-            </View>
-          }
           // NOTE: do not add removeClippedSubviews here - it breaks touch
           // delivery to the nested horizontal scrollables in ListHeaderComponent
           // (tag tabs / slots) on Android.

[2026-10-07 14:13:37] user-ui: single region source-of-truth hook.
  - NEW src/hooks/useRegion.ts: useRegion() returns { region, regionId,
    regionGeneration, hydrated, setRegion, clearRegion }. Wraps useRegionStore;
    owns the persist-hydration subscription so consumers no longer touch the store.
  - Routed all region/location reads through useRegion: LocationBar, RegionGate,
    RegionSelector (dropped selectedRegionId prop, reads hook), AddressForm,
    QuickDeliveryAddressSelector, PaymentAndOrderComponent, CheckoutAddressSelector,
    me/index.tsx, prominent-api-hooks (useGetEssentialConsts, useDiscoveryRegionId).
  - region-switch.ts keeps useRegionStore.getState() (non-hook lib, cannot call hooks).

[2026-10-07 14:26:08] location-based region resolution (backend + user-ui).
  Backend:
   - shared: add RegionBoundSummary + ResolvedRegion types (region.types.ts).
   - db_helper_sqlite: add getAllRegionsWithBounds() (regions ordered by id,
     each region's bounds ordered by ascending numeric priority); export it.
   - common tRPC: add public resolveRegionByLocation({lat,lng}) -> { region,
     bound } | null. Iterates every region, and within each region checks bounds
     least-priority-first; first containing bound wins. GeoJSON features
     (Polygon/MultiPolygon) converted with @turf.
  user-ui:
   - NEW src/store/locationStore.ts: zustand singleton that owns expo-location
     permission + watchPosition fixes (coords/status/error), start/stop/refresh.
   - src/hooks/useRegion.ts: now the location-aware single source of truth. While
     no region is chosen it starts tracking + calls resolveRegionByLocation and
     auto-sets the region; exposes coords/status/bound/isResolvingRegion. Stops
     tracking once a region exists.
   - RegionGate: shows spinner while resolving; only falls back to the chooser
     when location is unavailable/denied/no match.

[2026-10-07 15:02:02] user-ui: LocationTestWrapper owns the region chooser fallback.
  - NEW src/lib/is-emulator.ts: extracted emulator/simulator detection.
  - store/locationStore.ts: skip requesting location on emulators (status
    'unavailable'); check Location.hasServicesEnabledAsync(); race the first fix
    against a timeout so a missing GPS fix can no longer hang 'locating'.
  - LocationTestWrapper: rewritten as the region gate. Renders app once a region
    exists; spinner while deriving it from location; full-screen RegionSelector
    when location services are off, permission denied, on a simulator, or no
    bound contains the coordinates. Keeps the stale-region validation.
  - Moved LocationTestWrapper up (FirstUserWrapper) so the gate sits above
    Auth/Notification providers; removed it from app/_layout.tsx.
  - Removed src/components/RegionGate.tsx (superseded by LocationTestWrapper).

[2026-10-07 15:20:00] fix: region spinner stuck / infinite re-render.
  - regionStore: setRegion/clearRegion are now no-ops when nothing changes,
    so they no longer bump regionGeneration (and re-render) on every call.
  - useRegion: add resolvedAttempt flag -> isResolvingRegion flips false after
    the first definitive answer and never latches back on 'idle'; stop location
    tracking once settled; memoize/round the resolve query input; 8s resolve
    timeout fallback.
  - locationStore: round coords to ~1m and skip store updates when unchanged,
    so GPS jitter no longer churns a new query key every watch callback.
  - LocationTestWrapper: validation is membership-only (no setRegion in the
    effect), removing a possible self-triggering loop.

[2026-10-07 15:24:00] RegionSelector is controlled again (selectedRegionId prop) so
  the chooser no longer calls useRegion / starts location tracking; callers
  (LocationTestWrapper, LocationBar, me) pass the id from their useRegion.

[2026-10-07 15:42:21] regions cannot be created without bounds.
  - shared: add RegionBoundSeedInput + CreateRegionWithBoundsInput.
  - db_helper_sqlite: add createRegionWithBounds() (region + bounds inserted
    atomically in one transaction); export it.
  - superadmin regions.create: now requires bounds (min 1, valid GeoJSON +
    numeric priority) and returns { region, bounds }; duplicate priority -> 409.
  - superadmin-ui Regions page: create form now collects at least one bound
    (description/priority/GeoJSON supports multiple rows); legacy empty create
    removed.

[2026-10-07 15:58:00] admin-ui logout debug logging added temporarily.
  - (drawer)/_layout.tsx: log on drawer Logout item tap.
  - staff-auth-context.tsx: log on logout() entry and after deleteJWT resolves.

[2026-10-07 16:03:00] admin-ui logout: removed the temporary debug console.logs
  (drawer Logout handler and staff-auth-context logout()).

[2026-10-07 16:40:00] admin pickers leak cross-region data: fixed.
  - Root cause: three admin-only pickers used public, unscoped common endpoints.
  - common.getStoresSummary: public PROCEDURE aggregating ALL regions -> now
    protectedProcedure returning only the caller staff region's stores.
  - common.product.getAllProductsSummary: aggregated ALL regions -> now
    protectedProcedure returning scaffolledProducts(ctx.staffUser.regionId) only.
  - common.product.getAllSkusSummary: returned ALL SKUs -> protectedProcedure +
    new regionId arg on getAllSkusSummary (default null keeps old signature).
  - Affects admin-ui AND admin-web (both attach the staff JWT). The customer apps
    never call these (they use regional CDN cache files), so no public surface lost.

[2026-10-07 17:10:00] fix: essentialConsts returned region-1 values for region 3.
  Root cause: backend scaffold sent per-region settings as `regionSettings`
  but user-ui/web-ui read `effectiveSettings` -> override never applied, so the
  global (region-1-authored) top-level consts showed for every region.
  - backend scaffoldEssentialConsts now returns `effectiveSettings` (canonical)
    plus `regionSettings` alias for KV-cached payloads.
  - user-ui + web-ui read effectiveSettings ?? regionSettings, so even stale KV
    entries resolve correctly without waiting for a KV refresh.
  - After deploy, refresh KV (any const update / cache regen / seed calls
    refreshGenKv) so new payloads carry the canonical field.

[2026-10-07 17:25:00] fix: bound mutations now refresh KV.
  - updateBoundSettings wrote D1 only; KV mirror kept stale values.
    Now looks up the bound's region and awaits refreshGenKv(regionId).
  - Same staleness class fixed for createBound and updateBound (a new/changed
    bound can become the effective lowest-priority one).

[2026-10-07 17:40:00] fix: essentialConsts top-level fields now carry effective regional values.
  - scaffoldEssentialConsts resolved each business field as bound setting ??
    global const ?? default (numbers parsed, booleans coerced, raw passthrough
    otherwise), instead of storing globals flat next to the nested block.
  - Also exposes minRegularOrderValue/allItemsOrder/welcomeMessage top-level
    (previously nested-only). Helper return types stay `any` so the client
    contract is unchanged; only values changed.
  - Nested effectiveSettings (+regionSettings alias) retained for provenance
    and the client override path. Requires KV refresh post-deploy (any const
    save / cache regen / seed) to rewrite stored payloads.

[2026-10-07 17:55:00] essentialConsts payload is now flat: removed the nested
  effectiveSettings/regionSettings block. Top-level fields are the region's
  effective values (bound setting ?? global), so there is nothing nested left
  to re-appear. Clients keep reading the optional nested block only as a
  backward-compat fallback for payloads already cached in KV.

[2026-10-08 00:10:10] Part 1/2 - split consts model into three tables (global_consts / region_consts / region_bound_consts) + per-bound flat JSON in KV.

Planned diffs (backend + db_helper + admin-ui + admin-web + superadmin-ui; NO migration run; NO tests; NO git):

packages/db_helper_sqlite/src/db/schema.ts
  - Add globalConsts(key PK, value), regionConsts(region_id,key PK), regionBoundConsts(bound_id,key PK) tables.
  - Remove regionCacheVersions + regionBoundSettings tables and relations.
packages/db_helper_sqlite/drizzle/0009_three_const_tables.sql (new, NOT run) + meta/_journal.json idx 9.
  - CREATE 3 tables; copy global / region (versions + region-level keys incl allItemsOrder from effective bound) / bound rows;
    DELETE migrated keys from key_val_store (keep leftovers); DROP region_bound_settings + region_cache_versions.
packages/db_helper_sqlite/src/lib/const-keys.ts
  - Add GLOBAL_CONST_KEYS / REGION_CONST_KEYS / BOUND_CONST_KEYS / LEGACY_CONST_KEYS; rename cacheVersion -> products_version_num; keep merged CONST_KEYS.
packages/db_helper_sqlite/src/admin-apis/const.ts
  - Add getAllGlobalConsts/upsertGlobalConsts, getRegionConsts/upsertRegionConsts, getBoundConsts/upsertBoundConsts, getLegacyConsts/upsertLegacyConsts;
    getAllConstants/upsertConstants route by scope. Remove dead global version counters.
packages/db_helper_sqlite/src/lib/region-cache-versions.ts
  - Back get/incrementRegion* with region_consts rows (products_version_num / availability_version_num / slots_version_num).
packages/db_helper_sqlite/src/superadmin-apis/regions.ts
  - getBoundSettings/upsertBoundSettings -> region_bound_consts; add getRegionConstants/upsertRegionConstants;
    getEffectiveRegionSettings merged region+bound; add getEffectiveBoundId; getAllRegions + effectiveBoundId; seed defaults on create.
packages/db_helper_sqlite/src/db/seed.ts + seed.sql, index.ts exports.
packages/shared/types/region.types.ts - RegionSummary.effectiveBoundId.
apps/backend/src/lib/const-keys.ts, lib/const-store.ts, lib/gen-store.ts (essentialConsts_{boundId}),
  trpc/apis/common-apis/common-trpc-index.ts (scaffoldEssentialConsts(boundId), essentialConsts {boundId}, listRegions effectiveBoundId, regionSettings merged),
  lib/cloud_cache.ts, lib/flash-delivery-cron.ts, lib/seed.ts, sqliteImporter.ts,
  trpc/apis/admin-apis/apis/const.ts (global/legacy procedures + compat alias), admin-apis/apis/region.ts (region + bound constants),
  superadmin-apis/apis/regions.ts, new superadmin-apis/apis/const.ts router.
apps/admin-ui + apps/admin-web: customize-app 3 tabs (Global/Region/Bound); popular-items/all-items-order region-scoped; tagsOrder via legacy.
apps/superadmin-ui: constants.tsx -> superadmin.const.*; regions.tsx region + bound editors.
Typecheck: db_helper_sqlite, backend, admin-ui, superadmin-ui, admin-web.

[2026-10-08 00:29:40] Part 1/2 follow-up — finish the admin UIs (admin-ui, admin-web, superadmin-ui) + move tagsOrder into region_consts.

Backend/db (tagsOrder is now region-scoped, per user decision; overrides the plan which kept it legacy):
packages/db_helper_sqlite/src/lib/const-keys.ts
  - CONST_KEYS/LABELS/TYPES/VISIBILITY/DEFAULTS: add tagsOrder (string, hidden, default '[]').
  - REGION_CONST_KEYS: add 'tagsOrder'; LEGACY_CONST_KEYS: remove 'tagsOrder'.
apps/backend/src/lib/const-keys.ts
  - REGION_CONST_KEYS: add 'tagsOrder'; LEGACY_CONST_KEYS: remove 'tagsOrder'.
packages/db_helper_sqlite/drizzle/0009_three_const_tables.sql (NOT run)
  - Copy tagsOrder from key_val_store into region_consts per region; delete it from key_val_store.
packages/db_helper_sqlite/src/db/seed.ts
  - Remove tagsOrder from legacy seed list (region_defaults now seeds it).
apps/backend/src/lib/seed.ts
  - Remove tagsOrder from legacy seed list.
apps/backend/src/trpc/apis/admin-apis/apis/region.ts
  - updateRegionConstants: trigger scheduleStoreInitialization when tagsOrder changes; ignore version-counter keys.
apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts
  - updateRegionConstants: ignore version-counter keys (read-only).
apps/backend/src/trpc/apis/common-apis/common.ts
  - scaffoldProducts: read tagsOrder from region_consts (region-scoped) instead of the global key_val_store.

Admin UIs (3 tabs Global/Region/Bound; Global holds legacy keys, globals hidden; Region hides version counters; Bound = 5 keys):
apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx
  - Replace 2-way switch with 3 tabs; global uses admin.const.getGlobalConstants/getLegacyConstants, region uses admin.region.getRegionConstants/updateRegionConstants, bound keeps per-bound Formik; hide tab if no visible keys.
apps/admin-ui/app/(drawer)/dashboard/customize-app/popular-items.tsx
apps/admin-ui/app/(drawer)/dashboard/customize-app/all-items-order.tsx
  - Read/write popularItems/allItemsOrder via admin.region.getRegionConstants/updateRegionConstants.
apps/admin-ui/app/(drawer)/dashboard/product-tags/order.tsx
  - Read/write tagsOrder via admin.region.getRegionConstants/updateRegionConstants.
apps/admin-ui/components/OrderOptionsMenu.tsx
  - welcomeMessage read via admin.region.getRegionConstants.
apps/admin-web/src/routes/dashboard.customize-app.tsx
  - 3 tabs as above.
apps/admin-web/src/routes/dashboard.customize-app.popular.tsx
apps/admin-web/src/routes/dashboard.customize-app.ordering.tsx
  - Region-scoped popularItems/allItemsOrder.
apps/admin-web/src/routes/dashboard.product-tags.order.tsx
  - Region-scoped tagsOrder.
apps/superadmin-ui/src/routes/constants.tsx
  - Use superadmin.const.getGlobalConstants/updateGlobalConstants + getLegacyConstants/updateLegacyConstants; drop region/bound keys.
apps/superadmin-ui/src/routes/regions.tsx
  - Split into RegionConstantsEditor (superadmin.regions.getRegionConstants/updateRegionConstants, version counters hidden) and BoundSettingsEditor (5 bound keys).

web-ui and user-ui untouched. No migrations run. No tests run.

[2026-10-08 00:41:00] Part 1/2 follow-up completed. Backend/db_helper/admin-ui/admin-web/superadmin-ui typecheck clean (tsc --noEmit). Migration 0009 NOT run (user runs it). web-ui + user-ui untouched.
  Notes/decisions:
  - Global tab in admin-ui/admin-web shows the legacy leftovers (platformFeePercent,
    minOrderAmountForCoupon, flashDeliverySlotId); the 4 global keys stay hidden there and are
    managed in superadmin-ui. Tab is hidden entirely if it would render no visible keys.
  - Region tab hides the 3 version counters; tagsOrder is edited on the Tag Orders screen
    (admin apps) and in the superadmin Region settings editor (no dedicated tags screen there).
  - List screens send comma-joined ids to the region endpoint (input is a strict scalar union).
  - Stale: apps/admin-ui/tests/** still mock admin.const.getConstants/updateConstants (tests not run).

[2026-10-08 00:44:05] Part 2/2 — apps/user-ui consumes the per-bound flat JSON.

apps/user-ui/src/store/regionStore.ts
  - Add selectedBoundId (persisted); setRegion(region, boundId?) compares+stores it; clearRegion resets it.
apps/user-ui/src/hooks/useRegion.ts
  - Expose boundId from the store; on resolve persist setRegion(resolved.region, resolved.bound.id); setRegion signature gains boundId.
apps/user-ui/src/lib/region-switch.ts
  - confirmRegionSwitch(region, queryClient, boundId?) forwards boundId to setRegion.
apps/user-ui/src/components/RegionSelector.tsx
apps/user-ui/components/CheckoutAddressSelector.tsx
apps/user-ui/components/QuickDeliveryAddressSelector.tsx
  - Pass region.effectiveBoundId to confirmRegionSwitch.
apps/user-ui/src/hooks/prominent-api-hooks.ts
  - useGetEssentialConsts reads boundId from useRegion, queries { boundId }, persists under essential_consts_b{boundId}.
  - useDiscoveryRegionId reads flat data.regionId (fallback useRegion().regionId).
  - Cache URLs use products_version_num / availability_version_num / slots_version_num.
  - useRegionalConsts is a thin passthrough of the flat payload.
  - Drop DiscoveryData extension + discoverySettings + EffectiveRegionSettings import.
No tests run. web-ui untouched.

[2026-10-08 00:49:00] Part 2/2 completed. apps/user-ui typechecks clean; backend/db/admin apps still clean.
  Deviations/notes:
  - confirmRegionSwitch(region, queryClient, boundId?) defaults boundId to region.effectiveBoundId,
    so the address-selector call sites needed no change; RegionSelector passes it explicitly.
  - useRegion derives boundId = stored ?? region.effectiveBoundId ?? null and backfills a missing
    bound via common.listRegions (covers region state persisted before selectedBoundId existed).
  - useRegionalConsts keeps a loose (any) return so cart/checkout/floating-cart need no edits.

[2026-10-08 00:57:00] Globals are superadmin-only: removed the Global tab from the admin apps.
  apps/admin-ui/.../customize-app/index.tsx and apps/admin-web/.../dashboard.customize-app.tsx
  - Drop the Global tab, renderGlobal, global/legacy queries+mutations, GLOBAL_KEYS/LEGACY_KEYS,
    CONST_VISIBILITY; tab switcher is now Region | Bound only. tsc clean.
  - Global + legacy constants remain editable in apps/superadmin-ui/src/routes/constants.tsx.
  Backend note: staff `admin.const.*` (compat getConstants/updateConstants + the new
  getGlobalConstants/updateGlobalConstants/getLegacyConstants/updateLegacyConstants) still exist and
  are pinned by apps/backend/tests; not changed (no production UI caller remains).

[2026-10-08 01:12:47] Added packages/db_helper_sqlite/drizzle/merged_regions.sql — one squashed migration replacing 0006_regions_and_superadmins + 0007_region_columns_backfill + 0008_region_cache_versions + 0009_three_const_tables.
  - Drops the two throwaway staging tables (region_bound_settings, region_cache_versions) that the originals created only to copy from and then drop; global_consts / region_consts / region_bound_consts are seeded directly instead.
  - Phase order preserved: (1) regions/region_bounds/superadmins + seeds (from 0006), (2) 0007 region_id rebuild verbatim, (3) const tables + direct seeds (from 0008+0009).
  - Verification: rebuilt SQLite from apps/backend/dumps/latest.sql; applied 0006..0009 -> expected; applied merged_regions.sql -> merged. Python comparison: schema objects 86/86, tables 55/55, rows 21795/21795, IDENTICAL apart from CURRENT_TIMESTAMP seeds (regions.created_at, superadmins.created_at). Also validated D1-style splitting on the statement-breakpoint marker: 187 chunks, 0 failures, integrity ok, same-result. No migrations run against any real DB. No tests run.
  - Follow-up (exact-data check): re-ran 0006..0009 vs merged_regions.sql back-to-back in the same second and compared every row of the 6 new tables + 31 rebuilt tables + key_val_store with no masking -> EXACTLY IDENTICAL (rows: regions 1, region_bounds 2, superadmins 1, global_consts 3, region_consts 10, region_bound_consts 10; all 31 rebuilt tables match row-for-row, e.g. delivery_slot_info 1569, orders 2283, order_items 7959, order_status 2277, reserved_coupons 739; key_val_store 7 leftovers).
  - Squash applied: removed migrations 0006/0007/0008/0009 and replaced them with one file.
    * Backed up the pre-removal contents of 0006_regions_and_superadmins.sql,
      0007_region_columns_backfill.sql, 0008_region_cache_versions.sql and
      0009_three_const_tables.sql into
      packages/db_helper_sqlite/drizzle/stale/removed_region_migrations.txt
      (single txt, one section per file, verbatim).
    * Deleted those four .sql files.
    * Renamed packages/db_helper_sqlite/drizzle/merged_regions.sql ->
      packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql (same
      verified squashed content; staging tables removed).
    * drizzle/meta/_journal.json still lists tags 0007_region_columns_backfill,
      0008_region_cache_versions and 0009_three_const_tables; left untouched
      (user handles migrations) but needs those entries removed to stay consistent.
    * docs/consts-three-tables-part1-backend-admin.md still references
      `0009_three_const_tables`; left as-is.
    No migrations run. No tests run.

[2026-10-08 19:28:11] user-ui: startup-only location check (no movement tracking).
apps/user-ui/src/store/locationStore.ts
  - Remove watchPositionAsync subscription (movement tracking) and coordsEqual; keep a single
    getCurrentPositionAsync (8s timeout). start() idempotent via a per-launch `started` flag.
apps/user-ui/src/hooks/useRegion.ts
  - Run the location check once on hydration EVEN when a region is saved; never stop/start on regionId.
  - Apply outcome once per launch: same region -> no-op; different -> confirmRegionSwitch(resolved.region,
    queryClient, resolved.bound.id) (clears carts, invalidates region queries); null/denied/unavailable
    -> keep saved region. Single-flight switch guard (module flag) + manual-pick race guard.
  - Rename resolvedAttempt -> startupResolved; isResolvingRegion only for the true first run.
No backend changes. No tests run.

[2026-10-08 19:34:00] startup-only location check implemented. user-ui typecheck clean.
  - locationStore: single getCurrentPositionAsync per launch, no watchPositionAsync.
  - useRegion: check runs on every launch (saved region included); same -> no-op,
    different -> confirmRegionSwitch (option a: clears carts, refreshes screens);
    unusable/null -> keep saved region (or chooser when none). Single-flight switch + manual-pick race guard.

[2026-10-08 20:05:00] Checkout constants now come from the DELIVERY ADDRESS's bound (effective bound fallback).
packages/db_helper_sqlite/src/superadmin-apis/regions.ts
  - add getRegionSettingsForBound(regionId, boundId): region_consts + that bound's region_bound_consts
    (null when the bound does not belong to the region).
packages/db_helper_sqlite/index.ts - export it.
apps/backend/src/lib/region-resolve.ts (new)
  - boundToPolygons + resolveBoundForRegionPoint(regionId, lat, lng): first containing bound in
    priority-ascending order.
apps/backend/src/trpc/apis/user-apis/apis/order.ts
  - placeOrderUtil resolves the bound from the address coords (adminLatitude/Longitude ?? latitude/longitude),
    falls back to getEffectiveBoundId(regionId); bound-level constants (delivery charge/thresholds/min order)
    read via getRegionSettingsForBound. Region-level constants unchanged.
apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
  - new protectedProcedure common.resolveAddressBound({ addressId }) -> { regionId, boundId } (same resolver).
apps/user-ui/src/hooks/prominent-api-hooks.ts
  - useGetEssentialConsts uses the selected address's bound (when its region matches) else the browsing bound,
    so displayed delivery constants match what checkout charges.
Typechecks: db_helper, backend, user-ui clean.

[2026-10-08 20:23:32] user-ui: emulators/simulators are treated like physical devices for location.
apps/user-ui/src/store/locationStore.ts - remove the isEmulator() short-circuit (and import); emulators
  go through the normal permission + getCurrentPositionAsync path (they can supply a mock fix).
apps/user-ui/components/LocationTestWrapper.tsx - drop the emulator check from the spinner condition
  (and import); update the doc comment.
apps/user-ui/src/lib/is-emulator.ts left in place (now unused by location code).

[2026-10-08 20:30:00] user-ui: log the bound id used for essentialConsts.
apps/user-ui/src/hooks/prominent-api-hooks.ts - console.log the resolved boundId (+ source/region).

[2026-10-08 20:55:00] Active-bound model: addresses carry a bound_id; checkout uses the active bound.
Data model
  - schema.ts: addresses.boundId (FK region_bounds.id, nullable).
  - shared/types/user.ts: UserAddress.boundId.
  - drizzle/0007_addresses_bound_id.sql (new, NOT run): ADD COLUMN bound_id; backfill existing rows to 1.
  - meta/_journal.json: drop stale 0007/0008/0009 entries; add idx 7 = 0007_addresses_bound_id.
db_helper (user-apis/address.ts): mapUserAddress.boundId; create/update accept+persist boundId.
backend
  - user-apis/apis/address.ts: createAddress/updateAddress accept boundId; FIRST address becomes default.
  - user-apis/apis/order.ts: placeOrder accepts boundId; placeOrderUtil uses getRegionSettingsForBound(regionId,boundId)
    (fallback effective). Remove the address-coordinate bound resolution.
  - common-apis/common-trpc-index.ts: remove resolveAddressBound; lib/region-resolve.ts removed.
user-ui
  - prominent-api-hooks: useGetEssentialConsts uses the active bound only (drop resolveAddressBound override).
  - RegionSelector / region-switch: manual region pick uses the default address's bound (fallback effective).
  - AddressForm / CheckoutAddressSelector / me addresses: send boundId = active bound on create/update.
  - Checkout + quick-delivery address lists filtered to the active bound.

[2026-10-08 21:10:00] Active-bound model implemented. Typechecks: db_helper, backend, admin-ui, admin-web,
superadmin-ui, user-ui clean. (web-ui still has the known flat-JSON errors; out of scope.)
  - addresses.bound_id column + migration 0007 (backfill 1); journal tail fixed.
  - user-ui: manual region pick uses the default address's bound else effective; new addresses get the
    active bound; checkout/quick-delivery lists filtered to the active bound; order sends active boundId.
  - first address a user adds becomes their default.
  - startup location still wins for the active bound.

[2026-10-08 21:15:00] user-ui: log coords alongside the bound id in useGetEssentialConsts.

[2026-10-09 10:00:00] Active bound from the user's addresses (least-priority bound in the region).
backend
  - common-apis/common-trpc-index.ts: new common.activeBound({ regionId }) (protected) ->
    least-priority bound among the user's addresses in that region, else the region's effective bound.
user-ui
  - useRegion: region from location/manual; active bound from common.activeBound (fallback effective),
    persisted via setRegion; no longer uses the location's bound. Derivation runs on region change.
  - prominent-api-hooks: essentialConsts bound = selected checkout address's bound (same region) ?? active bound.
  - CheckoutAddressSelector / QuickDeliveryAddressSelector: show ALL addresses (no bound filter);
    same-region bound selection just re-adjusts consts, cross-region still confirms + switches.
  - PaymentAndOrderComponent: send boundId = the bound used for the displayed consts.
  - RegionSelector: manual pick no longer computes an address bound (derivation handles it).

[2026-10-09 10:15:00] activeBound model implemented. Typechecks: db_helper, backend, user-ui clean.
  - common.activeBound({regionId}) -> least-priority bound among the user's addresses in the region,
    else the region's effective bound.
  - useRegion derives the active bound from common.activeBound (fallback effective); location only sets region.
  - useGetEssentialConsts: bound = selected checkout address's bound (same region) ?? active bound.
  - Checkout/quick-delivery address lists show all addresses (all regions/bounds); same-region bound
    selection re-adjusts consts; cross-region still confirms then switches.
  - placeOrder boundId = constsData.boundId (the displayed bound).

[2026-10-09 10:30:00] fix: hooks rendered above AuthProvider no longer require it.
  - AuthContext: add useAuthOptional() (returns null instead of throwing when there is no provider).
  - useRegion + prominent-api-hooks use useAuthOptional so UpdateChecker (mounted above AuthProvider)
    no longer throws "useAuth must be used within an AuthProvider". Typecheck clean.

[2026-10-09 10:35:00] user-ui: comment out the essentialConsts boundId/coords console log (kept for later).

[2026-10-09 10:45:00] user-ui: address selector moves to the cart page; checkout shows it read-only.
  - new components/CheckoutAddressDisplay.tsx: read-only card for the selected (or default) address.
  - components/cart-page.tsx: render CheckoutAddressSelector (interactive) at the top of the scroll.
  - components/checkout-page.tsx: replace CheckoutAddressSelector with CheckoutAddressDisplay;
    drop the add-address dialog + AddressForm from checkout (no changing there).

[2026-10-09 10:55:00] done. user-ui typecheck clean.
  - cart-page shows the interactive CheckoutAddressSelector (top of the scroll, non-empty cart).
  - checkout-page shows CheckoutAddressDisplay (read-only; selected or default address); add-address
    dialog + AddressForm removed from checkout.

[2026-10-09 11:05:00] user-ui: cart page behind the login wall (useAuthenticatedRoute), covering both routes.

[2026-10-09 11:20:00] user-ui: fix cart login-wall back-loop. Replace the push-based useAuthenticatedRoute
  on the cart with an inline gate (renders a login prompt when signed out) so back navigation works.

[2026-10-09 11:35:00] user-ui: extract the login wall into components/LoginWall.tsx; use it on the cart and the me tab.
  - cart-page uses <LoginWall onBack=... />; me/_layout renders <LoginWall /> when signed out (replaces
    the push-based useAuthenticatedRoute on the me tab).

[2026-10-09 11:45:00] done. components/LoginWall.tsx (title/message/onBack); cart-page + me/_layout use it.
  me/_layout no longer uses useAuthenticatedRoute (checkout still does). user-ui typecheck clean.

[2026-10-09 12:00:00] user-ui: post-login returns to the intended page.
  - LoginWall records the current pathname in AUTH_REDIRECT_KEY before pushing /(auth)/login.
  - AuthContext.handlePostLoginRedirect now router.replace(targetPath) (was router.back()), so the
    user lands on the page they were gated from (cart/me/checkout), not home. user-ui typecheck clean.

[2026-10-09 12:10:00] user-ui cart: address selector moved below the items; "Go to 1 Hr Delivery" switcher
  card hidden ({false && ...}). user-ui typecheck clean.

[2026-10-09 12:20:00] user-ui CheckoutAddressSelector: show "No Location is attached to address" above the
  Attach Current Location button when the selected address has no coordinates.

[2026-10-09 12:30:00] user-ui cart: move the address selector to just above the Bill Details section.

[2026-10-09 12:45:00] user-ui: instructions move to the cart; checkout becomes a read-only summary.
  - new src/store/checkoutStore.ts (userNotes) shared between cart + checkout.
  - cart-page: "Delivery Instructions" input above the address selector (bound to checkoutStore).
  - PaymentAndOrderComponent: read userNotes from the store; remove its inline instructions input.
  - checkout-page: read-only summary cards for Items, Delivery Slot, Coupon (address + bill already shown).

[2026-10-09 12:55:00] done. user-ui typecheck clean.
  - checkoutStore (userNotes); cart has the Delivery Instructions input above the address selector;
    PaymentAndOrderComponent reads userNotes from the store (input removed) and still sends it with the order.
  - checkout-page shows read-only Items / Delivery Slot / Coupon cards + address + bill.

[2026-10-09 13:05:00] user-ui cart: move the Delivery Slot Summary to right after the items (before coupons).
  (Checkout page already shows Items -> Delivery Slot -> Coupon -> Address -> Bill.) typecheck clean.

[2026-10-09 13:15:00] user-ui checkout: Items section now groups by delivery slot (slot time header, then its
  items), slots sorted by time; removed the separate Delivery Slot card. typecheck clean.

[2026-10-09 13:20:00] user-ui checkout: give the slot-time header a subtle spotlight (pill background,
  brand icon, semibold text).

[2026-10-09 13:30:00] user-ui checkout: add a "Back to Cart" button above the Place Order button.

[2026-10-09 13:40:00] BUG B02 fix: signed-out users had no active bound (consts/products empty).
  - common.activeBound publicProcedure: signed-in -> least-priority address bound; signed-out -> region effective bound.
  - useRegion: propagate the location-resolved bound again (same-region -> setRegion(region,bound.id);
    region change -> confirmRegionSwitch(region,qc,resolved.bound.id)); activeBound query no longer auth-gated.

[2026-10-10 12:35:00] Testing session round 1 (docs/test-cases-multi-region.md).
  - Verified: superadmin login + regions editors (SU-1..SU-3), user-app fresh-start region resolve,
    me-tab login wall, wall -> login navigation (U-1, U-6 Me-tab, U-7 up to credentials).
  - Found + fixed B02 (signed-out users had no active bound -> no consts/products; activeBound now
    public + location bound propagated). Verified products + free-delivery threshold on device.
  - Blocked: password typing into the secure field on the iOS simulator never lands (harness quirk);
    password login could not be automated -> cart/checkout cases pending a manual sign-in or OTP.
  - Environment notes: openLink required for chromium flows; scrollUntilVisible on the admin regions
    page; text-node assertions unreliable on the RN app -> driven by point-taps + screenshots.

[2026-10-10 00:20:52 +0530] Added docs/e2e-sanity-test-plan.md following workflow/code inspection.
  - Cross-app journey checklist covering configuration, auth, catalog publication, slots, carts,
    addresses/bounds, bill parity, coupons, COD fulfillment, flash, vendors, support and recovery.
  - Separate API authorization/invariant release gates and future payment/refund readiness cases.
  - Recommended daily sanity subset, staging fixtures, bounded cache waits, evidence and policy gaps.
  - No application source changed; no tests, migrations or git commands executed.

[2026-10-10 00:31:41 +0530] Updated docs/e2e-sanity-test-plan.md per user request.
  - All login/setup flows are password-only; OTP/SMS testing explicitly excluded.
  - Replaced OTP authentication and OTP-created-account cases with password identifier
    coverage and password-change/re-login coverage, preserving existing case IDs.

[2026-10-10 01:31:35 +0530] Added docs/e2e-sanity-test-results.md (execution results for the plan).
  - Ran high-risk + daily-sanity subset via Maestro (iOS customer/admin apps) and direct
    tRPC probes: RG-01/02/03/06/10, SEC-01..05, BL-01/02/03/06, CP-01, AU-01/05,
    CT-01/04/08/09, AD-05, OR-01, SL-01, PD-01/02, PAY-01.
  - Confirmed 9 defects (D1..D9): customer token can mutate global consts (critical);
    cross-region SKU + unassigned/OOS SKU accepted by placeOrder; client/backend
    delivery-fee formula divergence (₹200 / ₹20 mismatches); min-order not enforced;
    non-atomic region create on D1; 500-instead-of-404; instructions persist post-order.
  - No application source changed. Created test-only staff/products/slots/coupon/orders
    in the disposable local DB via the app's own admin/superadmin APIs. Removed the
    half-created region (id 4) left by the RG-02 bug.

[2026-10-10 09:25:57 +0530] Continued docs/e2e-sanity-test-results.md — full second pass (~108/133 cases).
  - Added results for categories B (auth), C (products), D (discovery), E (slots),
    G (addresses), H (bill), I (coupons), J (orders), K (flash), L (vendor/support),
    and SEC-06/07/08. Extended the defect list to D1..D19.
  - New confirmed defects: D12 deleteProductTag FK failure; D13 deleteStore orphans
    products; D14 frozen slot accepted by placeOrder; D15 updatePassword duplicates
    user_creds (no effect); D16 updateProfile 500 (ctx.req.header); D17 no order
    idempotency; D18 incoherent address region/bound; D19 auth 500 vs 401.
  - Restored the disposable DB to baseline after testing (store 1 + 41 products,
    region consts, slot membership, product flags). No source changed.

[2026-10-10 09:52:53 +0530] Third pass on docs/e2e-sanity-test-results.md (~120/133 cases).
  - Ran the remaining API cases (BL-04/05, CP-02/07/08, PD-07/10/11, DS-05/07, FL-04)
    and UI cases (AU-02 cart-survives-login, AU-06 logout, AU-07 edit-profile, CT-03/06/07/10,
    DS-08 search) plus simulator GPS cases (RG-04, RG-08).
  - New defect D20: the cart does not reflect an out-of-stock item (stays orderable).
  - Notes: region B bound has an empty polygon (GPS can never resolve to B); logout does
    not clear the local cart; first-order/SKU/user/region coupon restrictions partly missing.
  - Restored flash=false, removed extra slots/fixtures. No application source changed.

[2026-10-10 09:58:00 +0530] Added docs/e2e-sanity-failed-cases.md (detailed failure report).
  - One section per FAIL case (FC-01..FC-20): symptom, repro steps, expected vs actual,
    evidence (order/entity ids), root cause with file/function, and suggested fix.
  - Cross-linked from docs/e2e-sanity-test-results.md. No application source changed.

[2026-10-10 10:05:00 +0530] Added docs/maestro-mcp-agent-guidelines.md (field guide for future agents).
  - Environment map, golden rules, working Maestro run patterns, iOS/web gotchas
    (hideKeyboard, masked secure fields, eraseText/pasteText, deep-link alert,
    screenshots/inspect_screen, permissions, simctl location), tRPC wire format,
    cache/versioning, fixtures, verified recipes, false-positive list, run checklist.
  - No application source changed.

[2026-10-10 10:26:19 +0530] .gitignore: ignore generated Expo native iOS projects (prebuild/CocoaPods output).
  - These are created by `expo run:ios` (Podfile, Podfile.lock, Pods/, xcodeproj, build/)
    and are build artifacts, not source; matches the existing apps/*/android/ rules.

  --- a/.gitignore
  +++ b/.gitignore
  @@
   apps/user-ui/android/
   apps/admin-ui/android/
  +apps/user-ui/ios/
  +apps/admin-ui/ios/
   .maestro-output/*

[2026-10-10 10:35:35 +0530] FC-01 (SEC-01): lock down admin.const router; delete dead global/legacy procedures.
  - No production UI caller existed (admin apps use admin.region.*; superadmin UI uses
    superadmin.const.*), so the four admin global/legacy procedures are removed. The two
    surviving compat procedures now require a staff token; updateConstants additionally
    rejects global-scope keys (globals are superadmin-only).

  --- a/apps/backend/src/trpc/apis/admin-apis/apis/const.ts
  +++ b/apps/backend/src/trpc/apis/admin-apis/apis/const.ts
  @@
  -import { router, protectedProcedure } from '@/src/trpc/trpc-index'
  +import { router, staffProcedure } from '@/src/trpc/trpc-index'
   import { z } from 'zod';
  +import { TRPCError } from '@trpc/server'
   import { computeConstants } from '@/src/lib/const-store'
   import { refreshGenKv, refreshGenKvForRegion } from '@/src/lib/gen-store'
   import { CONST_SCOPE } from '@/src/lib/const-keys'
   import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
   import {
     getAllConstants as getAllConstantsFromDb,
     upsertConstants as upsertConstantsInDb,
  -  getAllGlobalConsts,
  -  upsertGlobalConsts,
  -  getLegacyConsts,
  -  upsertLegacyConsts,
   } from '@/src/dbService'
  @@
  -const toRows = (constants: Constant[]) =>
  -  constants.map((c) => ({ key: c.key, value: c.value == null ? null : String(c.value) }))
  -
   export const constRouter = router({
     // Backward-compat: merged global + legacy view. Writes route by key scope.
  -  getConstants: protectedProcedure
  +  getConstants: staffProcedure
       .query(async (): Promise<Constant[]> => {
         return getAllConstantsFromDb();
       }),
   
  -  updateConstants: protectedProcedure
  +  updateConstants: staffProcedure
       .input(constantsInput)
       .mutation(async ({ input, ctx }): Promise<ConstantUpdateResult> => {
         const { constants } = input;
   
         const invalidKeys = constants
           .filter(c => !CONST_SCOPE[c.key])
           .map(c => c.key);
   
         if (invalidKeys.length > 0) {
           throw new Error(`Invalid constant keys: ${invalidKeys.join(', ')}`);
         }
   
  +      // Global constants (versionNum, playStoreUrl, …) are superadmin-only and are
  +      // managed via superadmin.const.*. Never let a region staff token write them
  +      // through the merged route.
  +      const globalKeys = constants
  +        .filter((c) => CONST_SCOPE[c.key] === 'global')
  +        .map((c) => c.key)
  +
  +      if (globalKeys.length > 0) {
  +        throw new TRPCError({
  +          code: 'FORBIDDEN',
  +          message: `Global constants are superadmin-only: ${globalKeys.join(', ')}`,
  +        })
  +      }
  +
         const regionId = ctx.staffUser?.regionId ?? null
         await upsertConstantsInDb(constants, regionId ?? undefined)
         ...
       }),
  -
  -  // Global consts (global_consts table).
  -  getGlobalConstants: protectedProcedure
  -    .query(async (): Promise<Constant[]> => {
  -      const values = await getAllGlobalConsts()
  -      return Object.entries(values).map(([key, value]) => ({ key, value }))
  -    }),
  -
  -  updateGlobalConstants: protectedProcedure
  -    .input(constantsInput)
  -    .mutation(async ({ input }): Promise<ConstantUpdateResult> => {
  -      await upsertGlobalConsts(toRows(input.constants))
  -      await computeConstants()
  -      await refreshGenKv()
  -      return {
  -        success: true,
  -        updatedCount: input.constants.length,
  -        keys: input.constants.map(c => c.key),
  -      }
  -    }),
  -
  -  // Legacy leftovers (key_val_store table).
  -  getLegacyConstants: protectedProcedure
  -    .query(async (): Promise<Constant[]> => {
  -      const values = await getLegacyConsts()
  -      return Object.entries(values).map(([key, value]) => ({ key, value }))
  -    }),
  -
  -  updateLegacyConstants: protectedProcedure
  -    .input(constantsInput)
  -    .mutation(async ({ input }): Promise<ConstantUpdateResult> => {
  -      await upsertLegacyConsts(toRows(input.constants))
  -      await computeConstants()
  -      if (input.constants.some((c) => CACHE_AFFECTING_KEYS.includes(c.key))) {
  -        await scheduleStoreInitialization()
  -      }
  -      return {
  -        success: true,
  -        updatedCount: input.constants.length,
  -        keys: input.constants.map(c => c.key),
  -      }
  -    }),
   });

  --- a/apps/backend/tests/api/authorization-matrix.test.ts
  +++ b/apps/backend/tests/api/authorization-matrix.test.ts
  @@
  -    it('pins: a user token CAN change config via admin.const.updateConstants', async () => {
  -      const before = await getConstants()
  -      const original = before.minOrderAmountForCoupon
  -
  -      try {
  -        await apiClient(userToken).admin.const.updateConstants.mutate({
  -          constants: [{ key: 'minOrderAmountForCoupon', value: 4321 }],
  -        })
  -        expect(asNumber((await getConstants()).minOrderAmountForCoupon)).toBe(4321)
  -      } finally {
  -        if (original !== undefined) await setConst('minOrderAmountForCoupon', original)
  -      }
  -    })
  -
   // ...moved to the "staff-guarded admin procedures" block, inverted:
  +    it('rejects a user token on admin.const.updateConstants', async () => {
  +      const error = await captureError(() =>
  +        apiClient(userToken).admin.const.updateConstants.mutate({
  +          constants: [{ key: 'minOrderAmountForCoupon', value: 4321 }],
  +        })
  +      )
  +      expect(error.message).toMatch(/UNAUTHORIZED|unauthorized/i)
  +    })
  +
  +    it('rejects a staff token writing a global constant via admin.const.updateConstants', async () => {
  +      const staff = await staffSession()
  +      const error = await captureError(() =>
  +        apiClient(staff.token).admin.const.updateConstants.mutate({
  +          constants: [{ key: 'versionNum', value: '9.9.9' }],
  +        })
  +      )
  +      expect(error.message).toMatch(/superadmin-only/i)
  +    })
  -    it('rejects a user token on admin.coupon.create', async () => { ... })  [kept]
  (also drops now-unused imports asNumber/getConstants/setConst if no longer referenced)

  Docs (no code): apps/backend/tests/BUGS.md entry #1 (drop admin.const.updateConstants from
  the reachable list); docs/e2e-sanity-failed-cases.md FC-01 + docs/e2e-sanity-test-results.md D1
  marked fixed. No migrations run. No tests run.

[2026-10-10 10:45:42 +0530] FC-02/FC-03/FC-13: validate order items and slots in placeOrderUtil.
  - New helper getDeliverySlotById (raw slot row) in user-apis/slots.ts, exported as
    getUserDeliverySlotById. placeOrderUtil now:
      * per item: product region must equal the order region (409); product must not be
        isDeleted / isOutOfStock / isSuspended (400).
      * per slot (scheduled only): slotId must be non-null; slot must exist, belong to the
        region (409), be isActive, have freezeTime > now and deliveryTime > now, and carry
        every ordered skuId in slot.skuIds (400).
    Covers FC-02 (cross-region SKU), FC-03 (unassigned/OOS) and FC-13 (frozen slot).
  - No schema/migration changes.

  --- a/packages/db_helper_sqlite/src/user-apis/slots.ts
  +++ b/packages/db_helper_sqlite/src/user-apis/slots.ts
  @@
   export async function getActiveSlotsList(regionId: number): Promise<UserDeliverySlot[]> {
  +
  +export async function getDeliverySlotById(slotId: number): Promise<SlotRow | null> {
  +  const slot = await db.query.deliverySlotInfo.findFirst({
  +    where: eq(deliverySlotInfo.id, slotId),
  +  })
  +  return slot ?? null
  +}

  --- a/packages/db_helper_sqlite/index.ts
  +++ b/packages/db_helper_sqlite/index.ts
  @@
   export {
     // User Slots
     getActiveSlotsList as getUserActiveSlotsList,
     getProductAvailability as getUserProductAvailability,
  +  getDeliverySlotById as getUserDeliverySlotById,
   } from './src/user-apis/slots'

  --- a/apps/backend/src/trpc/apis/user-apis/apis/order.ts
  +++ b/apps/backend/src/trpc/apis/user-apis/apis/order.ts
  @@
   import {
     ...
     getUserSlotCapacityStatus,
  +  getUserDeliverySlotById,
     ...
   } from "@/src/dbService";
  @@
   for (const item of selectedItems) {
     const product = await getOrderProductById(item.skuId);
     if (!product) {
       throw new ApiError(`Product ${item.skuId} not found`, 400);
     }
  +
  +  // SEC-04: the SKU must belong to the region being ordered into.
  +  if ((product.product?.regionId ?? null) !== params.regionId) {
  +    throw new ApiError(`Product ${item.skuId} is not available in this region`, 409);
  +  }
  +
  +  // SEC-05: never sell a deleted, out-of-stock or suspended product.
  +  if (product.isDeleted || product.isOutOfStock || product.marketStats?.isSuspended) {
  +    throw new ApiError(`Product ${item.skuId} is unavailable`, 400);
  +  }
  +
     if (!ordersBySlot.has(item.slotId)) { ... }
   }
  @@
   if (params.isFlash) { ... }
  +
  +// SEC-05 / SL-04: validate every scheduled slot (existence, region, state,
  +// freeze/delivery time) and that it carries the ordered SKUs.
  +if (!params.isFlash) {
  +  for (const [slotId, items] of ordersBySlot) {
  +    if (slotId == null) throw new ApiError("A delivery slot is required for scheduled orders", 400);
  +    const slot = await getUserDeliverySlotById(slotId);
  +    if (!slot) throw new ApiError("Selected delivery slot not found", 400);
  +    if (slot.regionId !== params.regionId)
  +      throw new ApiError("Selected delivery slot belongs to a different region", 409);
  +    if (!slot.isActive) throw new ApiError("Selected delivery slot is not available", 400);
  +    const now = Date.now();
  +    if (slot.freezeTime.getTime() <= now)
  +      throw new ApiError("Selected delivery slot is closed for orders", 400);
  +    if (slot.deliveryTime.getTime() <= now)
  +      throw new ApiError("Selected delivery slot has already passed", 400);
  +    const slotSkuIds = new Set(slot.skuIds ?? []);
  +    for (const item of items) {
  +      if (!slotSkuIds.has(item.skuId))
  +        throw new ApiError(`Product ${item.skuId} is not available in the selected delivery slot`, 400);
  +    }
  +  }
  +}

  --- a/apps/backend/tests/api/place-order-edge-cases.test.ts
  +++ b/apps/backend/tests/api/place-order-edge-cases.test.ts
  @@
  -  const place = (over) => apiClient(userToken).user.order.placeOrder.mutate({
  -    selectedItems: [{ skuId, quantity: 1, slotId }], addressId, paymentMethod: 'cod', ...over })
  +  const place = (over) => apiClient(userToken).user.order.placeOrder.mutate({
  +    selectedItems: [{ skuId, quantity: 1, slotId }], addressId, regionId: 1,
  +    paymentMethod: 'cod', ...over })
  @@
  -    it('pins: an out-of-stock product is still orderable', ...  expect(res.success).toBe(true)
  +    it('rejects an out-of-stock product', ...  expect(error.message).toMatch(/unavailable/i)
  -    it('pins: an inactive slot is accepted', ...  expect(res.success).toBe(true)
  +    it('rejects an inactive slot', ...  expect(error.message).toMatch(/not available/i)
  -    it('pins: a slot whose delivery time has passed is accepted', ...
  +    it('rejects a slot whose delivery time has passed', ...
  -    it('pins: a slot that does not carry the ordered SKU is accepted', ...
  +    it('rejects a slot that does not carry the ordered SKU', ... /not available in the selected/i)

  Docs (no code): apps/backend/tests/BUGS.md #13/#16; docs/e2e-sanity-failed-cases.md
  FC-02/FC-03/FC-13 + docs/e2e-sanity-test-results.md SEC-04/SEC-05/SL-04/D2/D3/D14.
  No migrations run. No tests run.

[2026-10-10 10:52:10 +0530] Test fixtures: pass the now-required regionId (1) to user.address.createAddress.
  - Pre-existing staleness (createAddress requires regionId since the multi-region work);
    matches the existing Mahabubnagar/region-1 assumption in these fixtures.

  --- a/apps/backend/tests/helpers/fixtures.ts
  +++ b/apps/backend/tests/helpers/fixtures.ts
  @@
   const created = await client.user.address.createAddress.mutate({
  +  regionId: 1,
     name: 'API Test Address',
     phone: '9999999999',
     addressLine1: '1 API Test Street',
     city: 'Mahabubnagar',
     state: 'Telangana',
     pincode: '509001',
     isDefault: true,
   })
   (applied to both ensureUserAddress and registerUserWithAddress)

[2026-10-10 11:24:13 +0530] FC-07/FC-08: backend placeOrder now uses the customer app's pricing model.
  - Threshold key: minRegularOrderValue -> freeDeliveryThreshold (flash unchanged).
  - Discount computed on the whole cart subtotal (frontend formula: percent
    min(subtotal*pct/100, maxValue || Infinity); flat min(flat, maxValue || subtotal)),
    then delivery decided on the post-discount total: finalTotal < threshold ? charge : 0.
  - Per suborder: discount allocated by subtotal proportion; delivery charge kept on the
    first suborder; total = subOrderTotal - orderDiscount + orderDelivery.
  - Drops the applyDiscountToUserOrder call (percent coupon no longer discounts delivery).
  - No nested ternaries. No schema/migration changes.

  --- a/apps/backend/src/trpc/apis/user-apis/apis/order.ts
  +++ b/apps/backend/src/trpc/apis/user-apis/apis/order.ts
  @@
   import {
  -  applyDiscountToUserOrder,
     cancelUserOrderTransaction,
     ...
   } from "@/src/dbService";
  @@
  -  const minOrderValue = isFlashDelivery
  +  const freeDeliveryThreshold = isFlashDelivery
       ? numSetting(CONST_KEYS.flashFreeDeliveryThreshold)
  -    : numSetting(CONST_KEYS.minRegularOrderValue);
  +    : numSetting(CONST_KEYS.freeDeliveryThreshold);
  @@
   const appliedCoupon = await validateAndGetUserCoupon(couponId, userId, totalAmount);
  -const expectedDeliveryCharge = totalAmount < minOrderValue ? deliveryCharge : 0;
  -const totalWithDelivery = totalAmount + expectedDeliveryCharge;
  +let discountAmount = 0;
  +if (appliedCoupon) {
  +  const maxValue = appliedCoupon.maxValue ? parseFloat(appliedCoupon.maxValue.toString()) : 0;
  +  if (appliedCoupon.discountPercent) {
  +    const percentDiscount = (totalAmount * parseFloat(appliedCoupon.discountPercent.toString())) / 100;
  +    discountAmount = Math.min(percentDiscount, maxValue || Infinity);
  +  } else if (appliedCoupon.flatDiscount) {
  +    const flat = parseFloat(appliedCoupon.flatDiscount.toString());
  +    discountAmount = Math.min(flat, maxValue || totalAmount);
  +  }
  +}
  +const finalTotal = totalAmount - discountAmount;
  +const expectedDeliveryCharge = finalTotal < freeDeliveryThreshold ? deliveryCharge : 0;
  +const totalWithDelivery = finalTotal + expectedDeliveryCharge;
  @@
  -    const subOrderTotalWithDelivery = subOrderTotal + expectedDeliveryCharge;
  -    const orderGroupProportion = subOrderTotal / totalAmount;
  -    const orderTotalAmount = isFirstOrder ? subOrderTotalWithDelivery : subOrderTotal;
  -    const { finalOrderTotal: finalOrderAmount } = applyDiscountToUserOrder(
  -      orderTotalAmount, appliedCoupon, orderGroupProportion)
  +    const orderGroupProportion = totalAmount > 0 ? subOrderTotal / totalAmount : 0;
  +    const orderDiscount = discountAmount * orderGroupProportion;
  +    const orderDelivery = isFirstOrder ? expectedDeliveryCharge : 0;
  +    const finalOrderAmount = subOrderTotal - orderDiscount + orderDelivery;
  @@
  -      deliveryCharge: isFirstOrder ? expectedDeliveryCharge.toString() : "0",
  +      deliveryCharge: orderDelivery.toString(),

  --- a/apps/backend/tests/api/coupon-math.test.ts
  +++ b/apps/backend/tests/api/coupon-math.test.ts
  @@
   apiClient(userToken).user.order.placeOrder.mutate({
     selectedItems: items,
     addressId,
  +  regionId: 1,
     paymentMethod: 'cod',
   @@
  -it('pins: a percentage coupon discounts the delivery fee too', ...
  -  expect(total(res)).toBeCloseTo((UNIT_PRICE + deliveryCharge) * 0.9, 6)
  +it('applies a percentage coupon to the goods subtotal only', ...
  +  expect(total(res)).toBeCloseTo(UNIT_PRICE * 0.9 + deliveryCharge, 6)
  @@
  -it('pins: a 100% coupon zeroes the order without going negative', ...
  -  expect(total(res)).toBe(0)
  +it('a 100% coupon zeroes the goods but still adds delivery', ...
  +  expect(total(res)).toBe(deliveryCharge)
  (header comment updated; coupon-math is otherwise stale w.r.t. the region/bound refactor)

  Docs (no code): apps/backend/tests/BUGS.md #6 (fixed); docs/e2e-sanity-failed-cases.md
  FC-07/FC-08 + docs/e2e-sanity-test-results.md BL-03/BL-06/D4/D5/D10.
  No migrations run. No tests run.

[2026-10-10 11:32:49 +0530] Remove the dead `minRegularOrderValue` bound constant (resolves FC-06).
  - It was not enforced as a minimum and no longer used as the delivery threshold.
    Removed from both const-key registries, the essential-consts payload, the web-ui
    hook, the three admin/superadmin bound editors, the sqlite/postgres seeds, and the
    two tests that read it (now use freeDeliveryThreshold).
  - NOT touched: applied migration 0006 (still seeds a row) — a future migration should
    stop seeding it / delete the orphan region_bound_consts rows; user owns migrations.

  --- a/apps/backend/src/lib/const-keys.ts
  +++ b/apps/backend/src/lib/const-keys.ts
  @@ CONST_KEYS / CONST_LABELS / CONST_TYPES / CONST_VISIBILITY / BOUND_CONST_KEYS
  -  minRegularOrderValue: 'minRegularOrderValue',
  -  minRegularOrderValue: 'Minimum Regular Order Value',
  -  minRegularOrderValue: 'number',
  -  minRegularOrderValue: true,
  -  'minRegularOrderValue', 'freeDeliveryThreshold', 'deliveryCharge',
  +  'freeDeliveryThreshold', 'deliveryCharge',

  --- a/packages/db_helper_sqlite/src/lib/const-keys.ts
  +++ b/packages/db_helper_sqlite/src/lib/const-keys.ts
  @@ CONST_KEYS / CONST_LABELS / CONST_TYPES / CONST_VISIBILITY / CONST_DEFAULTS / BOUND_CONST_KEYS
  -  minRegularOrderValue: 'minRegularOrderValue',
  -  minRegularOrderValue: 'Minimum Regular Order Value',
  -  minRegularOrderValue: 'number',
  -  minRegularOrderValue: true,
  -  minRegularOrderValue: 300,
  -  'minRegularOrderValue', 'freeDeliveryThreshold', 'deliveryCharge',
  +  'freeDeliveryThreshold', 'deliveryCharge',

  --- a/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
  +++ b/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
  @@
  -  minRegularOrderValue: pickNumber(boundConsts['minRegularOrderValue'], 0),
     freeDeliveryThreshold: pickNumber(boundConsts['freeDeliveryThreshold'], 200),

  --- a/apps/web-ui/src/hooks/prominent-api-hooks.ts
  +++ b/apps/web-ui/src/hooks/prominent-api-hooks.ts
  @@
  -  minRegularOrderValue: pickNumber('minRegularOrderValue', (data as any)?.minRegularOrderValue),
     }

  --- a/apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx
  +++ a/apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx
  @@ BOUND_KEYS / CONST_LABELS / KEY_TYPES
  -  'minRegularOrderValue', 'freeDeliveryThreshold', 'deliveryCharge',
  +  'freeDeliveryThreshold', 'deliveryCharge',
  -  minRegularOrderValue: 'Minimum Regular Order Value',
  -  minRegularOrderValue: 'number',

  --- a/apps/admin-web/src/routes/dashboard.customize-app.tsx
  +++ b/apps/admin-web/src/routes/dashboard.customize-app.tsx
  @@ (same three removals as admin-ui)

  --- a/apps/superadmin-ui/src/routes/regions.tsx
  +++ b/apps/superadmin-ui/src/routes/regions.tsx
  @@ SETTING_KEYS / SETTING_LABELS
  -  'minRegularOrderValue',
  -  minRegularOrderValue: 'Minimum Regular Order Value',

  --- a/packages/db_helper_sqlite/src/db/seed.sql
  +++ b/packages/db_helper_sqlite/src/db/seed.sql
  @@
  -INSERT OR IGNORE INTO key_val_store (key, value) VALUES ('minRegularOrderValue', '300');

  --- a/packages/db_helper_postgres/src/db/seed.ts
  +++ b/packages/db_helper_postgres/src/db/seed.ts
  @@
  -    { key: CONST_KEYS.minRegularOrderValue, value: minOrderValue },

  --- a/apps/backend/tests/api/order-rules.test.ts
  +++ b/apps/backend/tests/api/order-rules.test.ts
  @@
  -  let minOrder = 0
  +  let freeDeliveryThreshold = 0
  -  minOrder = asNumber(consts.minRegularOrderValue)
  +  freeDeliveryThreshold = asNumber(consts.freeDeliveryThreshold)
  -  expect(minOrder).toBeGreaterThan(UNIT_PRICE)
  +  expect(freeDeliveryThreshold).toBeGreaterThan(UNIT_PRICE)
  -  const quantity = Math.ceil(minOrder / UNIT_PRICE) + 1
  +  const quantity = Math.ceil(freeDeliveryThreshold / UNIT_PRICE) + 1
  (comments updated)

  --- a/apps/backend/tests/api/coupon-math.test.ts
  +++ b/apps/backend/tests/api/coupon-math.test.ts
  @@
  -  let minOrderValue = 0
  +  let freeDeliveryThreshold = 0
  -  minOrderValue = asNumber(consts.minRegularOrderValue)
  +  freeDeliveryThreshold = asNumber(consts.freeDeliveryThreshold)
  (assertions/comments updated)

  Docs (no code): docs/e2e-sanity-failed-cases.md FC-06 (resolved by removal);
  docs/e2e-sanity-test-results.md BL-02/D6; apps/user-ui/tests/KNOWN-GAPS.md.
  No migrations run. No tests run.

[2026-10-10 11:52:42 +0530] FC-04 (SEC-06): enforce user-based coupon scope at redemption.
  - validateAndGetCoupon now loads the coupon's applicableUsers and rejects when the
    coupon isUserBased (and not isApplyForAll) and the ordering user is not listed.
  - SKU (FC-09) and region (FC-10) scoping deliberately NOT enforced: SKU-specific
    coupons are not created today and region-scoped coupons are not wanted; those are
    false flags for now.

  --- a/packages/db_helper_sqlite/src/user-apis/order.ts
  +++ b/packages/db_helper_sqlite/src/user-apis/order.ts
  @@
   const coupon = await db.query.coupons.findFirst({
     where: eq(coupons.id, couponId),
     with: {
       usages: { where: eq(couponUsage.userId, userId) },
  +    applicableUsers: true,
     },
   })
   if (!coupon) throw new Error('Invalid coupon')
  +
  +// User-based coupons are only spendable by their listed users (the display
  +// endpoints already hide them from everyone else).
  +if (coupon.isUserBased && !coupon.isApplyForAll) {
  +  const applicableUsers = coupon.applicableUsers ?? []
  +  if (!applicableUsers.some((au) => au.userId === userId)) {
  +    throw new Error('This coupon is not applicable to your account')
  +  }
  +}
  +
   if (coupon.isInvalidated) throw new Error('Coupon is no longer valid')

  --- a/apps/backend/tests/api/coupon-ux.test.ts
  +++ b/apps/backend/tests/api/coupon-ux.test.ts
  @@
   apiClient(user.token).user.order.placeOrder.mutate({
     selectedItems: [{ skuId, quantity, slotId }],
     addressId: user.addressId,
  +  regionId: 1,
     paymentMethod: 'cod',
  @@
  -it('pins: user B can apply a coupon issued to user A', ... expect(total).toBe(295)
  +it('rejects a user B applying a coupon issued to user A', ...
  +  expect(error.message).toMatch(/not applicable/i)
  (header comment updated)

  Docs (no code): apps/backend/tests/BUGS.md #8 (fixed); docs/e2e-sanity-failed-cases.md
  FC-04 (fixed) + FC-09/FC-10 (false flags); docs/e2e-sanity-test-results.md SEC-06/CP-04/
  CP-05/CP-11 + the matching defect row.
  No migrations run. No tests run.

[2026-10-10 12:03:04 +0530] FC-11/FC-12: stop store-delete orphaning; make tag delete work.
  - deleteStore now refuses to delete a store that still has products (plain Error,
    500) and no longer nulls product_info.store_id.
  - deleteProductTag now deletes the product_tags junction rows first (transaction),
    so the FK no longer blocks deleting a tag that has products.
  - No schema/migration changes (no FK cascade added).

  --- a/packages/db_helper_sqlite/src/admin-apis/store.ts
  +++ b/packages/db_helper_sqlite/src/admin-apis/store.ts
  @@
  -import { eq, inArray, and } from 'drizzle-orm'
  +import { eq, inArray, and, sql } from 'drizzle-orm'
  @@
   export async function deleteStore(regionId: number, id: number): Promise<{ message: string }> {
     const existing = await db.query.storeInfo.findFirst({
       where: and(eq(storeInfo.id, id), eq(storeInfo.regionId, regionId)),
       columns: { id: true },
     })
     if (!existing) {
       throw new Error('Store not found')
     }
  -
  -  return await db.transaction(async (tx) => {
  -    await tx.update(productInfo).set({ storeId: null }).where(eq(productInfo.storeId, id))
  -    const [deletedStore] = await tx.delete(storeInfo).where(eq(storeInfo.id, id)).returning()
  -    if (!deletedStore) throw new Error('Store not found')
  -    return { message: 'Store deleted successfully' }
  -  })
  +
  +  // A store cannot be deleted while products still reference it — that would
  +  // orphan them. Reassign or remove the products first.
  +  const [{ count }] = await db
  +    .select({ count: sql<number>`count(*)` })
  +    .from(productInfo)
  +    .where(eq(productInfo.storeId, id))
  +  if (Number(count) > 0) {
  +    throw new Error('Cannot delete a store that still has products. Remove or reassign them first.')
  +  }
  +
  +  await db.delete(storeInfo).where(eq(storeInfo.id, id))
  +
  +  return { message: 'Store deleted successfully' }
   }

  --- a/packages/db_helper_sqlite/src/admin-apis/product.ts
  +++ b/packages/db_helper_sqlite/src/admin-apis/product.ts
  @@
   export async function deleteProductTag(regionId: number, tagId: number): Promise<boolean> {
  -  const [deleted] = await db.delete(productTagInfo)
  -    .where(and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId)))
  -    .returning({ id: productTagInfo.id })
  -  return !!deleted
  +  return db.transaction(async (tx) => {
  +    const tag = await tx.query.productTagInfo.findFirst({
  +      where: and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId)),
  +      columns: { id: true },
  +    })
  +    if (!tag) return false
  +
  +    // Drop the product associations first; the product_tags FK blocks the tag
  +    // delete otherwise.
  +    await tx.delete(productTags).where(eq(productTags.tagId, tagId))
  +    await tx.delete(productTagInfo)
  +      .where(and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId)))
  +    return true
  +  })
   }

  --- a/apps/backend/tests/api/admin-ops.test.ts
  +++ b/apps/backend/tests/api/admin-ops.test.ts
  @@ (after "deletes a store")
  +  it('rejects deleting a store that still has products', async () => {
  +    const target = await createStoreWithSku()
  +    const error = await captureError(() =>
  +      admin.admin.store.deleteStore.mutate({ storeId: target.storeId })
  +    )
  +    expect(error.message).toMatch(/still has products/i)
  +  })

  --- a/apps/backend/tests/api/admin-tags.test.ts
  +++ b/apps/backend/tests/api/admin-tags.test.ts
  @@
  +import { createStoreWithSku } from '../helpers/fixtures'
  @@ beforeAll
  +  const store = await createStoreWithSku()
  +  skuId = store.skuId
  @@ (new test)
  +  it('deleteProductTag removes a tag that has products', async () => {
  +    const created = await admin.admin.product.createProductTag.mutate({
  +      tagName: `API Tag w/ product ${uniqueSuffix()}`,
  +      isDashboardTag: true,
  +      productIds: [skuId],
  +    })
  +    const id = (created as { tag: { id: number } }).tag.id
  +    const res = await admin.admin.product.deleteProductTag.mutate({ id })
  +    expect((res as { message?: string }).message ?? '').toMatch(/deleted/i)
  +  })

  Docs (no code): docs/e2e-sanity-failed-cases.md FC-11/FC-12 + docs/e2e-sanity-test-results.md
  PD-13/DS-02/D12/D13.
  No migrations run. No tests run.

[2026-10-10 12:35:14 +0530] FC-14 (CT-07) closed as a false flag (docs only, no source).
  - Reproduced on the simulator: cart held sku 155; toggleOutOfStock{id:155} bumped availability
    av-17 -> av-18 (published av-18 shows isOutOfStock:true); relaunch + open cart showed the line
    normally, then ~70 s later (the app's essentialConsts refetchInterval of 60 s) it correctly
    rendered "Out of Stock". The cart already flags/filters/blocks OOS; the E2E observed the
    pre-propagation window. Report's root cause was inaccurate.
  - docs/e2e-sanity-failed-cases.md FC-14 + summary row + fix-order line;
    docs/e2e-sanity-test-results.md CT-07 + D20. Stock restored; no source changed.

[2026-10-10 12:41:56 +0530] FC-15 (AU-07) + FC-16 (AU-08): fix profile update and password change.
  FC-15:
  - Context.req is the tRPC fetch adapter's Request (not HonoRequest); corrected the
    type in trpc-index.ts and switched auth.ts to ctx.req.headers.get('authorization').
  - Relaxed the optional email: the backend now treats an empty email as "no change"
    (zod no longer forces .email() on ''), and the client form only requires email in
    registration mode, not edit.
  FC-16:
  - upsertUserPassword now does an explicit select-then-update-or-insert (updates ALL
    rows for the user, repairing existing duplicates) instead of relying on Postgres
    error 23505.
  - Added a unique index on user_creds.user_id in the schema (migration handled by the
    user; existing duplicate rows must be deduped before the index can be created).

  --- a/apps/backend/src/trpc/trpc-index.ts
  +++ b/apps/backend/src/trpc/trpc-index.ts
  @@
  -  req: HonoContext['req'];
  +  req: Request;

  --- a/apps/backend/src/trpc/apis/user-apis/apis/auth.ts
  +++ b/apps/backend/src/trpc/apis/user-apis/apis/auth.ts
  @@
  -      email: z.string().email('Invalid email format').optional(),
  +      email: z.string().optional(),
  @@
  -      if (email) { ... regex ... }
  +      const cleanEmail = email?.trim() || undefined
  +      if (cleanEmail) { ... regex ... }
  @@
  -        email: email?.toLowerCase().trim(),
  +        email: cleanEmail?.toLowerCase(),
  @@
  -      const authHeader = ctx.req.header('authorization');
  +      const authHeader = ctx.req.headers.get('authorization');

  --- a/apps/user-ui/components/registration-form.tsx
  +++ a/apps/user-ui/components/registration-form.tsx
  @@
  -    // Validate email
  -    if (!data.email.trim()) { setError("email", { message: "Email is required" }); return; }
  -    if (!validateEmail(data.email)) { ... }
  +    // Email is required on registration only; optional when editing.
  +    if (!isEdit && !data.email.trim()) { setError("email", { message: "Email is required" }); return; }
  +    if (data.email.trim() && !validateEmail(data.email)) { ... }

  --- a/packages/db_helper_sqlite/src/user-apis/auth.ts
  +++ b/packages/db_helper_sqlite/src/user-apis/auth.ts
  @@
  -export async function upsertUserPassword(userId, hashedPassword) {
  -  try { await db.insert(userCreds).values({ userId, userPassword: hashedPassword }); return }
  -  catch (error) { if (error.code === '23505') { await db.update(...).where(eq(userCreds.userId, userId)); return } throw error }
  -}
  +export async function upsertUserPassword(userId, hashedPassword) {
  +  const existing = await db.select({ id: userCreds.id }).from(userCreds)
  +    .where(eq(userCreds.userId, userId)).limit(1)
  +  if (existing.length > 0) {
  +    await db.update(userCreds).set({ userPassword: hashedPassword }).where(eq(userCreds.userId, userId))
  +  } else {
  +    await db.insert(userCreds).values({ userId, userPassword: hashedPassword })
  +  }
  +}

  --- a/packages/db_helper_sqlite/src/db/schema.ts
  +++ b/packages/db_helper_sqlite/src/db/schema.ts
  @@ userCreds
  -export const userCreds = sqliteTable('user_creds', { ... })
  +export const userCreds = sqliteTable('user_creds', { ... }, (t) => ({
  +  unq_user_creds_user: uniqueIndex('unique_user_creds_user').on(t.userId),
  +}))

  --- a/apps/backend/tests/api/misc-procedures.test.ts
  +++ a/apps/backend/tests/api/misc-procedures.test.ts
  @@
  -it('pins: updateProfile crashes after writing the change', ... expect(error).toMatch(/ctx.req.header is not a function/)
  +it('updates the profile and returns the new name', ... expect(res.success).toBe(true); getSelfData reflects it
  -it('pins: updatePassword reports success but the old password still works', ...)
  +it('updatePassword: new password works and the old one fails', ...)

  Docs (no code): apps/backend/tests/BUGS.md #3/#4; docs/e2e-sanity-failed-cases.md
  FC-15/FC-16; docs/e2e-sanity-test-results.md AU-07/AU-08 + D15/D16.
  No migrations run. No tests run.

[2026-10-10 12:50:42 +0530] Added hand-written migration 0008_user_creds_unique.sql.
  - Collapses existing duplicate user_creds rows (keep MAX(id) per user) and creates
    the unique index on user_creds(user_id) matching the schema declaration.
    Required because CREATE UNIQUE INDEX fails while duplicates exist (users 379, 908, 1311).
  - Not run (user applies migrations). No journal/meta edit; SQL-only as requested.

  --- a/packages/db_helper_sqlite/drizzle/0008_user_creds_unique.sql
  +++ b/packages/db_helper_sqlite/drizzle/0008_user_creds_unique.sql
  @@
  +-- Migration: enforce one credentials row per user.
  +-- ...
  +DELETE FROM `user_creds`
  +WHERE `id` NOT IN (SELECT MAX(`id`) FROM `user_creds` GROUP BY `user_id`);
  +--> statement-breakpoint
  +CREATE UNIQUE INDEX `unique_user_creds_user` ON `user_creds` (`user_id`);

[2026-10-10 12:53:21 +0530] Added migration 0009_remove_min_regular_order_value.sql.
  - minRegularOrderValue was removed from the app earlier this session, leaving orphan
    region_bound_consts rows (4) and a legacy key_val_store row. This migration deletes
    them; it runs after 0006 (which seeds the bound rows), so fresh installs are cleaned too.
  - Not run (user applies migrations). SQL-only.

  --- a/packages/db_helper_sqlite/drizzle/0009_remove_min_regular_order_value.sql
  +++ b/packages/db_helper_sqlite/drizzle/0009_remove_min_regular_order_value.sql
  @@
  +DELETE FROM `region_bound_consts` WHERE `key` = 'minRegularOrderValue';
  +--> statement-breakpoint
  +DELETE FROM `key_val_store` WHERE `key` = 'minRegularOrderValue';

[2026-10-10 12:54:31 +0530] Merged 0008 + 0009 into one migration file (applied as a single go).
  - Removed 0008_user_creds_unique.sql and 0009_remove_min_regular_order_value.sql.
  - Added 0008_user_creds_unique_and_min_order_cleanup.sql containing both the
    user_creds dedupe + unique index and the minRegularOrderValue row cleanup.
  - Not run (user applies migrations). SQL-only.

[2026-10-10 12:58:04 +0530] FC-17 (OR-12): client-side double-submit guard (server idempotency deferred).
  - PaymentAndOrderComponent: handlePlaceOrder now early-returns while a submit is in
    flight (a synchronous useRef guard + placeOrderMutation.isPending), and the Place
    Order button is disabled while pending. Stops accidental double-taps; the server
    still has no idempotency key, so API replays/network retries are not covered.
  - Added a test asserting a second press while in flight does not re-call placeOrder.

  --- a/apps/user-ui/components/PaymentAndOrderComponent.tsx
  +++ a/apps/user-ui/components/PaymentAndOrderComponent.tsx
  @@
  -import React, { useState, useMemo } from 'react';
  +import React, { useState, useMemo, useRef } from 'react';
  @@
  +  const submittingRef = useRef(false);
  @@ onSettled
  -    setIsLoadingDialogOpen(false);
  +    submittingRef.current = false;
  +    setIsLoadingDialogOpen(false);
  @@
   const handlePlaceOrder = () => {
  +    if (submittingRef.current || placeOrderMutation.isPending) return;
  +    submittingRef.current = true;
     if (!selectedAddress) { ... }
  @@ button
  -  disabled={!selectedAddress}
  +  disabled={!selectedAddress || placeOrderMutation.isPending}
  (opacity also keyed on the same condition)

  --- a/apps/user-ui/tests/components/payment-and-order.test.tsx
  +++ a/apps/user-ui/tests/components/payment-and-order.test.tsx
  @@
  +  it('ignores a second press while the order is in flight', async () => { ... procCount === 1 })

  Docs (no code): docs/e2e-sanity-failed-cases.md FC-17 + summary row;
  docs/e2e-sanity-test-results.md OR-12 + its defect row; apps/backend/tests/BUGS.md #17.
  No migrations run. No tests run.

[2026-10-10 13:03:57 +0530] FC-19 (RG-02): make createRegionWithBounds atomic on D1.
  - Reproduced: superadmin.regions.create with two bounds at priority "1" returned the
    unique-priority error but left region 5 with zero bounds (D1 does not roll back the
    region insert with the failed bound insert).
  - Fix: validate bounds before any insert (>=1 bound, unique priorities) and add a
    compensating cleanup that removes the region + its child rows if a later insert
    fails, so a failed create never leaves a half-created region.

  --- a/packages/db_helper_sqlite/src/superadmin-apis/regions.ts
  +++ a/packages/db_helper_sqlite/src/superadmin-apis/regions.ts
  @@
   export async function createRegionWithBounds(input) {
  +  // Validate before touching the DB: D1 does not reliably roll back a
  +  // multi-statement drizzle transaction, so a bad payload must never reach the
  +  // inserts (it would leave a region with no bounds behind).
  +  if (!input.bounds || input.bounds.length === 0)
  +    throw new Error('A region must be created with at least one bound')
  +  const priorities = input.bounds.map((b) => String(b.priority))
  +  if (new Set(priorities).size !== priorities.length)
  +    throw new Error('Each bound priority must be unique within the region')
  +
     return db.transaction(async (tx) => {
       const [region] = await tx.insert(regions).values(...).returning()
  +    try {
         const inserted = await tx.insert(regionBounds).values(...).returning()
         await tx.insert(regionConsts).values(defaultRegionRows(region.id)).onConflictDoNothing()
         const boundRows = inserted.flatMap(...)
         if (boundRows.length > 0) await tx.insert(regionBoundConsts).values(boundRows).onConflictDoNothing()
         return { region: toSummary(region), bounds: inserted.map(toBoundDto) }
  +    } catch (error) {
  +      await tx.delete(regionBoundConsts).where(eq(regionBoundConsts.regionId, region.id))
  +      await tx.delete(regionConsts).where(eq(regionConsts.regionId, region.id))
  +      await tx.delete(regionBounds).where(eq(regionBounds.regionId, region.id))
  +      await tx.delete(regions).where(eq(regions.id, region.id))
  +      throw error
  +    }
     })
   }

  Docs (no code): docs/e2e-sanity-failed-cases.md FC-19 + summary row;
  docs/e2e-sanity-test-results.md RG-02 + its defect row.
  No migrations run. No tests run.

[2026-10-10 13:12:28 +0530] Moved + timestamped the E2E reports into docs/test reports/.
  - docs/e2e-sanity-failed-cases.md  -> docs/test reports/e2e-sanity-failed-cases-2026-10-10-1310.md
  - docs/e2e-sanity-test-results.md  -> docs/test reports/e2e-sanity-test-results-2026-10-10-1310.md
  - Updated cross-references in both files and in docs/maestro-mcp-agent-guidelines.md.
    (Historical change-log entries above keep the old paths.) No application source changed.

[2026-10-10 13:42:06 +0530] Move `is_offer` from product_skus -> product_market_stats (the
  availability table). isOffer is dropped from products.json and now travels in
  availability.json only; the apps read it from the availability merge. Combo-item
  isOffer and the admin SKU payload stay (different payloads), still sourced from
  product_market_stats. New hand-written migration 0009 (NOT run).

  --- a/packages/db_helper_sqlite/src/db/schema.ts
  +++ b/packages/db_helper_sqlite/src/db/schema.ts
  @@ productSkus
  -  isOffer: integer('is_offer', { mode: 'boolean' }).notNull().default(false),
     isComboOnly: ...
  @@ productMarketStats
  +  isOffer: integer('is_offer', { mode: 'boolean' }).notNull().default(false),
     isSuspended: ...

  --- a/packages/shared/types/user.ts
  +++ b/packages/shared/types/user.ts
  @@ ProductDetailCore
  -  isOffer?: boolean;
     isComboOnly?: boolean;
  @@ ProductPriceFlags
  +  isOffer: boolean;

  --- a/packages/db_helper_sqlite/src/stores/store-helpers.ts
  +++ b/packages/db_helper_sqlite/src/stores/store-helpers.ts
  @@ ProductBasicData
  -  isOffer: boolean
  @@ getAllProductsForCache
  -      isOffer: sku.isOffer ?? false,
  @@ getAllProductCombosForCache
  -      isOffer: ci.sku?.isOffer ?? false,
  +      isOffer: ci.sku?.marketStats?.isOffer ?? false,
  @@ getAvailabilityForCache
  +      isOffer: stat.isOffer,

  --- a/packages/db_helper_sqlite/src/user-apis/product.ts
  +++ b/packages/db_helper_sqlite/src/user-apis/product.ts
  -      isOffer: ci.sku?.isOffer ?? false,
  +      isOffer: ci.sku?.marketStats?.isOffer ?? false,

  --- a/packages/db_helper_sqlite/src/admin-apis/product.ts
  +++ b/packages/db_helper_sqlite/src/admin-apis/product.ts
  @@ mapSku
  -  isOffer: sku.isOffer,
  +  isOffer: marketStats?.isOffer ?? false,
  @@ createProduct / updateProduct
  -  isOffer in the productSkus insert/update
  +  isOffer moved into the productMarketStats insert/marketStatsValues

  --- a/apps/backend/src/trpc/apis/common-apis/common.ts
  +++ b/apps/backend/src/trpc/apis/common-apis/common.ts
  -      isOffer: product.isOffer,   (products.json no longer carries it)

  --- a/apps/backend/src/stores/product-store.ts
  +++ b/apps/backend/src/stores/product-store.ts
  -  isOffer: boolean   (interface) and -  isOffer: product.isOffer, (mapping)

  --- a/apps/user-ui/src/hooks/prominent-api-hooks.ts
  +++ b/apps/user-ui/src/hooks/prominent-api-hooks.ts
  --- a/apps/web-ui/src/hooks/prominent-api-hooks.ts
  +++ b/apps/web-ui/src/hooks/prominent-api-hooks.ts
  @@ merge
  +        isOffer: availability?.isOffer ?? false,

  New file: packages/db_helper_sqlite/drizzle/0009_move_is_offer_to_market_stats.sql
    ALTER TABLE product_market_stats ADD COLUMN is_offer ...; backfill from product_skus;
    ALTER TABLE product_skus DROP COLUMN is_offer.
  No migrations run. No tests run.

  Type fix: both apps' useAllProducts merged-data cast changed from
  `ProductsResponse & { products: MergedProduct[] }` to
  `Omit<ProductsResponse, 'products'> & { products: MergedProduct[] }` — with isOffer
  gone from the base product, the array intersection otherwise resolved .products to
  the base element type (user-ui order-again filter failed typecheck).
  Verified: migration run on a COPY of the local D1 (SQLite 3.42) — column moved,
  backfill of a synthetic offer sku + the orphan-offer safety net both correct.
  tsc --noEmit: backend, admin-ui, user-ui PASS; web-ui has 12 pre-existing unrelated
  errors (cacheVersion/freeDeliveryThreshold), none isOffer-related. No live probe
  (dev DB not migrated).

[2026-10-10 14:09:38 +0530] Docs only (no code): added the global-stores-and-products
  implementation plans under docs/impl-plans/ — README + phase-1 (per-region
  product_market_stats), phase-2 (global stores/products backend), phase-3 (admin UI),
  phase-4 (superadmin UI). No source changed. No migrations run. No tests run.

[2026-10-10 14:13:30 +0530] Docs only (no code): resolved the Phase-2 new-region seeding
  decision — on region create, replicate the least-id region's global data (its
  per-region product_market_stats rows for global SKUs) into the new region. Updated
  docs/impl-plans/README.md, phase-2 §3, phase-4 §7. No source changed.

[2026-10-10 14:16:37 +0530] Docs only (no code): since migration 0006 (merged regionalization,
  recreates store_info/product_info/product_market_stats/...) is not applied yet, revised the
  plans to fold all schema changes into 0006's __new_* rebuilds instead of separate 0010/0011
  recreate migrations. Updated docs/impl-plans/README.md (migration strategy), phase-1 §4/§8,
  phase-2 §3/§10/§11. Noted 0009 (is_offer move) as a candidate to fold into 0006 too (open
  question). No source changed. No migrations run.

[2026-10-10 14:22:19 +0530] Fold the 0009 (is_offer move) into the unapplied 0006 migration;
  delete 0009_move_is_offer_to_market_stats.sql. Phase 1/2 schema folds (region_id /
  is_suspended_in_region / is_global) intentionally NOT applied yet — they stay documented as
  build-time edits to 0006 because region_id NOT NULL would break current market-stats writes.

  --- a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
  +++ b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
  @@ __new_product_skus (is_offer removed)
  -   `is_offer` integer DEFAULT false NOT NULL,
  - INSERT INTO `__new_product_skus` (...,`is_offer`,...) SELECT ...,`is_offer`,...
  + INSERT INTO `__new_product_skus` (...,...) SELECT ...,...
  @@ __new_product_market_stats (is_offer added + backfilled from old product_skus)
  +   `is_offer` integer DEFAULT false NOT NULL,
  @@ copy
  - INSERT ... SELECT id,sku_id,market_price,our_price,is_flash_available,flash_price,is_out_of_stock,is_suspended FROM product_market_stats;
  + INSERT ... (...,`is_offer`) SELECT ms.id,ms.sku_id,ms.market_price,ms.our_price,ms.is_flash_available,ms.flash_price,ms.is_out_of_stock,ms.is_suspended,COALESCE(ps.is_offer,false)
  +   FROM product_market_stats ms JOIN product_skus ps ON ps.id = ms.sku_id;   (JOIN also prunes the 3 orphan rows)
  (index `product_market_stats_sku_id_unique` left unchanged)

  Deleted: packages/db_helper_sqlite/drizzle/0009_move_is_offer_to_market_stats.sql
  Docs: docs/impl-plans/README.md + phase-1 updated. No migrations run. No tests run.

[2026-10-10 14:25:07 +0530] Phase 1 — per-region product_market_stats (region-scoped market data).
  Adds region_id (NOT NULL) + is_suspended_in_region to product_market_stats, moves the unique
  key to (sku_id, region_id), folds the DDL into the pending 0006 rebuild, changes the
  productSkus.marketStats relation one->many, and region-scopes every read/write.

  --- a/packages/db_helper_sqlite/src/db/schema.ts
  +++ b/packages/db_helper_sqlite/src/db/schema.ts
  @@ productMarketStats
  -  skuId: integer('sku_id').notNull().references(() => productSkus.id).unique(),
  +  skuId: integer('sku_id').notNull().references(() => productSkus.id),
  +  regionId: integer('region_id').notNull().references(() => regions.id),
     ... isSuspended ...
  +  isSuspendedInRegion: integer('is_suspended_in_region', { mode: 'boolean' }).notNull().default(false),
     isOffer: ...
  -})
  +}, (t) => ({ unq_sku_region: uniqueIndex('product_market_stats_sku_region').on(t.skuId, t.regionId) }))
  @@ relations
  -  marketStats: one(productMarketStats),
  +  marketStats: many(productMarketStats),
  @@ productMarketStatsRelations
  +  region: one(regions, { fields: [productMarketStats.regionId], references: [regions.id] }),

  --- a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
  +++ a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
  @@ __new_product_market_stats
  +  `region_id` integer NOT NULL,
  +  `is_suspended_in_region` integer DEFAULT false NOT NULL,
  +  FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ...
  @@ copy
  + region_id=(SELECT id FROM regions WHERE name='Mahabubnagar'), is_suspended_in_region=false
  @@ index
  - CREATE UNIQUE INDEX `product_market_stats_sku_id_unique` ON `product_market_stats` (`sku_id`);
  + CREATE UNIQUE INDEX `product_market_stats_sku_region` ON `product_market_stats` (`sku_id`,`region_id`);

  New file: packages/db_helper_sqlite/src/lib/market-stats.ts  (marketStatsForRegion helper)

  Region-scoped reads/writes (pick the region row; check isSuspended + isSuspendedInRegion):
  - stores/store-helpers.ts: getAllProductsForCache, getAvailabilityForCache (region filter),
    getAllProductCombosForCache, suspended-sku set, getAllSlotsWithProductsForCache.
  - user-apis/product.ts: getProductDetailById, combo items, getProductById, getAllProductsWithUnits
    (+ regionId param), getSuspendedSkuIds (region filter), getAllSkusSummary.
  - user-apis/order.ts: getProductById (derive region from product).
  - user-apis/stores.ts: getStoreSummaries, getStoreDetail.
  - user-apis/slots.ts: getProductAvailability (region filter).
  - admin-apis/product.ts: mapSku callers, getAllProducts, getProductById, createProduct,
    updateProduct, updateProductPrices, toggleProductOutOfStock, tags/groups mapSku callers.
  - admin-apis/order.ts: latest-price lookups region-scoped.
  - apps/backend/.../user-apis/apis/order.ts: unavailability check adds isSuspendedInRegion.

  No migrations run. No tests run.

[2026-10-10 14:32:30 +0530] Revise Phase 1 suspension model: global `is_suspended` moves to
  product_skus; product_market_stats keeps only the per-region `is_suspended_in_region`
  (drop its `is_suspended`). Phase-1 admin write still targets the global flag (superadmin/
  region split stays Phase 2).

  --- a/packages/db_helper_sqlite/src/db/schema.ts
  +++ a/packages/db_helper_sqlite/src/db/schema.ts
  @@ productSkus
  +  isSuspended: integer('is_suspended', { mode: 'boolean' }).notNull().default(false),
  @@ productMarketStats
  -  isSuspended: integer('is_suspended', { mode: 'boolean' }).notNull().default(false),
     isSuspendedInRegion: ...   (kept)

  --- a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
  +++ a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
  @@ __new_product_skus
  +  `is_suspended` integer DEFAULT false NOT NULL,
  + copy: is_suspended = COALESCE((SELECT is_suspended FROM product_market_stats WHERE sku_id=product_skus.id), false)
  @@ __new_product_market_stats
  -  `is_suspended` integer DEFAULT false NOT NULL,   (and dropped from its copy)

  --- a/packages/db_helper_sqlite/src/lib/market-stats.ts
  +++ ...
  - isMarketStatsSuspended(stats)
  + isSkuSuspended(globalSuspended, stats)  // global (sku) OR per-region

  Reads/writes updated so a SKU is suspended when product_skus.is_suspended (global) OR
  product_market_stats.is_suspended_in_region (region):
  - store-helpers.ts (products cache, availability cache, combos suspended-set, slots)
  - user-apis/product.ts (detail, getAllProductsWithUnits, getSuspendedSkuIds, getAllSkusSummary)
  - user-apis/stores.ts
  - admin-apis/product.ts: mapSku reads sku.isSuspended; createProduct/updateProduct write the
    global flag (productSkus) and drop it from market stats; combo-suspend check uses both.
  - apps/backend/.../user-apis/apis/order.ts: product.isSuspended || marketStats.isSuspendedInRegion

  No migrations run. No tests run.

[2026-10-10 14:37:08 +0530] Phase 2 (global stores/products, backend) + remove the store->admin
  owner attachment.

  OWNER REMOVAL:
  - schema.ts: storeInfo drops `owner` (and storeInfoRelations.owner).
  - 0006: `__new_store_info` drops `owner` (column, FK, copy).
  - shared: Store.owner removed; CreateStoreInput/UpdateStoreInput.owner removed.
  - db_helper_sqlite admin-apis/store.ts: drop assertOwnerInRegion + owner from reads/mapping.
  - admin-apis/product.ts mapStore: drop owner. staff-user.ts deleteStaffUser: drop the
    store-owner block.
  - backend admin store.ts: drop owner from zod/create/update.
  - admin-ui + admin-web StoreForm/screens + tests: drop the owner picker.

  PHASE 2 (global stores/products):
  - schema.ts: storeInfo gains `isGlobal` (region_id/owner nullable); productInfo.regionId
    nullable (already in schema).
  - 0006: `__new_store_info` region_id nullable + `is_global`; `__new_product_info` region_id
    nullable.
  - NEW packages/db_helper_sqlite/src/superadmin-apis/{global-stores,global-products}.ts
    (CRUD + per-region market-stats seeding + isGlobalStore).
  - NEW superadmin routers globalStores/globalProducts; registered in superadmin-trpc-index.
  - regions.ts createRegionWithBounds: seed new region's global-SKU market rows from the
    least-id region (compensating cleanup).
  - Visibility/guards: admin product/store reads include global; assert*/resolve* accept
    global; store-helpers/user stores include global; getAllSkusSummary includes global.
  - Write scoping: admin updateProduct on a global product applies only market-stats fields.
  - Region resolution: getOrderProductById + getProductDetailById accept a regionId.
  - Cache regen: global structural writes regen all regions.

  No migrations run. No tests run.

[2026-10-10 14:44:58 +0530] Phase 2 follow-ups (region resolution + edit paths).
  - user-apis/order.ts getProductById(skuId, regionId?) + placeOrderUtil passes the order
    region (both call sites) -> global SKUs price from the order region's row.
  - user-apis/product.ts getProductDetailById(skuId, regionId?) and the public
    user.product.getProductDetails input now accepts an optional regionId; region =
    sku product region ?? client region.
  - admin-apis/product.ts updateProduct(regionId | null, id, input): global product edited by
    a regional admin -> updateProductMarketDataForRegion (market fields only, their region);
    regionId null (superadmin structural edit) leaves each region's market data untouched and
    seeds new SKUs to every region. createProduct|updateProduct return picks
    regionId ?? targetRegionIds[0].
  - superadmin-apis/global-products.ts updateGlobalProduct (structural) + globalProducts.update
    router procedure; exported from the package index.
  No migrations run. No tests run.

[2026-10-10 14:50:23 +0530] Phase 3 — admin UI for global products/stores (admin-ui + admin-web).
  - shared: AdminProduct gains isGlobal; admin-apis/product.ts mapProduct sets it
    (product.regionId == null).
  - admin-ui: NEW src/components/GlobalProductForm.tsx (read-only structure + editable
    market fields for the admin's region); products/edit.tsx branches to it when
    product.isGlobal; products/index.tsx shows a GLOBAL badge; stores/edit.tsx renders a
    read-only view for global stores.
  - admin-web: NEW src/components/GlobalProductForm.tsx; dashboard.products.edit.tsx
    branches to it; dashboard.products.tsx shows a GLOBAL badge; dashboard.stores.edit.tsx
    renders a read-only view for global stores.
  tsc --noEmit: admin-ui, admin-web, backend PASS. No migrations run. No tests run.

[2026-10-10 14:51:58 +0530] Phase 3 polish.
  - Products list: added a "Global" filter chip (All / In Stock / Out of Stock / Global) in
    admin-ui products/index.tsx and admin-web dashboard.products.tsx.
  - Stores list: global store rows no longer show delete and are not navigable to edit
    (admin-ui stores/index.tsx, admin-web dashboard.stores.tsx): the edit screen stays
    read-only and delete is superadmin-only.
  - user-ui ProductDetail passes the active regionId to user.product.getProductDetails so
    global SKUs resolve price/availability for the user's region.
  tsc --noEmit: backend, admin-ui, admin-web, user-ui PASS. No migrations run. No tests run.

[2026-10-10 14:54:10 +0530] Phase 4 — superadmin UI for global stores/products (apps/superadmin-ui).
  - NEW src/routes/global-stores.tsx: list + create/edit/delete global stores
    (superadmin.globalStores.*), GLOBAL badge, image URL field.
  - NEW src/routes/global-products.tsx: list + create/delete global products
    (superadmin.globalProducts.*) with a global-store select and per-SKU price/stock/
    quantity-feature; deleting confirms; shows per-SKU region-row count.
  - AppShell NAV + dashboard cards gain Global Stores / Global Products (Store, Package icons).
  - routeTree.gen.ts updated with /global-stores + /global-products
    (TanStack Router regenerated it cleanly; no duplicates).
  tsc --noEmit: superadmin-ui PASS. No migrations run. No tests run.

[2026-10-10 14:55:15 +0530] Phase 4 — superadmin global-product EDIT UI (full parity).
  - superadmin-apis/global-products.ts: list/get payload now includes sku comboItems.
  - apps/superadmin-ui/src/routes/global-products.tsx: shared GlobalProductForm now
    create + edit; edit prefills name/descriptions/store/type and every SKU (name, price,
    marketPrice, features add/remove, out-of-stock, offer, combo-only, deleted, global
    suspended) and calls superadmin.globalProducts.update; list has an Edit action + cancel.
  tsc --noEmit: superadmin-ui, backend PASS. No migrations run. No tests run.

[2026-10-10 14:57:27 +0530] Superadmin UI — image upload for global products.
  - backend: trpc-index.ts adds authenticatedProcedure (user | staff | superadmin);
    common.generateUploadUrls now uses it so superadmins can request presigned URLs.
  - superadmin global-products router (create/update) stores sku.images as-is (keys) instead
    of running extractKeyFromPresignedUrl (the UI uploads and sends keys).
  - apps/superadmin-ui: NEW src/hooks/useUploadToObjectStorage.ts (presigned PUT helper);
    global-products.tsx adds per-SKU image picking (existing keys + new uploads with previews +
    remove) and uploads on submit with contextString 'product_info'.
  tsc --noEmit: superadmin-ui, backend PASS. No migrations run. No tests run.

[2026-10-10 15:01:22 +0530] Superadmin: list all products (all regions) + elevate a regional product
  to global (attach to a global store).

  - schema.ts: productInfoRelations gains `region` (one regions via productInfo.regionId).
  - NEW packages/db_helper_sqlite/src/superadmin-apis/products.ts:
      listAllProducts(regionId?) — global + regional products with store/region/skus.
      elevateProductToGlobal(productId, globalStoreId) — set region_id NULL + store to the
        global store, seed each other region's market-stats row from the source region
        (copy price/stock/offer/flash, is_suspended_in_region=false), compensating revert.
  - index.ts: export listAllProducts, elevateProductToGlobal.
  - NEW apps/backend/.../superadmin-apis/apis/products.ts router (list, elevate) registered in
    superadmin-trpc-index.ts; elevate regenerates ALL regions.
  - apps/superadmin-ui/src/routes/global-products.tsx: "All Products" / "Global Products" tabs;
    All tab lists every product (region + store + GLOBAL/REGIONAL badge) with an Elevate action
    (pick global store + confirm).
  No migrations run. No tests run.

[2026-10-10 16:16:11 +0530] Enable Maestro MCP server for pi in this project.

  Planned diffs:

  .pi/mcp.json (NEW)
    + {
    +   "mcpServers": {
    +     "maestro": {
    +       "command": "maestro",
    +       "args": ["mcp"],
    +       "description": "Maestro mobile/web UI automation: list devices, drive and inspect
    +         the screen, run YAML flows locally or on Maestro Cloud."
    +     }
    +   }
    + }
    (pi equivalent of the opencode.jsonc "maestro" local MCP entry:
     opencode `"type": "local", "command": ["maestro", "mcp"]`
     -> pi stdio `command` + `args`. Project-scoped, so it needs project trust.)

  No source files touched. No migrations run. No tests run.
