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