freshyo/docs/regions-proposal.md
2026-10-07 13:36:48 +05:30

480 lines
35 KiB
Markdown

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