# 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 no `staff_users` row). - **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_stats` row **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` 1. **`CREATE TABLE __new_store_info`**: - `owner` → drop `NOT NULL` (global stores have no staff owner). - `region_id` → drop `NOT NULL` (global stores are region-less). - add `is_global integer DEFAULT false NOT NULL`: ```sql `owner` integer, `region_id` integer, `is_global` integer DEFAULT false NOT NULL, ``` 2. **Its copy `INSERT INTO __new_store_info (…) SELECT …`**: append `is_global` with value `false`. 3. **`CREATE TABLE __new_product_info`**: `region_id` → drop `NOT NULL` (global products are region-less). The copy `SELECT` is unchanged — pre-existing rows still get the Mahabubnagar region id via the existing `(SELECT id FROM regions WHERE name = 'Mahabubnagar')` subquery. 4. 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**: 1. `srcRegion = MIN(regions.id)` (the newly created region has the greatest id, so it is never the source). 2. For every **global** SKU, copy the source region's `product_market_stats` row (`region_id = srcRegion`) into a new row with `region_id = `. 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 from `createRegionWithBounds`. - `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`: ```ts export const superadminRouter = router({ auth, regions, staff, const, globalStores: superadminGlobalStoresRouter, globalProducts: superadminGlobalProductsRouter, }) ``` - `globalStores.list/get/create/update/delete` (all `superadminProcedure`). - `globalProducts.list/get/create/update/delete` (all `superadminProcedure`). - 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.ts` - `getAllProducts(regionId)`: include `product.region_id = regionId OR `. - `getProductById(regionId, id)`: allow global. - `getAllSkusSummary(regionId)` (`user-apis/product.ts`): include global SKUs (admin pickers). - `admin-apis/store.ts` - `getAllStores(regionId)`: `region_id = regionId OR is_global = 1`. - `getStoreById(regionId, id)`: allow global. - `stores/store-helpers.ts` - `getAllProductsForCache(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.ts` `getStoreSummaries`/`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 in `updateProduct` (branch on `product.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_suspended` is 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`) → add `regionId`; `placeOrderUtil` (`apps/backend/src/trpc/apis/user-apis/apis/order.ts`) passes the order region. Verify the `isSuspended || isSuspendedInRegion` check (~132) uses the region row. - `getProductDetails` / `getProductDetailById` (`apps/backend/src/trpc/apis/user-apis/apis/product.ts` + `user-apis/product.ts`): add an optional `regionId`; the app already knows its region (`useRegion`). Regional products fall back to the product's own region. - `admin-apis/order.ts` price 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 1. `bunx tsc --noEmit` (backend + apps). 2. Edited `0006` validated on a **fresh** DB copy (apply from `0000`): `store_info` accepts NULL region/owner and has `is_global`; `product_info` accepts NULL region; existing rows intact; indexes present. 3. 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 `getProducts` and can change its price → **only** region 1's `availability.json`/`price` changes; 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_region` removes 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-apply `0000`…). - **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).