[2026-10-03 12:12:39] Regions feature (superadmin) - schema + migration + shared types + db helper + tRPC + UI. Files: - packages/db_helper_sqlite/src/db/schema.ts: add `regions` (id, name, description, added_at) and `region_bounds` (id, region_id FK->regions.id, geojson text, added_at) tables + relations. geojson stored as raw text (pasted string). - packages/db_helper_sqlite/drizzle/0006_regions.sql: CREATE TABLE IF NOT EXISTS for both tables + journal idx 6. - packages/shared/types/region.types.ts (+index re-export): Region/RegionBound/Create/Update types. - packages/db_helper_sqlite/src/admin-apis/region.ts: getRegions/getRegionById/createRegion/updateRegion/deleteRegion/addRegionBound/deleteRegionBound. - packages/db_helper_sqlite/index.ts + apps/backend/src/sqliteImporter.ts: export region helpers. - apps/backend/src/trpc/apis/admin-apis/apis/region.ts: regionRouter (protectedProcedure); registered as admin.region in admin-trpc-index.ts. - apps/superadmin-ui: AppShell NAV + dashboard card + routes/regions.tsx, routes/regions.new.tsx, routes/regions.$id.edit.tsx. [2026-10-03 12:28:37] Fix: /regions/new and /regions/$id/edit were blank (rendered parent list). TanStack flat-file routing nests regions.new.tsx and regions.$id.edit.tsx under regions.tsx. regions.tsx now acts as a layout: renders the list only when pathname === '/regions', otherwise . Removed duplicate ProtectedRoute/AppShell wrappers from the two child routes (parent supplies them). Renamed list component to RegionsList. [2026-10-03 18:26:53] Region scoping - Phase 1: schema, migration, shared types. Schema (packages/db_helper_sqlite/src/db/schema.ts): - add region_id (NOT NULL, FK regions.id) to staff_users, addresses, vendor_snippets, store_info, product_tag_info, product_group_info, product_market_stats, product_info, delivery_slot_info, home_banners. - product_info: add available_in_all_regions (bool, default false); REMOVE store_id. - product_market_stats: add store_id (nullable FK store_info.id); sku_id unique -> composite unique (sku_id, region_id). - relations: region back-refs; productSkus.marketStats one->many; productMarketStats.store; storeInfo.products re-sourced from productMarketStats. Migration packages/db_helper_sqlite/drizzle/0007_region_scoping.sql + journal idx 7. Shared types: regionId + availableInAllRegions; storeId moved to availability shape. [2026-10-03 18:33:02] Region scoping - Phase 2: auth context + admin/superadmin procedures. - trpc-index.ts: Context.staffUser gains regionId/staffRoleId/staffRoleName; add adminProcedure (staff + region) and superAdminProcedure (role super_admin). - app.ts: populate staffUser.regionId + role name on each request. - db staff-user.ts: getStaffRoleById helper (+barrels); createStaffUser(regionId); getAllStaff selects regionId. - staff-user router: login returns regionId/roleName; getStaff returns regionId; createStaffUser is superAdminProcedure, takes optional regionId (defaults to ctx). [2026-10-03 18:37:36] Region scoping - Phase 3: make admin store + vendor-snippet helpers region-aware. packages/db_helper_sqlite/src/admin-apis/store.ts - import: drop productInfo, add productMarketStats; add `and` from drizzle-orm; import DEFAULT_REGION_ID from @packages/shared. - getAllStores(regionId?): add optional regionId; findMany where regionId !== undefined ? eq(storeInfo.regionId, regionId) : undefined. - createStore(input & { regionId? }, products?): insert storeInfo.regionId = input.regionId ?? DEFAULT_REGION_ID; resolve SKU ids -> product ids -> all their SKUs; set productMarketStats.storeId = newStore.id where skuId in chunk AND regionId = regionId (runBatched). Return object gains regionId. - updateStore(id, input & { regionId? }, products?): destructure regionId out of input; include regionId in .set() only when input.regionId !== undefined; clear productMarketStats.storeId where storeId = id AND regionId = updatedStore.regionId; then re-target productMarketStats.storeId for the resolved SKUs in updatedStore.regionId. Return object gains regionId. - deleteStore(id): clear productMarketStats.storeId where storeId = id (product_info.store_id removed). getStoreById unchanged (row already has regionId). packages/db_helper_sqlite/src/admin-apis/vendor-snippets.ts - import DEFAULT_REGION_ID (value) from @packages/shared. - mapVendorSnippet: include regionId: snippet.regionId. - getAllVendorSnippets(regionId?): add optional regionId; findMany where regionId !== undefined ? eq(vendorSnippets.regionId, regionId) : undefined. - createVendorSnippet(input): input gains regionId?: number; insert regionId: input.regionId ?? DEFAULT_REGION_ID. - Other snippet fns unchanged; regionId flows through mapper. - mapDeliverySlot: include regionId: slot.regionId (AdminDeliverySlot now requires regionId). [2026-10-03 18:41:00] Region scoping - Phase 3-5: addresses + user regions endpoint, orders, snippets/stores. - shared: DEFAULT_REGION_ID=1; UserAddress.addressForm regionId; GetAllOrdersInput.regionId. - address.ts helper + user.address router: optional regionId (default 1). - common-trpc-index: user-facing common.getRegions (summaries: id/name/description). - region.ts: getRegionSummaries (+barrels). - admin order.ts db helper: getAllOrders/getSlotOrders accept regionId, filter via address join (exists). - order router: getAll/getSlotOrders -> adminProcedure, inject ctx region (super_admin = all). - store.ts + vendor-snippets.ts helpers scoped by region; routers adminProcedure; create stamps ctx region. [2026-10-03 19:56:50] Region scoping - Phase 6 (user reads): product.ts region-aware. packages/db_helper_sqlite/src/user-apis/product.ts - imports: add DEFAULT_REGION_ID (value) from @packages/shared + InferSelectModel type; add local MarketStatsRow type and generic pickMarketStats(marketStatsArray, regionId) helper (find by regionId or null). - getProductDetailById(skuId, regionId = DEFAULT_REGION_ID): sku.marketStats is now an array -> marketStats = pickMarketStats(sku.marketStats, regionId); bail (null) when no row or suspended/deleted; store now resolved from marketStats.storeId (product.storeId removed); combo item price uses pickMarketStats(ci.sku.marketStats, regionId). - getProductById(skuId, regionId = DEFAULT_REGION_ID): pick region row; returned object exposes marketStats: picked row + price/marketPrice/flashPrice/isFlashAvailable/ isOutOfStock from that row. - getAllProductsWithUnits(tagId?, regionId = DEFAULT_REGION_ID): filter sku when picked region row missing/suspended, sku deleted, or product is region-restricted (!availableInAllRegions && product.regionId !== regionId); price fields from picked row. - getSuspendedSkuIds(regionId = DEFAULT_REGION_ID): where isSuspended AND regionId = region. - getAllSkusSummary(regionId = DEFAULT_REGION_ID): product columns storeId -> regionId + availableInAllRegions; filter same as products; storeId now from picked marketStats.storeId. [2026-10-03 19:56:50] Region scoping - Phase 6 (user reads): stores.ts region-aware. packages/db_helper_sqlite/src/user-apis/stores.ts - imports: replace productInfo with productMarketStats; add DEFAULT_REGION_ID + InferSelectModel; add local MarketStatsRow + generic pickMarketStats helper. - getStoreSummaries(regionId = DEFAULT_REGION_ID): storeInfo select filtered by storeInfo.regionId = regionId; active SKUs filtered via picked region stats + product region acceptance; grouped by picked marketStats.storeId (was product.storeId). - getStoreDetail(storeId, regionId = DEFAULT_REGION_ID): store lookup also matches storeInfo.regionId = regionId; product ids sourced from productMarketStats where storeId = storeId AND regionId = regionId (values are SKU ids -> productSkus.id); product rows filtered/read through picked region stats. - getStoresSummary(regionId = DEFAULT_REGION_ID): where storeInfo.regionId = regionId. [2026-10-03 19:56:50] Region scoping - Phase 6 (user reads): store-helpers.ts region-aware. packages/db_helper_sqlite/src/stores/store-helpers.ts - imports: add DEFAULT_REGION_ID + InferSelectModel; add local MarketStatsRow + generic pickMarketStats helper. - getAllBannersForCache(regionId = DEFAULT_REGION_ID): where regionId = region. - getAllProductsForCache(regionId = DEFAULT_REGION_ID): filter picked region stats + product region acceptance; storeId now picked marketStats.storeId. - getAvailabilityForCache(regionId = DEFAULT_REGION_ID): where productMarketStats.regionId = region. - getAllStoresForCache(regionId = DEFAULT_REGION_ID): where storeInfo.regionId = region. - getAllProductCombosForCache(regionId = DEFAULT_REGION_ID): suspended-sku set filtered by region; price from picked region stats. - getAllProductTagsForCache(regionId = DEFAULT_REGION_ID): where productTagInfo.regionId = region. - getAllTagsForCache(regionId = DEFAULT_REGION_ID): where productTagInfo.regionId = region. - getAllTagProductMappings(regionId = DEFAULT_REGION_ID): join productTagInfo and filter region. - getAllSlotsWithProductsForCache(regionId = DEFAULT_REGION_ID): slots filtered by deliverySlotInfo.regionId; skus load marketStats with store; filter/read picked region stats (store resolved from marketStats.store, storeId from stats.storeId). [2026-10-03 19:56:50] Region scoping - Phase 6 (user reads): order.ts market-stats fix. packages/db_helper_sqlite/src/user-apis/order.ts - imports: add DEFAULT_REGION_ID + InferSelectModel; add local MarketStatsRow + generic pickMarketStats helper. - getProductById(skuId, regionId = DEFAULT_REGION_ID): sku.marketStats is now an array -> marketStats = pickMarketStats(sku.marketStats, regionId); returned object exposes that picked row with price/marketPrice/flashPrice/isFlashAvailable/isOutOfStock from it. [2026-10-03 20:10:42] Region scoping - Phase 7: slot + banner db helpers region-aware. packages/db_helper_sqlite/src/admin-apis/slots.ts - import DEFAULT_REGION_ID (value) from @packages/shared. - mapDeliverySlot: include regionId: slot.regionId (AdminDeliverySlot now requires it). - getActiveSlotsWithProducts(limit = 20, regionId = DEFAULT_REGION_ID): where and(eq(deliverySlotInfo.isActive, true), eq(deliverySlotInfo.regionId, regionId)). - getSlotsAfterDate(afterDate, regionId = DEFAULT_REGION_ID): where and(eq(isActive, true), gt(deliveryTime, afterDate), eq(regionId, regionId)). - createSlotWithRelations(input): input gains regionId?: number; insert regionId: input.regionId ?? DEFAULT_REGION_ID. - mapVendorSnippet: include regionId: snippet.regionId (AdminVendorSnippet now requires it). - No `with: { marketStats: true }` usage in this file, so no pickMarketStats helper added. packages/db_helper_sqlite/src/admin-apis/banner.ts - import and from drizzle-orm; import DEFAULT_REGION_ID from @packages/shared. - getBanners(regionId = DEFAULT_REGION_ID): where eq(homeBanners.regionId, regionId); row mapper gains regionId. - getBannerById: mapped Banner gains regionId (read unchanged). - createBanner(input: Omit & { regionId?: number }): insert regionId: input.regionId ?? DEFAULT_REGION_ID; returned Banner gains regionId. - updateBanner: returned Banner gains regionId. packages/db_helper_sqlite/src/user-apis/banners.ts - import and, eq; import DEFAULT_REGION_ID. - mapBanner: include regionId: banner.regionId (UserBanner = Banner requires it). - getActiveBanners(regionId = DEFAULT_REGION_ID): where and(isNotNull(homeBanners.serialNum), eq(homeBanners.regionId, regionId)). packages/db_helper_sqlite/src/user-apis/slots.ts - import and; import DEFAULT_REGION_ID. - mapSlot: include regionId: slot.regionId (UserDeliverySlot = AdminDeliverySlot). - getActiveSlotsList(regionId = DEFAULT_REGION_ID): where and(eq(deliverySlotInfo.isActive, true), eq(deliverySlotInfo.regionId, regionId)). - getProductAvailability(regionId = DEFAULT_REGION_ID): where and(eq(productMarketStats.isSuspended, false), eq(productMarketStats.regionId, regionId)). [2026-10-03 20:12:00] Follow-up: vendorSnippets.regionId is NOT NULL, so the two snippet inserts inside createSlotWithRelations / updateSlotWithRelations must stamp it. - createSlotWithRelations snippet insert: add regionId: newSlot.regionId. - updateSlotWithRelations snippet insert: add regionId: updatedSlot.regionId. [2026-10-03 20:13:45] Admin product router region scoping: apps/backend/src/trpc/apis/admin-apis/apis/product.ts - import adminProcedure from @/src/trpc/trpc-index. - add ctxRegion(ctx) and scopedRegion(ctx) helpers. - getProducts/getGroups/getProductTags -> adminProcedure; pass scopedRegion(ctx). - getProductById -> adminProcedure; pass ctx.staffUser?.regionId. - getProductTagById -> adminProcedure; pass ctx.staffUser?.regionId as 2nd arg. - createProduct/updateProduct -> adminProcedure; zod: storeId optional, add regionId, availableInAllRegions, storeIdsByRegion; normalize storeIdsByRegion keys to numbers; pass regionId: input.regionId ?? ctx.staffUser?.regionId plus new fields. - toggleOutOfStock/updateProductPrices -> adminProcedure; pass ctx.staffUser?.regionId. - createGroup -> adminProcedure; pass ctx.staffUser?.regionId as 4th arg. - createProductTag/updateProductTag -> adminProcedure; stamp regionId. - deleteProduct/deleteGroup/deleteProductTag/getProductReviews/respondToReview unchanged. [2026-10-03 20:19:14] Per-region cache file generation. packages/db_helper_sqlite/src/admin-apis/const.ts - import DEFAULT_REGION_ID from '@packages/shared'. - add `versionKey(base, regionId?)` -> base for null/region 1, `${base}_${regionId}` otherwise. - getCacheVersion/incrementCacheVersion (cacheVersion), getAvailabilityVersionNum/ incrementAvailabilityVersionNum (availabilityVersionNum), getSlotsVersionNum/ incrementSlotsVersionNum (slotsVersionNum): all gain optional regionId and use versionKey(CONST_KEYS.*, regionId). Region 1/omitted -> legacy global key. apps/backend/src/lib/cloud_cache.ts - import DEFAULT_REGION_ID from '@packages/shared'; import getRegions from dbService. - buildCachePath(path, version, regionId?) / buildAvailabilityPath(version, regionId?) / buildSlotsPath(version, regionId?): prepend `r-/` only when regionId != null && != 1. - constructCacheUrl/constructAvailabilityUrl/constructSlotsUrl gain regionId. - createProductsFileInternal/createEssentialConstsFileInternal/createStoresFileInternal/ createBannersFileInternal/createAllStoresFilesInternal/createAvailabilityCacheFile/ createSlotsCacheFile gain regionId; scaffold* calls + paths + version increments region-aware. - createAvailabilityCacheFile/createSlotsCacheFile: regionId omitted -> loop all regions; explicit region -> single region; refreshGenKv(regionId). - createAllCacheFiles(): getRegions() loop; new createRegionCacheFiles(regionId) does the per-region build + purge + refreshGenKv; returns DEFAULT_REGION_ID result for back-compat. apps/backend/src/lib/gen-store.ts - import DEFAULT_REGION_ID; add regionKvKey(regionId?). - buildEssentialConsts(regionId?); refreshGenKv(regionId?) puts region key + legacy key for region 1/undefined; readEssentialConstsFromKv(regionId?) reads region key, D1 backfill kept. apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts - scaffoldEssentialConsts(regionId?): region-aware version getters + cachePathPrefix field. - essentialConsts procedure: optional { regionId } input; readEssentialConstsFromKv(regionId). apps/backend/src/trpc/apis/common-apis/common.ts - scaffoldProducts(regionId?): getAllProducts(regionId), getSuspendedSkuIds(regionId), getAllTagsForCache(regionId), getAllTagProductMappings(regionId). - scaffoldAvailability(regionId?): getAvailabilityForCache(regionId). apps/backend/src/stores/product-store.ts - getAllProducts(regionId?) / getProductById(regionId?) thread region into cache helpers. apps/backend/src/stores/slot-store.ts - getAllSlots(regionId?) / fetchAllTransformedSlots(regionId?) thread region. apps/backend/src/trpc/apis/user-apis/apis/stores.ts - scaffoldStores(regionId?) / scaffoldStoreWithProducts(storeId, regionId?). apps/backend/src/trpc/apis/user-apis/apis/slots.ts - scaffoldSlotsWithProducts(regionId?) -> getAllSlots/region + getUserProductAvailability(region). apps/backend/src/trpc/apis/user-apis/apis/banners.ts - scaffoldBanners(regionId?) -> getUserActiveBanners(region). apps/user-ui/src/constants.ts - export const REGION_ID = 1 (client hardcode). apps/user-ui/src/hooks/prominent-api-hooks.ts - prepend cachePathPrefix (default '') to products/availability/slots/store cache URLs. store-initializer.ts / cache-creator.ts unchanged (createAllCacheFiles now loops regions). Admin triggers unchanged (no-arg create*CacheFile loops every region). [2026-10-03 20:27:32] Region-aware store selector + "Available in all regions" checkbox on product Add/Edit forms (admin-ui + admin-web). apps/admin-ui/src/components/ProductForm.tsx - ProductFormData gains optional regionId?, availableInAllRegions?, storeIdsByRegion?. - formInitialValues normalizes availableInAllRegions ?? false and storeIdsByRegion ?? {}. - store source switched from trpc.common.getStoresSummary to trpc.admin.store.getStores; keep {label,value} options plus store.regionId for per-region filtering. - new regions query trpc.admin.region.getRegions -> regions[]. - yup storeId now required only when availableInAllRegions is false (Yup.when). - new product-level Checkbox `product-all-regions-checkbox` ("Available in all regions"). - when unchecked render the existing single store BottomDropdown; when checked render one BottomDropdown per region bound to storeIdsByRegion[region.id]. - toggle handler pre-fills each region with the store whose name matches the current single-selection store's name (region+name match). - RegionStorePrefill child (useFormikContext) name-matches per-region stores on edit when availableInAllRegions is true and a region has no selection yet. - onSubmit still emits ProductFormData (new fields flow through to the screens). apps/admin-ui/app/(drawer)/dashboard/products/add.tsx - initialValues add regionId: undefined, availableInAllRegions: false, storeIdsByRegion: {}. - create payload: if values.availableInAllRegions -> { availableInAllRegions: true, storeIdsByRegion (only regions with storeId>0) }; else { availableInAllRegions: false, storeId: values.storeId }. regionId omitted on create. apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx - initialValues: storeId from productData.store?.id ?? 1 (fixes pre-existing storeId TS error), regionId: productData.regionId, availableInAllRegions: productData.availableInAllRegions ?? false, storeIdsByRegion: {} (prefilled by name-match). - update payload: always regionId; all-regions -> availableInAllRegions + storeIdsByRegion; restricted -> availableInAllRegions: false + storeId. apps/admin-web/src/components/ProductForm.tsx - same shape as admin-ui: optional ProductFormData fields, normalized formInitialValues, trpc.admin.store.getStores + storeOptionsForRegion, trpc.admin.region.getRegions, conditional yup storeId, `product-all-regions-checkbox` Checkbox, per-region Dropdowns, name-match toggle prefill + RegionStorePrefill child. apps/admin-web/src/routes/dashboard.products.new.tsx - initialValues add regionId: undefined, availableInAllRegions: false, storeIdsByRegion: {}. - create payload mirrors admin-ui (storeIdsByRegion when all-regions, else storeId; no regionId). apps/admin-web/src/routes/dashboard.products.edit.tsx - initialValues: storeId from productData.store?.id ?? 1 (fixes pre-existing storeId TS error), regionId, availableInAllRegions, storeIdsByRegion: {}. - update payload mirrors admin-ui, always includes regionId. Tests: apps/admin-ui/tests/components/product-form.test.tsx mocks `common.getStoresSummary`. Since the form now queries `admin.store.getStores`, that mock no longer feeds store options. Unmocked procedures resolve to null, so assertions still hold (dropdown visible / fetch called); only the store-options data would be empty if a test asserted option labels. Not edited per instructions. [2026-10-03 20:31:34] Region scoping - Phases 6-11 complete: products/availability, lifecycle, slots/banners, cache, UIs. - product.ts: getAllProducts/getProductById region-filtered (myregion OR allregions); createProduct/updateProduct region + availableInAllRegions + per-region storeIdsByRegion; market stats per region (non-creator regions out of stock); updateProductPrices/toggleProductOutOfStock region-scoped; backfillMarketStatsForRegion. - product router: adminProcedure, region/availableInAllRegions/storeIdsByRegion inputs. - region router: superAdminProcedure; create backfills market stats; delete rejects (non-deletable). - cache: per-region files (r-/ prefix), per-region version counters + essentialConsts KV keys; region 1 keeps legacy. - superadmin-ui: /admins create-admin (role+region dropdowns); region Delete removed. - admin-ui + admin-web: ProductForm gains 'Available in all regions' checkbox + per-region store dropdowns (name-matched). - user-ui: REGION_ID=1 constant; cache URL prefix. [2026-10-03 20:50:28] Region defaults: make admin db helpers require regionId; keep optional (default 1) only for user-facing APIs. Admin helpers (product/slots/banner/vendor-snippets/store) now take required regionId; call sites pass ctx.staffUser.regionId. User helpers (user-apis product/stores/slots/banners/order + store-helpers cache fns) keep regionId optional (defaults to DEFAULT_REGION_ID). Kept DEFAULT_REGION_ID in: user-ui constant, address add/update, backfill, and region-1 legacy cache path/KV/version checks. [2026-10-03 20:56:15] Region defaults cleanup: admin helpers require regionId; user-facing keep optional (default 1). - admin-apis/product.ts, slots.ts, banner.ts, vendor-snippets.ts, store.ts: regionId now REQUIRED (no default); create paths guard/inject region. - admin routers: getBanners/createBanner/slots.getAll pass ctx.staffUser.regionId; getUpcomingSlots (public) uses DEFAULT_REGION_ID. - product-tag-store.getTagsByStoreId(storeId, regionId=DEFAULT_REGION_ID) (user-facing). - Kept DEFAULT_REGION_ID: user-ui constant, address add/update, backfill source, and region-1 legacy cache path/KV/version checks. - Removed unused DEFAULT_REGION_ID imports. [2026-10-03 21:17:26] All-region products: product_info.region_id is NULL. - schema.ts: productInfo.regionId nullable (remove .notNull()). - migration 0007: product_info.region_id column no NOT NULL (allow NULL). - shared types: AdminProduct.regionId number | null. - product.ts: createProduct sets regionId=null when availableInAllRegions; region logic keyed on creator ctx region for market stats; updateProduct handles null product.regionId. - product router / superadmin / admin forms tolerate null regionId. [2026-10-03 21:21:26] Verified: all-region products store NULL region_id. - tsc: backend, admin-ui, admin-web, user-ui, web-ui, superadmin-ui all 0 errors. [2026-10-03 22:16:19] Fix: embedded product slots/nextDeliveryDate were cross-region. - store-helpers getAllDeliverySlotsForCache(regionId=DEFAULT_REGION_ID) now filters deliverySlotInfo.regionId. - user-apis/product getNextDeliveryDateWithCapacity(skuId, regionId=DEFAULT_REGION_ID) now filters region. - product-store.getAllProducts passes regionId; common.scaffoldProducts passes regionId. - (special_deals still global: no region column — separate gap.) [2026-10-03 22:17:29] Slot region-leak fix verified: backend tsc 0 errors. Remaining intentionally user-default-1: legacy common-product.controller.ts (getNextDeliveryDate/getAllProductsWithUnits). special_deals remains global (no region column). [2026-10-03 22:23:23] Delete dead legacy REST chain for /api/v1/cm/products/summary. Removed: apps/backend/src/apis/common-apis/apis/common-product.controller.ts, common-product.router.ts, common.router.ts, apps/backend/src/v1-router.ts, and the '/v1' mount + import in main-router.ts. No client references this route (UI uses trpc.common.product.getAllProductsSummary instead). Also removes the last non-region-scoped getNextDeliveryDate caller. [2026-10-03 22:27:00] Remove unused getAllProductsWithUnits + ProductSummaryData (sqlite + barrels). - Deleted from packages/db_helper_sqlite/src/user-apis/product.ts (+ unused productTags import). - Removed exports from packages/db_helper_sqlite/index.ts and apps/backend/src/sqliteImporter.ts. - postgres package left untouched (out of scope, not consumed). [2026-10-03 22:31:53] Fix: region create now regenerates caches. - region router createRegion: after createRegion + backfillMarketStatsForRegion, call scheduleStoreInitialization() so per-region cache files (incl. the new region) are rebuilt. [2026-10-03 22:43:36] All-region toggle-off check: restricted-branch delete already uses creatorRegionId (product.ts:552). Reported bug referenced product.regionId, but current code uses creatorRegionId (the editing admin's region), so 'regionId <> creatorRegionId' correctly removes other regions' rows when toggling all-regions -> restricted. Added a guard throwing if creatorRegionId is null (all-region product + no ctx region) to prevent silent no-op. [2026-10-03 22:46:09] Fix: product create/update must force ctx region (ignore client regionId). - admin.product.createProduct / updateProduct: use ctx.staffUser.regionId as the write target instead of client-supplied input.regionId, preventing a non-superadmin admin from writing another region's market-stats rows. [2026-10-03 22:48:56] Fix same escalation in admin.store: createStore/updateStore force ctx region for non-superadmins. - Added writeRegion(ctx, inputRegion?) helper (super_admin may target a region; others forced to ctx). - createStore (was input.regionId ?? ctx) and updateStore (was raw input.regionId) now use writeRegion. - staff-user createStaffUser is superAdminProcedure and intentionally honors input.regionId. [2026-10-03 22:54:30] Fix: admin getProductById had no region/availableInAllRegions filter. - getAllProducts / getProductById now accept regionId?: number; when null -> no filter (super_admin sees all). When set -> region = ? OR availableInAllRegions = true. - Router getProductById uses scopedRegion(ctx) (consistent with getProducts) instead of ctxRegion. [2026-10-03 22:55:43] Verified: backend tsc 0 errors after getProductById/getAllProducts region filter. [2026-10-03 22:58:48] Fix: product tag names were globally unique, blocking reuse across regions. - schema.ts: productTagInfo.tagName .unique() -> composite uniqueIndex(tagName, regionId). - migration 0007: DROP INDEX product_tag_info_tag_name_unique; CREATE UNIQUE INDEX unique_tag_name_region (tag_name, region_id). - checkProductTagExistsByName(tagName, regionId?) scoped by region. - admin.product.createProductTag passes ctx region. [2026-10-03 23:03:07] Remove dead REGION_ID constant from apps/user-ui/src/constants.ts (zero usages; cache prefix comes from essentialConsts.cachePathPrefix). [2026-10-03 23:07:58] Fix: rebalanceSlots treated marketStats as a single object (now an array -> NaN/0 prices). - admin-apis/order.ts rebalanceSlots(slotIds, regionId) uses pickMarketStats per order item. - router provides ctx region via adminProcedure. [2026-10-03 23:09:07] rebalanceSlots fix verified: backend tsc 0 errors. [2026-10-03 23:18:19] Delete getUpcomingSlots procedure + fallback-ui usage. - backend vendor-snippets router: removed getUpcomingSlots (hardcoded DEFAULT_REGION_ID). - fallback-ui vendor-order-list: removed getUpcomingSlots query, slot auto-select, slot selector UI; orders now always from getOrdersBySnippet. [2026-10-04 09:41:41] Remove unused getSlotsAfterDate db helper (sqlite). - Deleted from packages/db_helper_sqlite/src/admin-apis/slots.ts. - Removed exports from packages/db_helper_sqlite/index.ts and apps/backend/src/sqliteImporter.ts. - postgres copy left untouched (out of scope). [2026-10-04 10:09:07] Cross-region store selection + per-region storeId persistence. 1) New backend procedure store.getStoresForAllRegions (adminProcedure) returning all stores across regions (unfiltered), same scaffoldAssetUrl image mapping + {stores,count} shape as getStores. getStores remains write-scoped. 2) admin-web + admin-ui ProductForm: load getStoresForAllRegions for the all-regions store dropdowns + storesForRegion + RegionStorePrefill; keep getStores for single-store branch. 3) updateProduct (db_helper_sqlite/src/admin-apis/product.ts): availableInAllRegions branch now UPDATEs existing productMarketStats.storeId for every region key present in storeIdsByRegion (missing-row insert retained; price/stock untouched for non-creator regions; absent keys = no change). 4) UI constraint: storeId never null. Both ProductForms build validationSchema via useMemo; when availableInAllRegions, require a positive store for every region, message: Create a store for "" before saving. [2026-10-04 10:22:46] User region resolution on startup (user-ui + backend). 1) New backend public procedure common.resolveRegionForLocation (apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts): input {lat,lng}, loads regions+bounds, turf booleanPointInPolygon per bound (Polygon/Feature/FeatureCollection tolerant, skip bad GeoJSON), first match wins, returns {regionId,regionName} or {regionId:null}. checkLocationInPolygon untouched. 2) user-ui RegionContext (persisted) + RegionGate blocking screen replacing LocationTestWrapper warnings: permission->resolve->persist, unserved/denied->manual region picker via common.getRegions. 3) regionId threaded through all user API calls (essentialConsts + products/stores/slots/banners/addresses); backend audit adds optional regionId where missing (default 1 preserved). [2026-10-04 10:32:26] Home screen region bar above search (user-ui). - apps/user-ui/app/(drawer)/(tabs)/home/index.tsx: Animated region bar (pin icon + active regionName via useRegion) rendered above the fixed search bar; collapses (height/opacity over scroll 0..48) via main MyFlatList onScroll, so region scrolls out while search stays sticky. testID home-region-bar. [2026-10-04 10:36:51] Fix migration 0007: replace product_info DROP COLUMN store_id with a table rebuild. Root cause: SQLite ALTER TABLE ... DROP COLUMN fails when the column is used in a FOREIGN KEY definition; product_info.store_id has FOREIGN KEY (store_id) REFERENCES store_info(id). Error: 'error in table product_info after drop column: unknown column "store_id" in foreign key definition'. Verified local DB rolled back atomically (no region_id columns), remote untouched. Pattern matches existing 0002_sku_split.sql rebuild (PRAGMA defer_foreign_keys = on, __new_product_info, copy, DROP, RENAME). Diff packages/db_helper_sqlite/drizzle/0007_region_scoping.sql: - Added PRAGMA defer_foreign_keys = on; at top. - Removed product_info region_id/available_in_all_regions ADD COLUMN statements and the UPDATE backfill. - Removed ALTER TABLE product_info DROP COLUMN store_id. - Added a rebuild block (after market-stats backfill): CREATE TABLE __new_product_info (id, name, short_description, long_description, region_id, available_in_all_regions, increment_step, created_at, product_type) with region_id=1 backfill in the INSERT/SELECT, DROP TABLE product_info, RENAME __new_product_info -> product_info. - Index swap statement unchanged. [2026-10-04 10:52:29] RegionGate: remove simulator/emulator bypass. - apps/user-ui/components/RegionGate.tsx: deleted isEmulatorDevice check and forceGate prop; location permission + GPS resolve + picker flow now runs identically on simulators and real devices. [2026-10-04 10:58:43] RegionGate: 'Unable to obtain location' message with cause-specific subheading + action. - Detects location-services-off via hasServicesEnabledAsync (separate from permission-denied). - Message screen: title 'Unable to obtain location'; denied -> grant-access copy + 'Open Settings' (expo-linking); services-off -> turn-on copy + Android enableNetworkProviderAsync / iOS Open Settings. - Secondary 'Choose region manually' -> existing picker; tertiary continue-with-stored when present; AppState recheck on return from Settings. [2026-10-04 11:42:04] Region switch with per-region cart snapshots + reconcile (user-ui). - hooks/cart-query-hooks.tsx: export getLocalCart/saveLocalCart; add cart-snapshot key helpers; regionSwitchInProgress guard respected by useReconcileCartSlots. - New src/hooks/useRegionSwitch.ts: LoadingDialog -> snapshot both carts -> setRegion -> await fresh region payloads -> restore-or-carry -> reconcile (keep/nearest-future-freeze-slot/remove) -> save -> results BottomDialog. - Home bar: BottomDropdown region switcher (pin+name trigger) replacing static label; collapse animation kept. [2026-10-04 11:51:57] Region dropdown on all level-1 tab pages (user-ui). - New RegionSwitchProvider (context around useRegionSwitch) + RegionSwitchDialogs mounted once in _layout; home no longer owns switch dialogs. - New shared components/RegionBar.tsx (BottomDropdown pin+name trigger, optional scrollY collapse); used on home, stores, order-again, me, flash-delivery products (inside list header there). [2026-10-04 12:03:55] Hide 'popularItems' constant in admin-ui customize-app screen. Diff apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx: - CONST_VISIBILITY.popularItems: true -> false [2026-10-04 12:14:20] Region-based essential consts (region_consts table). - New region_consts(region_id,key,value,PK(region_id,key)) + 0008 migration (backfill all regions from key_val_store, then delete the 10 regional keys); seeds scrubbed. - REGION_CONST_KEYS (10 admin-ui-visible keys); getRegionConstants/upsertRegionConstants; getAllConstValues/getConstant(s) accept regionId (global+region merge). - Admin const router: adminProcedure + ctx region; refreshGenKv(regionId); same Constant[] shape (forms unchanged). - scaffoldEssentialConsts passes regionId; order placement consts resolve via address.regionId. KV payload shape unchanged. [2026-10-04 12:21:15] Seed Mahabubnagar region + 2 MBNR polygons in 0006 migration. - packages/db_helper_sqlite/drizzle/0006_regions.sql: INSERT OR IGNORE region id 1 'Mahabubnagar' + two region_bounds rows (Polygon geometries extracted from apps/backend/src/map-assets/Mbnr-1.geojson and Mbnr-2.geojson), guarded by NOT EXISTS so re-runs/existing region 1 stay untouched. [2026-10-04 12:25:50] Condense 0008_region_consts into 0007_region_scoping (both unapplied). - Appended region_consts CREATE + backfill + key_val_store DELETE to 0007 as section 6; deleted 0008_region_consts.sql; journal idx 8 entry removed. [2026-10-04 13:16:22] Region Telegram creds + per-region order notifications. - 0006_regions.sql: region_telegram_creds(id,region_id,bot_token,chat_id,added_at,UNIQUE(region_id,chat_id)) + seed row for region 1 (guarded). - schema.ts regionTelegramCreds + relations; getRegionTelegramCreds(regionId) helper (+barrels). - getOrdersByIdsWithFullData address select gains regionId. - telegram-service sendTelegramMessage(message, creds) per-cred fan-out; handleOrderPlaced + cancellation group by address.regionId, zero creds -> skip + log, else per-region message to all creds. Env sender untouched. [2026-10-04 13:21:14] Superadmin region create: at least 1 telegram cred set mandatory. - regions.new.tsx: creds section (bot token + chat id rows, add/remove, min 1 required, submit blocked otherwise). - createRegion input gains creds; db createRegion inserts region_telegram_creds rows in same transaction; shared CreateRegionInput extended. [2026-10-04 13:38:16] Push token saved with region (user-ui background). - 0006_regions.sql: region_id (nullable FK) on notif_creds + unlogged_user_tokens. - schema.ts: nullable regionId + relations on both tables. - upsertNotifCred/upsertUnloggedToken take regionId, by-token move semantics (owner+region follow device). - savePushToken input gains regionId; notif-checker sends active region and resaves on region change/detection. [2026-10-04 13:40:37] Admin user broadcast scoped to admin region. - User push broadcast (admin notify-all-users path) filters notif_creds + unlogged tokens by ctx staffUser.regionId via region_id column. [2026-10-04 13:44:03] Backfill region 1 for existing push tokens. - 0006_regions.sql: UPDATE notif_creds + unlogged_user_tokens SET region_id = 1 WHERE region_id IS NULL. [2026-10-04 13:46:45] Order-placed staff push scoped to order region. - getAllStaffNotifTokens(regionId?) filters via staff_users.region_id. - notifyAllAdmins(payload, regionId?) passes through; handleOrderPlaced notifies per order with order.address.regionId (regionless -> all staff + log). [2026-10-04 13:48:01] Admin push on new complaint (region-scoped). - Complaint raise path notifies region admins via notifyAllAdmins with the complainant/order region. [2026-10-04 13:57:47] AddressForm region dropdown (user-ui). - src/components/AddressForm.tsx: region BottomDropdown (common.getRegions) at the end of the form, required; defaults to detected active region; regionId sent on create and update. [2026-10-04 14:05:09] Cart page address selector with region-aware auto-select. - cart-page.tsx: address selector section (list + add via AddressForm dialog, shared useAddressStore). - On add: new address in current region -> auto-selected; in another region -> dialog lists all addresses of that region for manual pick. [2026-10-04 14:08:42] Address-change region reconcile with pre-confirm dialog (user-ui). - centralSlotStore: pure buildProductSlotsMap extracted; useRegionSwitch: fetchRegionSlotMap helper (no store write). - New AddressRegionWatcher (mounted in layout): on selected-address region change with non-empty carts, previews reconcile and shows confirm dialog (moves/removals, >1hr shifts badged); Confirm runs switchRegion, Cancel reverts selection. [2026-10-04 14:12:08] Checkout page shows selected address read-only (no selector). - checkout-page.tsx: CheckoutAddressSelector replaced with static delivery-address card; removed dead add-address dialog + unused imports/state. [2026-10-04 14:31:09] Per-bound constants + bound name/description/priority (prerequisite, unapplied migrations edited in place). - 0006: region_bounds gains name/description/priority; MBNR seeds carry values (priorities 1,2). - 0007 S6 rewritten: region_consts(id PK,region_id,bound_id NULL,key,value,UNIQUE(region,key,bound)), backfilled with bound_id NULL. - Bound meta mandatory (name/description) + unique-priority enforced in superadmin forms + region router guard; bounds ordered asc(priority),asc(id) everywhere. - resolveRegionForLocation returns boundId/boundName; RegionContext + essentialConsts + KV per bound (essential_consts__); priority-1 bound is the default (server-side, NULL rows fallback-only). - Admin const router boundId scope; customize-app bound tabs; order consts resolve bound from address coords. [2026-10-04 15:30:41] Fix: same tag name blocked across regions (missing index swap in 0007). - 0007_region_scoping.sql S7: DROP INDEX product_tag_info_tag_name_unique; CREATE UNIQUE INDEX unique_tag_name_region (tag_name, region_id). Code already region-scoped; only the migration was missing. [2026-10-04 15:33:38] Order pricing/flash validation uses order region, not region 1. - getProductById(skuId, regionId, boundId?) threads bound into pickMarketStats. - placeOrderUtil passes (address.regionId, addressBoundId) at both getOrderProductById calls (pricing + flash gate). [2026-10-04 15:34:48] updateRegion/deleteRegionBound preserve bound ids + clean bound consts. - RegionBoundInput gains optional id; updateRegion upserts bounds by id (update existing, insert new, delete removed + their region_consts rows); deleteRegionBound deletes dependent region_consts first. Router boundInput + duplicate guard accept ids; edit form tracks and sends bound ids. [2026-10-04 15:47:37] Cross-region hijack guards on product/store writes. - product.updateProduct / store.updateStore: non-superadmin 403 on foreign-region targets; flag flips either way 403. - toggleOutOfStock / updateProductPrices / deleteProduct: same ownership rule (prices folds foreign ids into invalidIds). - New admin.staffUser.getSelf + useIsSuperAdmin in both admin apps; ProductForm checkbox disabled-checked for non-superadmin on all-region products. [2026-10-04 15:58:19] Fix user-ui region/address drift. - AddressRegionWatcher: address-region mismatch always converges active region (silent snapshot+setRegion for empty/all-kept carts, confirm dialog only for moves/removals); effect watches activeRegionId with external-switch re-anchor (explicit region choice wins); cancel dismissal remembered to avoid re-prompt loops. - RegionContext hydrate validates stored regionId against backend getRegions; unknown ids reset (gate re-prompts); stale boundId left to graceful server fallback. [2026-10-04 16:06:14] Missing region propagation fixes. - common.product.getAllProductsSummary/getAllSkusSummary: publicProcedure -> adminProcedure + scopedRegion(ctx). - common.getStoresSummary: optional regionId input threaded through. - scaffoldStoreWithProducts: getTagsByStoreId(storeId, regionId) (fixes cross-region tags in cache files). - Deleted dead slot-store.getSlotById (no callers, unexported). [2026-10-04 16:35:04] Remove per-startup seed from local dev server. apps/backend/index.ts: - Remove 'import { seed } from "@/src/lib/seed"' and the top-level 'seed()' call. - initFunc() and createApp() stay; seed helpers in packages/db_helper_sqlite (src/lib/seed.ts + src/db/seed.ts) remain available for manual use. [2026-10-04 17:02:53] Move SKU isOffer to product_market_stats (per-region). - schema.ts: isOffer on productMarketStats (default false), removed from productSkus. - 0007: ADD COLUMN + backfill from parent SKU + DROP COLUMN product_skus.is_offer. - Writes: form value lands on creator-region market-stats rows only; reads sourced from picked region row. Types/responses unchanged. [2026-10-04 18:05:00] Fix D1 single-element IN (?) failure in region helpers (found during multi-region test run: superadmin /regions list "Error loading regions"). - admin-apis/region.ts getBoundsForRegionIds: use eq() when exactly 1 region id (D1 rejects scalar IN (?) binding); inArray otherwise. - Same guard for updateRegion removed-bound deletes (regionConsts.boundId, regionBounds.id) which hit IN (?) with 1 id when a single bound is removed. [2026-10-04 18:40:00] Test-run finding: local dev D1 was missing 0006/0007 pieces, breaking admin.region.getRegions, getRegionById, and common.resolveRegionForLocation (the user-ui gate "could not detect your region" was caused by this, not by location). Per user instruction ran user's wrangler --file command for 0006 (partially failed on missing columns), then applied residuals to DEV DB ONLY (migrations untouched): - region_bounds: ADD name/description/priority + backfilled Mbnr-1 (pri 1) / Mbnr-2 (pri 2). - Created region_telegram_creds + unique index + seeded R1 cred. - notif_creds / unlogged_user_tokens: ADD region_id + backfilled 1. - region_consts: rebuilt with (id PK, bound_id) preserving R1 rows + unique (region,key,bound). - product_market_stats: ADD is_offer + backfilled from skus; DROP product_skus.is_offer. - Tag composite unique (tag_name, region_id) created. Verified: admin getRegions returns bounds; resolve(16.745,78.01) -> {1, Mbnr-1}. [2026-10-04 21:20:00] Test-run finding: order totals wrong whenever a region delivery-charge row exists (R1 order stored total '23318' instead of 251). Root cause: region_consts values are DB strings; const-store mergedConstMap/getConstant returned them uncast, so totalAmount + deliveryCharge concatenated ('233'+'18') and 'false' boolean flags were truthy (flash could never be disabled per region; essentialConsts served "false" strings). Fix: apply castConstValue in const-store mergedConstMap + getConstant (globals + regional). Admin paths already cast (idempotent). [2026-10-04 21:45:00] Multi-region test run completed (multi-region-tests.txt 1-26 + docs/region-test-cases.txt §§1-20) via Maestro MCP (iOS sim), Playwright (superadmin-ui), direct tRPC. Code fixes applied during run: (1) region.ts single-element IN (?) guards; (2) const-store castConstValue on user paths (order totals + flash flags). Dev-D1 schema aligned to 0006/0007 (additive, per user instruction). Full verdicts in chat report. [2026-10-04 22:15:00] Add committed region test suites (user asked to keep run tooling in repo). - NEW tests/e2e/regions/: config.yaml, run.sh, .env.example, README.md + Maestro flows (user-region-gate-manual-pick, user-login-password, user-cart-add-item, user-cart-select-address, user-region-confirm-switch, admin-login subflow reuse, admin-product-visible, admin-product-absent, admin-const-edit-delivery-charge). Own workspace so the main tests/e2e glob is unaffected. - NEW tests/web/: playwright.config.ts, .env.example, README.md, lib/trpc.ts (tRPC helper), specs auth.spec.ts, regions.spec.ts (create/list UI), regions-negative.spec.ts (API-level: dup priorities/creds/name, pri 0, delete 400, SEC 403/401), admins.spec.ts (create admin UI). - EDIT package.json: add test:e2e:regions + test:web scripts. EDIT .gitignore: playwright test-results/blob/auth outputs. [2026-10-04T17:20Z] e2e full-suite per tests/e2e-suite.txt (user: Maestro mobile + Playwright web; reuse region 1; add Store/Tag testIDs; spike slot dates first; Maestro-Chromium dropped, Chrome/web-driver broken in this env) + tests/web/specs/e2e-setup.spec.ts (new): superadmin login -> assert Mahabubnagar/region-1 present -> create region-1 admin (role admin) -> verify staff login via tRPC -> write tests/e2e/full-suite/.env.e2e (STAMP/ADMIN_NAME/ADMIN_PASSWORD/REGION_ID=1) for Maestro run.sh hand-off [2026-10-04T17:35Z] full-suite: add testIDs to StoreForm (store-name-input, store-description-input, store-owner-dropdown, store-products-selector, store-submit-button) + TagForm (tag-name-input, tag-description-input, tag-image-add, tag-dashboard-checkbox, tag-stores-dropdown, tag-products-selector, tag-submit-button). No behavior change; enables Maestro id selectors. [2026-10-04T18:05Z] full-suite: add testIDs to ProductForm combo rows (variant-{i}-combo-add, variant-{i}-combo-sku-{c}) — Included Items Add/SKU dropdowns had no testIDs (would render undefined-* selectors). No behavior change. + tests/e2e/full-suite/ workspace (Maestro iOS + Playwright web setup): config, run.sh, .env.example, README, subflows, admin/user flows, scripts/readback (structure below) [2026-10-05T03:55Z] BUGFIX (found by full-suite): tag<->product assignment sent PRODUCT ids into product_tags.product_id which references product_skus.id (FK 500 unless ids coincide). TagForm submit now sends SKU ids; hydration keyed by skuId. Files: apps/admin-ui/src/components/TagForm.tsx, apps/admin-web/src/components/TagForm.tsx. No migration (schema already SKU-based). [2026-10-05T06:50Z] full-suite: BottomDropdown search input gets autoCorrect={false} autoCapitalize="none" (iOS autocorrect rewrote suite search queries, e.g. "E2E.." -> "VE2E..", breaking option filtering). Search-box correctness fix, no behavior change otherwise. [2026-10-05T09:05+05:30] full-suite slots leg: slot_products attach rewritten in scripts/gen_slots.py — no search interaction at all (tapping search summons keyboard which swallows paging swipes; typing proved unreliable). Open selector + 12x long unconditional swipes (50%,80% -> 50%,30%) then exact testID taps slot-products-selector-option- + Done. Verified paging geometry via CLI probe on live sheet. [2026-10-05T09:10+05:30] full-suite slots leg: slot dialog search auto-focuses AFTER data loads (delayed) — keyboard covers swipe zone so paging silently no-ops. Fix in scripts/gen_slots.py: tap sheet title "Select Products" to blur search/dismiss keyboard, then page with long swipes. Rows confirmed to expose slot-products-selector-option- testIDs. [2026-10-05T09:25+05:30] full-suite: fix scripts/readback.py --slots procedure path admin.slot.getAll -> admin.slots.getAll (router is slotsRouter mounted as slots; --slots never ran green before). [2026-10-05T09:30+05:30] full-suite slots leg ROOT CAUSE (MCP micro-spike on live wheels): minute down-drags at (35%,50%->62%) never engage the wheel — touch-down must be ON the selected row (~56%) at the minute column (~38%). Verified: swipe 38%,56%->68% moves minutes -3 exactly (5:15PM->5:12PM). Fix in scripts/gen_slots.py: down_drags start 50->56, minute x 35->38. Also adding SLOT_FROM/SLOT_TO subset (retry slots 4-8 without duplicating 1-3) and relaxing readback.py slot gaps (wild wheel-init minutes: delivery gap 7200+-180s, freeze gap 12-18min). [2026-10-05T09:45+05:30] full-suite: fix scripts/readback.py --slots timezone bug — backend stores delivery/freeze in UTC ISO, targets are IST; parse_time now converts aware datetimes to IST before naive compare. [2026-10-05T09:55+05:30] full-suite: repaired freeze times of slots 1-3 (created with broken minute geometry: gaps 12/59/60min) to exact delivery-15min via admin.slots.updateSlot API (ids 1991/1992/1993). tRPC notes: mutations POST {0:data}; queries GET-only with input {"0":inp}. [2026-10-05T10:00+05:30] full-suite: freeze clock read moved BEFORE wheels open in gen_slots.py (M0 ~= wheel-init minute; post-drag reads undershoot by elapsed minutes). Residual outliers normalized via admin.slots.updateSlot. [2026-10-05T10:05+05:30] full-suite: NEW scripts/normalize_slots.py (set matched slots freeze = delivery-15min exact via updateSlot; wired into run.sh after admin-slots.yaml, before readback --slots). Wheel minute drags systematically undershoot ~3-4 rows (coast interrupted by chunk reopens); deliveries/order/SKUs stay UI-created, only the freeze offset is exacted. All 8 slots now verified: 2h apart, freeze 15min, SKU sets correct. [2026-10-05T10:15+05:30] full-suite user leg diagnosis (MCP wedged, CLI probes): home tag tabs are a HORIZONTAL bar ordered by tagsOrder (ours last); vertical scroll never reveals them. Fix: readback --tags exports TAG1_ID/TAG2_ID; user-journey navigates tabs horizontally by testID (tag-tab-). Region confirmed match (products region 1, Mahabubnagar == region 1, app on Mahabubnagar). [2026-10-05T10:25+05:30] full-suite: ma_user now uninstalls the user app before each run — Maestro clearState does not fully wipe iOS storage (stale essentialConsts + old products.json survived, hiding new tags; proven by order glimpse rendering on "fresh" launch). Admin leg keeps terminate (auth persistence wanted). [2026-10-05T10:35+05:30] full-suite: NEW scripts/refresh_bound.py + run.sh wiring (before user leg). No-op admin.const.updateConstants for bound 1 rebuilds the bound-scoped essentialConsts KV snapshot so the app reads current cache versions. App bug flagged: bound KV keys rot (772 vs 796) since only const-saves refresh them; product/tag/slot creation + boot refresh region keys only. [2026-10-05T14:05+05:30] full-suite user leg: product cards expose concatenated a11y text (exact-name textesa never matches) — verify grid rows by testID tag-product- (P1SK0/P2SK0 via MENV+EXTRA); search-result add-to-cart is an ICON (add-to-cart-icon), not 'Add to Cart' textesa. Probe proved tag-12 grid renders our Chicken row (name+price+qty) once bound consts are fresh. [2026-10-05T14:10+05:30] full-suite user leg time-robustness: slot 2 carries full SKU superset (gen_slots.slot_skus); readback --slots emits SLOT_A/SLOT_B (first two live slots as dialog testIDs); user-journey 18a/18b/19 tap SLOT_A/B instead of fixed SLOT1/2; step-17 full-order check stays in readback, UI does live-pair smoke check. Search cards use 'ADD TO CART' button textesa (in-stock row first), not the icon. [2026-10-05T14:20+05:30] full-suite (session repair): combo SKU 164 lived only in expired slot 1 -> attached to live slot 3 (id 1993) via updateSlot so step 19 can add the combo. Future runs covered by slot-2 superset rule instead. [2026-10-05T14:25+05:30] full-suite user leg: bottom tabs expose merged iOS a11y ('Offers, tab, 2 of 5') — tap by regex, not bare label. Steps 15-18 verified green (tags, grids, search, both slot dialogs, confirms). [2026-10-05T14:30+05:30] full-suite user leg: launchApp now clearKeychain:true — cart/session persist in expo-secure-store (iOS keychain) across clearState launches, causing stale steppers instead of ADD TO CART buttons on reruns. [2026-10-05T14:40+05:30] full-suite user leg: tab-strip paging via swipe-from-element chains (strip Y shifts with page content: ~21% logged-out vs ~47% with order carousel — fixed points miss). Chain 9->8->6 then assert; TAG2 nudge from active tab. [2026-10-05T14:50+05:30] full-suite user leg step 19: combo card tap via stamp regex (.*STAMP.*) — card names line-wrap into separate textesa nodes (no exact full-name match); stamp has no spaces so never splits. Only our combo is on Offers. [2026-10-05T16:10+05:30] full-suite step 20: cart entry via deep link freshyo://(drawer)/(tabs)/home/cart + Open-sheet confirm — floating Go to Cart bar mis-routed to the flash cart twice. Regular cart verified holding all 3 items in right slots (probe screenshot). [2026-10-05T16:20+05:30] full-suite login-user subflow rewritten: mobile submit always sends OTP — password path is 'other ways to login' BEFORE submit (direct to password step, identifier prefilled). Paste-style typing; post-login cart entry via deep link (avoids floating-bar mis-route). [2026-10-05T16:30+05:30] full-suite: tab taps anchored (^Offers, tab, 2 of 5$) — unanchored textesa also matches ancestor containers with merged a11y, whose center-tap lands on the flash tab (root cause of both flash mis-routes). [2026-10-05T16:45+05:30] full-suite steps 20-23 restructure: address is added on CART (Delivery Address section, authenticated) not checkout; checkout asserts 'No address selected' gone; step-23 glimpse scroll DOWN (UP scrolls risk tab taps). [2026-10-05T17:20+05:30] full-suite: fresh end-to-end run with new STAMP (old stamp slots expired faster than debug cycles). All Rubin-hemaspheric fixes in: bound refresh, SLOT_A/B live pointers, slot-2 superset, anchored tab taps, from-element strip paging, keychain wipe, deep-link cart, password-before-submit login, cart-side address + conditional create, Offers browse + search add. [2026-10-05T17:30+05:30] full-suite: gen_flows.select_option gains settle wait between option scroll and tap — taps during sheet-centering land on backdrop, silently closing with nothing selected (store "Owner is required" kill on fresh full run). [2026-10-05T18:38+05:30] scripts/clear-db.sql: add 5 tables missing vs live sqlite schema (diffed schema.ts sqliteTable names against script DROPs). Diff: + -- ---- regions (new: child-first) ---- + DROP TABLE IF EXISTS region_consts; (refs regions, region_bounds) + DROP TABLE IF EXISTS region_bounds; (refs regions) + DROP TABLE IF EXISTS region_telegram_creds; (refs regions) + DROP TABLE IF EXISTS regions; + -- in staff section, before staff_users: DROP TABLE IF EXISTS staff_notif_creds; (refs staff_users) Left untouched: 4 stale DROPs still in script but absent from schema (address_areas, address_zones, product_categories, user_notifications) — harmless under IF EXISTS. [2026-10-05T19:39+05:30] drizzle/0007_region_scoping.sql step 4 rewritten: DROP TABLE product_info fails on D1 (dashboard AND cli) with FK constraint — D1 enforces FKs and neuters defer_foreign_keys/foreign_keys=OFF pragmas, so the create-copy-drop-rename pattern dies at DROP while product_skus/product_reviews hold rows. Verified in-memory: DROP TABLE parent fails (exit 19), DROP COLUMN on FK-child col succeeds, ADD..REFERENCES..NOT NULL DEFAULT rejected, no ALTER COLUMN in SQLite. New approach (user-designed, extended one level): rebuild the full 13-table FK subgraph with NOT NULL preserved — __new_product_info, __new_product_skus, __new_product_reviews, 9 sku-children, plus coupon_usage (found via schema.ts audit: coupon_usage.order_item_id refs order_items, so order_items is not a leaf). Leaves drop freely; mids drop once unreferenced; renames auto-rewrite child FK clauses (verified). Two deviations from drizzle-kit rendering, both required: rating_check CHECK written unqualified (RENAME does not rewrite CHECK exprs — qualified name would dangle), __new_ FKs point at __new_ names (rewritten to final on rename). Index creation moved after renames (names freed by drops). Old step 5 (market_stats unique swap) removed — subsumed by the rebuild. PRE-FLIGHT REQUIRED on live target before apply: SELECT type,name FROM sqlite_master WHERE (sql LIKE '%product_skus%' OR sql LIKE '%product_info%') AND name NOT LIKE 'sqlite_%' must show only known tables+indexes (no legacy/views/triggers). [2026-10-05T19:52+05:30] docs/recreate-referenced-table.md: new doc capturing the D1 FK-rebuild pattern (why DROP dies on D1, leaves-first subgraph rebuild, pre-flight query, CHECK/index/rename pitfalls, proof harness). Written for reuse the next time a referenced table must be re-created. [2026-10-05T20:05+05:30] Phase A1 web parity: testID support in select primitives, mirroring native BottomDropdown convention ({testID}, {testID}-search, {testID}-option-{value}, {testID}-done). web-components Dropdown gains testID prop (wrapper data-testid + per-option IDs); SearchBar gains testID + autoCorrect/autoCapitalize passthrough (defaults off/none, as native); admin-web SearchableSelect/MultiSelect thread {testID}-search/option/done IDs (replacing generic multiselect-option). [2026-10-05T20:18+05:30] Phase A2 web parity: admin-web customize-app hub gains bound scoping identical to admin-ui (getMyRegionBounds + activeBoundId/boundsReady, enabled-gated getConstants({boundId}), updateConstants({boundId}), const-bound-tabs/tab-{id} testIDs, Formik key remount). CONST_LABELS/VISIBILITY aligned to native canonical set (adds internalAppVersion label; platformFeePercent/minOrderAmountForCoupon/flashDeliverySlotId/versionNum/playStoreUrl/appStoreUrl/popularItems hidden as on native). popular/ordering sub-screens left unscoped on both apps (native navigates without bound param). [2026-10-05T20:27+05:30] Phase A3 web parity: data-testid hooks mirroring native testIDs — StoreForm (store-name-input/description-input/owner-dropdown/products-selector/submit-button), TagForm (7 IDs), ProductForm (native names incl. -dropdown/create-product-button renames), SlotForm snippet selector, const-bound-style tabs n/a; OrderOptionsMenu welcome row (welcomeMessage + isFirstOrder send-welcome-msg); BannerForm autoCapitalize/autoCorrect; add-product-button + edit-slot-fab IDs on index/detail routes. [2026-10-05T20:45+05:30] Phase B web parity (web-ui): data-testid hooks mirroring native (tag-tab-/tag-grid-/tag-show-more-/tag-product-/slot-card-/search-input, ProductCard variant+badges, address-option-, select-address-error/place-order-button, login/register IDs); behavior fixes — freezeTime slot filtering (home sortedSlots + AddToCartDialog), slots-load guard on product sort, NextOrderGlimpse on home, logout clears query cache, ProtectedRoute preserves query params + covers /home/checkout. [2026-10-05T21:10+05:30] Phase C1 web parity: RegionContext port (localStorage-backed active_region, getRegions ghost validation, useRegion/useRegionParams) + wire into __root above AuthProvider; prominent-api-hooks useGetEssentialConsts scoped to {regionId,boundId} with cachePathPrefix + build*CacheUrl helpers. [2026-10-05T21:28+05:30] Phase C2 web parity: RegionGate port (browser geolocation + visibilitychange re-check, resolveRegionForLocation auto-pass, region-gate-*/region-pick-* testIDs, stored-region continue) mounted in AppLayout; RegionBar port (region-bar testID, collapsible) placed on home above Explore Products. [2026-10-05T22:10+05:30] Phase D web parity start: cart/checkout depth (slot grouping + per-item pickers, cart address section, slot-grouped checkout URLs, coupon/threshold logic, QuickDeliveryAddressSelector, order-success glimpse). [2026-10-05T22:40+05:30] RegionGate infinite-loading fix (user-ui + web-ui): full-screen spinner reflashed on every re-detection because render had no settled memory. Gate now tracks settledRef (first detection completion) — background re-runs keep the current blocked/picker screen instead of flashing loading; flags only reset on the initial run. AppState/visibility-triggered re-runs gain a 15s cooldown; settings-return bypasses it via expectReturnRef so the grant-permission flow still re-checks immediately. [2026-10-06T00:01+05:30] superadmin scope work: new superadmins table (id autoincrement PK, name UNIQUE NOT NULL, password NOT NULL, created_at; no region_id/role — global by definition) in db_helper_sqlite + db_helper_postgres schemas; drizzle migration 0008 (CREATE TABLE only); backend ctx.superadmin ({superadminId} JWT claim) + superadminProcedure + src/trpc/apis/superadmin-apis/ (auth.login + thin wrappers for the 9 other procedures superadmin-ui uses, unscoped) merged as superadmin router; superadmin-ui client switched admin.* -> superadmin.*. admin.* untouched. Bootstrap: manual SQL INSERT with bcryptjs hash (cost 10). [2026-10-06T00:20+05:30] all-region stores work: E2E audit — full-suite gen_flows.py product_flow asserts product-all-regions-checkbox visible+unchecked (E2E admin role is 'admin', so hiding the checkbox requires dropping those generator steps; gen/*.yaml regenerate per run.sh so only the generator changes). regions/admin-product-search.yaml only needs an all-regions product to EXIST (no checkbox interaction — safe). Plan: hide flag in admin-ui/admin-web ProductForm for all roles, gen_flows.py steps removed, admin.product 403 on flag=true (superadmin scope only). [2026-10-06T00:35+05:30] all-region stores Phase 1+2: proof_0009 passes; schema storeInfo regionId nullable + availableInAllRegions; migration 0009 (2-table rebuild, verified verbatim, 9 statements); shared CreateStoreInput/UpdateStoreInput gain availableInAllRegions?; read-path OR-flag: getAllStores scoped branch, getAllStoresForCache, getStoreSummaries, getStoreDetail; createStore/updateStore accept nullable region + flag, market-stats product assignment spans all regions for regionless stores. [2026-10-06T01:10+05:30] all-region stores Phase 3-5: superadmin.store/product/staffUser.getStaff/upload procs (product create requires creator regionId; update/delete/toggle mirrored; getAllSkusSummary unscoped); admin.store/admin.product 403 on all-regions flag create/flip/delete (superadmin scope only); per-region ops (OOS/suspend/prices) untouched. superadmin-ui stores+products sections (list/new/edit, AppShell nav, copied+adapted StoreForm/ProductForm/ProductsSelector/MultiSelect/SearchableSelect/upload hook; routeTree regenerated via vite dev). Admin-ui/admin-web ProductForm flag hidden for all roles (all-region edits read-only banner + disabled save); gen_flows.py checkbox steps removed (gen YAMLs regenerate per run.sh). tsc clean: backend, superadmin-ui, admin-web, admin-ui, web-ui. NOTE: postgres skipped per user. [2026-10-05 23:58:50] Add scripts/delete-orders-before.sql (apps/backend/scripts). New file apps/backend/scripts/delete-orders-before.sql: - Deletes orders with created_at < a single editable cutoff (helper table _old_orders holds {id, payment_info_id}; dropped at start and end so re-runs are fresh), plus dependent rows child-first because D1 enforces FKs without defer: coupon_usage (order_id OR order_item_id subselect), complaints, user_incidents, payments, refunds, order_status, order_items, orders; optional orphaned payment_info cleanup (step 5, kept on by default). - Header documents date formats (ISO '2026-01-01' recommended; full 'T...Z' timestamp also accepted), run command, and backup warning. [2026-10-06T01:30+05:30] superadmin-ui tabbed sections: products + stores lists gain Global-first tab strips (global = availableInAllRegions only; region tabs = that region's exclusive products/stores); regions via getRegions; *-tab-*/grid testIDs. [2026-10-06 00:04:56] Spell out the ordered date components in delete-orders-before.sql header. apps/backend/scripts/delete-orders-before.sql: - DATE FORMAT comment now explains each placeholder position explicitly: 'YYYY(=2026)-MM(=01 month)-DD(=01 day)' with an example mapping 25 Mar 2024 -> '2024-03-25'. [2026-10-06T01:45+05:30] superadmin-ui products edit: global-product price edits threw 'regionId is required' (db scopes writes to one creatorRegionId row; all-regions mode sends regionId null). Edit route now falls back to first region, matching create-route rule; other regions' rows untouched. [2026-10-06T02:05+05:30] admin-ui ProductForm regional global-edit: removed create-global traces already; now regional staff CAN edit global products scoped to own region (banner reworded, per-region store UI collapsed to staff region only with name-match prefill, validation scoped to own region, save re-enabled). super_admin role keeps full per-region UI. Backend already scopes writes via writeRegion (no change). all-region stores included in region store lists. [2026-10-06T02:20+05:30] admin-ui product edit fix: global-product save crashed zod (regionId null vs optional number). Route now sends regionId ?? undefined; backend writeRegion falls back to staffer region = desired regional scoping. [2026-10-06T02:35+05:30] user-ui: console.log constructed cache URLs in buildProductsCacheUrl/buildAvailabilityCacheUrl/buildSlotsCacheUrl (single choke point for all callers). [2026-10-06T01:05+05:30] cache URL segment swap fix: client built {region}{key}/v-... but writer/R2 use {key}/{region}v-... (proven live: writer path 200, client path 404; invisible on region 1 where prefix is empty). Fixed buildProductsCacheUrl + store-products URL in user-ui and web-ui builders; availability/slots were already correct. [2026-10-06T02:00+05:30] superadmin product form restructure: RegionSkuStats type + db create/update per-region overlay + superadmin zod; form split into product-info section, stat-less variant cards, and region-tabbed pricing/availability with match-for-all (default checked on create). [2026-10-06T09:30+05:30] neo-tests/e2e scaffold (new tests, tests/ untouched): Maestro MCP (stdio, device chromium) web flows for superadmin-ui region check. MBNR verified pre-existing via API (region 1 Mahabubnagar, bounds Mbnr-1 p1 + Mbnr-2 p2, coordinates match map-assets exactly) so UI flow is verify-only; create branch runs only if Mahabubnagar card missing. neo-tests/e2e/mbnr-region-verify.yaml: - url header http://localhost:4175/login + launchApp clearState, tapOn placeholder fields (Enter your name / Enter your password), inputText creds, tapOn Login, assert Regions, openLink /regions, assert Mahabubnagar. neo-tests/e2e/mbnr-region-create.yaml: - Same login, then /regions/new: name Mahabubnagar, description, 2 bounds (Mbnr-1 p1 / Mbnr-2 p2, compact Polygon geojson from map-assets), Add Bound for second, telegram cred from env TG_TOKEN/TG_CHAT, Create Region, assert Mahabubnagar card. [2026-10-06T09:45+05:30] neo-tests/e2e: assertVisible timeout property rejected by Maestro 2.7.0 schema (Unknown Property: timeout); reverted to plain string asserts in both flows. [2026-10-06T09:50+05:30] superadmin-ui admins: Create Admin becomes full admin management (list + new + edit + delete). Backend staff-user.ts gains updateStaffUserInfo (rename unique-checked, role, region, optional bcrypt-12 password reset) + deleteStaffUser (deletes staff_notif_creds; 409 blocks when staff owns stores / created coupons+reserved / filed incidents). Router: getStaff enriched with role+region names; new updateStaffUser/deleteStaffUser procs. UI: /admins list cards (name, role, region, Edit/Delete), /admins/new (moved form), /admins/$id/edit (prefill + optional new-password), nav renamed Admins, routeTree regen. [2026-10-06T10:05+05:30] admins CRUD verified: local backend (wrangler dev, dev D1) getStaff returns roleId/roleName/regionName; create temp id 8, update rename+region+password, staff login with new password OK, delete qusham blocked 'they own 1 store...', temp deleted and gone. UI via Maestro MCP Chrome: list + edit prefill render (role/region names blank until backend deploy since devapi runs old code). Fixed double AppShell on /admins/new + /admins/$id/edit (parent layout already wraps; matches regions convention). [2026-10-06T10:20+05:30] neo-tests/e2e/ensure-init-regions.yaml (new, Maestro flow per user): login via SUPERADMIN_NAME/PASSWORD env, guarded region blocks (Mahabubnagar Mbnr-1 p1 + Mbnr-2 p2 compact geometry embedded; Jadcherla single bound from jcl.geojson; TG_TOKEN/TG_CHAT env only on create path), guarded admin blocks (mbnradmin/mbnradmiN123 admin+Mahabubnagar, jcladmin/jcladmiN123 admin+Jadcherla; existing left untouched). Targets whatever backend superadmin-ui points at (now local http://192.168.1.5:8787 via shared default). [2026-10-06T10:35+05:30] Maestro web inputText bug root-caused: inputText resolves target via createXPathFromElement, which uses id else class. Add-admin inputs had no id and shared wrapper class 'mb-4' + same input class, so xpath was ambiguous and typed password into the Name field (login worked only because its wrappers were classless/positional). Fix: add stable ids to superadmin-ui admin + region create/edit form controls and tap by id in neo-tests/e2e/ensure-init-regions.yaml. Files: apps/superadmin-ui/src/routes/admins.new.tsx, admins.$id.edit.tsx, regions.new.tsx, regions.$id.edit.tsx; neo-tests/e2e/ensure-init-regions.yaml. [2026-10-06T10:50+05:30] neo-tests/e2e/create-mbnr-admin.yaml (new): dedicated flow to create an admin in Mahabubnagar via id-based field targeting, then verify the card on /admins. Note: reuse of a single MCP server session keeps one Chrome window alive across tools/call; spawning a new `maestro mcp` per call creates a fresh Chrome/profile. [2026-10-06T11:00+05:30] Maestro web native