9.7 KiB
Phase 2 — Global stores & products (backend)
Status: not started. Depends on: Phase 1 verified. Blocks: Phases 3–4.
1. Goal
Introduce stores and products that are shared across all regions, created and owned by
superadmins, visible to every regional admin, with per-region market data on top of
Phase 1's product_market_stats(region_id).
2. Model
- Global store:
store_info.is_global = 1,store_info.region_id = NULL,store_info.owner = NULL(a superadmin has nostaff_usersrow). - Global product:
product_info.region_id = NULL,product_info.store_id→ a global store. A product is global iff its store is global. - Market data: a global SKU has one
product_market_statsrow per region (created in Phase 1's schema). Regional SKUs keep exactly one row (their region). - Suspension:
product_skus.is_suspended = global(superadmin only) — kills the SKU in every region.product_market_stats.is_suspended_in_region = per region(that region's admin) — kills it only there.
3. Schema changes go into 0006 (no new migration)
0006_regions_and_superadmins.sql is not applied yet and already rebuilds store_info and
product_info through __new_* tables (with owner/region_id NOT NULL). Fold the global
changes into those rebuilds instead of a standalone 0011 recreate — 0006 already rebuilds
the entire connected FK subgraph in dependency order, so no FK-deferral juggling is needed.
Edits to 0006_regions_and_superadmins.sql
CREATE TABLE __new_store_info:owner→ dropNOT NULL(global stores have no staff owner).region_id→ dropNOT NULL(global stores are region-less).- add
is_global integer DEFAULT false NOT NULL:
`owner` integer, `region_id` integer, `is_global` integer DEFAULT false NOT NULL,- Its copy
INSERT INTO __new_store_info (…) SELECT …: appendis_globalwith valuefalse. CREATE TABLE __new_product_info:region_id→ dropNOT NULL(global products are region-less). The copySELECTis unchanged — pre-existing rows still get the Mahabubnagar region id via the existing(SELECT id FROM regions WHERE name = 'Mahabubnagar')subquery.- Indexes (
idx_store_info_region,idx_product_info_region) are unchanged — a NULL region is simply not matched by the region index.
End state: store_info(owner NULL, region_id NULL, is_global), product_info(region_id NULL) —
exactly what schema.ts declares.
Seeding global products per region
On global product create (superadmin), for every SKU insert one product_market_stats row
per region using the superadmin's entered values.
Seeding a new region (decided). When a new region is created, seed it by replicating the least-id region's global data:
srcRegion = MIN(regions.id)(the newly created region has the greatest id, so it is never the source).- For every global SKU, copy the source region's
product_market_statsrow (region_id = srcRegion) into a new row withregion_id = <newRegion>.
Implement inside createRegionWithBounds
(packages/db_helper_sqlite/src/superadmin-apis/regions.ts), alongside the region + bounds
inserts, and honour the D1 compensating-cleanup pattern from FC-19 (a failure must not leave a
half-seeded region). Global stores need no replication — they are region-less
(region_id NULL) and already visible in every region.
4. Data helpers
New packages/db_helper_sqlite/src/superadmin-apis/global-stores.ts and global-products.ts:
listGlobalStores(),getGlobalStore(id),createGlobalStore(input),updateGlobalStore(id, input),deleteGlobalStore(id).listGlobalProducts(),getGlobalProduct(id),createGlobalProduct(input),updateGlobalProduct(id, input),deleteGlobalProduct(id).seedGlobalProductMarketStats(skuIds | productId, regions, initialValues).seedRegionMarketStatsForGlobalSkus(regionId), called fromcreateRegionWithBounds.isGlobalStore(storeId)helper.
Export them from packages/db_helper_sqlite/index.ts and add to the explicit export list
in apps/backend/src/sqliteImporter.ts (dbService.ts re-exports it).
5. tRPC routers
New apps/backend/src/trpc/apis/superadmin-apis/apis/global-stores.ts and global-products.ts;
register in superadmin-trpc-index.ts:
export const superadminRouter = router({
auth, regions, staff, const,
globalStores: superadminGlobalStoresRouter,
globalProducts: superadminGlobalProductsRouter,
})
globalStores.list/get/create/update/delete(allsuperadminProcedure).globalProducts.list/get/create/update/delete(allsuperadminProcedure).- Global structural writes → regenerate all regions' caches
await scheduleStoreInitialization()(no region = every region).
6. Visibility & guards (make global valid in every region)
Reads
admin-apis/product.tsgetAllProducts(regionId): includeproduct.region_id = regionId OR <store is global>.getProductById(regionId, id): allow global.getAllSkusSummary(regionId)(user-apis/product.ts): include global SKUs (admin pickers).
admin-apis/store.tsgetAllStores(regionId):region_id = regionId OR is_global = 1.getStoreById(regionId, id): allow global.
stores/store-helpers.tsgetAllProductsForCache(regionId): include global SKUs; use the region's market-stats row.getAvailabilityForCache(regionId): include global SKUs' region rows.getAllStoresForCache(regionId): include global stores.
user-apis/stores.tsgetStoreSummaries/getStoreDetail: include global stores.
Guards — accept global, still reject other regions
assertStoreInRegion,assertStoreIdsInRegion,assertSkuIdsInRegion/resolveSkuRegions(admin-apis/product.ts).resolveInRegionProductIds(admin-apis/store.ts).- Slot/banner/tag/group/coupon resolvers that validate SKU/store regions
(
admin-apis/{slots,banner}.ts,replaceTagProducts, coupon create/update). Assumption: a global SKU/store is valid in every region. deleteStore: a global store may only be deleted by a superadmin and only when no products reference it.
7. Write scoping
- Admin editing a global product: accept only market-stats fields
(
price,marketPrice,flashPrice,isFlashAvailable,isOutOfStock,isSuspendedInRegion,isOffer) and apply them to the caller region's row. Reject/ignore structural fields (name, descriptions, images, incrementStep, SKUs/features, combos, store, productType). Implement inupdateProduct(branch onproduct.region_id == null/ global store). - Admin editing a regional product: unchanged (full edit).
- Admin cannot create/update/delete global stores, nor create/delete global products.
updateProductPrices/toggleProductOutOfStock: already region-scoped (Phase 1) — they work for global SKUs too.- Suspension split: admin product update writes
is_suspended_in_region;is_suspendedis writable only via the superadmin global-product path. checkProductExistsByName: decide scoping — recommend global names globally unique, regional names unique within their region.
8. Region resolution for global SKUs (user-facing)
Once a SKU can be global, functions that resolved a region from the product row must receive one explicitly:
getOrderProductById(skuId)(user-apis/order.ts) → addregionId;placeOrderUtil(apps/backend/src/trpc/apis/user-apis/apis/order.ts) passes the order region. Verify theisSuspended || isSuspendedInRegioncheck (~132) uses the region row.getProductDetails/getProductDetailById(apps/backend/src/trpc/apis/user-apis/apis/product.tsuser-apis/product.ts): add an optionalregionId; the app already knows its region (useRegion). Regional products fall back to the product's own region.
admin-apis/order.tsprice lookups: scope to the order's region row.
9. Cache regeneration
| Change | Regen |
|---|---|
| Superadmin creates/edits/deletes a global store or global product (structure) | all regions — scheduleStoreInitialization() |
| Admin edits market data for a global product | that region — createAvailabilityCacheFile(regionId) (+ scheduleStoreInitialization(regionId) if needed) |
| Regional product/store change | that region (unchanged) |
| New region created | seed global SKU rows, then regen that region |
10. Verification
bunx tsc --noEmit(backend + apps).- Edited
0006validated on a fresh DB copy (apply from0000):store_infoaccepts NULL region/owner and hasis_global;product_infoaccepts NULL region; existing rows intact; indexes present. - Runtime (after the user applies migrations):
- Superadmin creates a global store + global product → a market-stats row exists for every region.
- A region-1 admin sees the global product in
getProductsand can change its price → only region 1'savailability.json/pricechanges; region 2 unchanged. - A region-1 admin cannot edit the global product's name/SKUs, nor create/edit/delete the global store.
is_suspended(superadmin) removes it everywhere;is_suspended_in_regionremoves it in one region only.- Add a global SKU to a region-1 slot → allowed; order for it prices from region 1's row.
11. Risks
- Editing the pending
0006: since it is unapplied, edits are safe, but the local dev D1 already has its effects — validation requires a fresh DB (reset + re-apply0000…). - Global SKU region resolution in order/detail paths — wrong region = wrong price.
- Guard relaxation must not accidentally allow another region's private rows.
12. Out of scope
Admin UI and superadmin UI (Phases 3–4).