16 KiB
Plan — Part 1/2: Backend + Admin UIs (three-table consts model)
Part 1 of 2. Covers the DB model, KV, migration, backend, and the admin UIs
(apps/admin-ui, apps/admin-web, apps/superadmin-ui). Part 2 covers apps/user-ui
(see consts-three-tables-part2-user-ui.md). Supersedes three-table-consts-model.md.
0. Decisions
- Scope Part 1: backend + admin-ui + admin-web + superadmin-ui.
allItemsOrderis region-scoped (one row per region inregion_consts), grouped withpopularItems.- Leftover keys stay in
key_val_store:platformFeePercent,taxRate,tester,minOrderAmountForCoupon,maxCouponDiscount,flashDeliverySlotId,readableOrderId,tagsOrder. region_cache_versions+region_bound_settingsare dropped after data copy.- Precomputed flat JSON per bound in the KV gen namespace (§2) — consumed by user-ui (Part 2).
- AGENTS.md: do NOT run migrations (user runs), do NOT run the test suite, do NOT use git.
Append planned diffs + timestamp to
change-log.txtbefore editing non-.md/.txtfiles.
1. Data model
New tables (packages/db_helper_sqlite/src/db/schema.ts):
global_consts (key TEXT PRIMARY KEY, value TEXT)
region_consts (region_id INTEGER FK->regions.id, key TEXT, value TEXT, PK(region_id,key))
region_bound_consts (bound_id INTEGER FK->region_bounds.id, region_id INTEGER FK->regions.id,
key TEXT, value TEXT, PK(bound_id,key))
| Table | Keys |
|---|---|
global_consts |
versionNum, playStoreUrl, appStoreUrl, internalAppVersion |
region_consts |
products_version_num (was cache_version), availability_version_num, slots_version_num, popularItems, allItemsOrder, isFlashDeliveryEnabled, supportMobile, supportEmail, welcomeMessage |
region_bound_consts |
minRegularOrderValue, freeDeliveryThreshold, deliveryCharge, flashFreeDeliveryThreshold, flashDeliveryCharge |
key_val_store (kept) |
platformFeePercent, taxRate, tester, minOrderAmountForCoupon, maxCouponDiscount, flashDeliverySlotId, readableOrderId, tagsOrder |
- Region-level keys are one row per region (no bound precedence). Bound-level keys stay per bound.
- Version counters (
products_version_num/availability_version_num/slots_version_num) live inregion_consts, auto-created default 1. allItemsOrder: exactly one row per region; identical for every bound in that region.
2. KV model
- Key
essentialConsts_{boundId}infreshyo_gen/freshyo_gen_dev. Flat value ={ ...global, ...region, ...bound, assetsDomain, apiCacheKey, regionId, boundId, webviewHtml, isWebviewClosable }. - Numbers/booleans coerced (
Number()/ boolean) at build time; other values raw strings.
3. Migration (author only — user runs)
packages/db_helper_sqlite/drizzle/0009_three_const_tables.sql + journal idx 9
(0009_three_const_tables). Steps: CREATE the 3 tables; copy global_consts (4 keys) from
key_val_store; copy region_consts version counters from region_cache_versions and region
business keys (incl. allItemsOrder) from each region's lowest-priority bound's
region_bound_settings; copy the 5 bound keys into region_bound_consts; DELETE the migrated keys
from key_val_store (keep the 8 leftovers); DROP region_bound_settings + region_cache_versions.
(full SQL is in docs/consts-three-tables-changes.md §2.2 — reuse it verbatim.)
4. Backend
4.1 packages/db_helper_sqlite
src/db/schema.ts: addglobalConsts,regionConsts,regionBoundConsts; removeregionCacheVersions+regionBoundSettingsand their relations.src/lib/const-keys.ts: addGLOBAL_CONST_KEYS,REGION_CONST_KEYS,BOUND_CONST_KEYS,LEGACY_CONST_KEYS; keep mergedCONST_KEYS+ labels/types/visibility/defaults; addproducts_version_num; addCONST_SCOPE(global|region|bound|legacy).src/admin-apis/const.ts:- add
getAllGlobalConsts(),upsertGlobalConsts(rows),getRegionConsts(regionId),upsertRegionConsts(regionId, rows),getBoundConsts(boundId),upsertBoundConsts(boundId, regionId, rows),getLegacyConsts(),upsertLegacyConsts(rows). - keep
getAllConstants/upsertConstantsworking:getAllConstants()= merged global+legacy (+CONST_DEFAULTS);upsertConstants(rows, regionId?)routes byCONST_SCOPE. - remove the dead global counters (
get/incrementCacheVersion, availability, slots).
- add
src/lib/region-cache-versions.ts: back it withregion_consts(products_version_num/availability_version_num/slots_version_num), auto-create rows; public signatures/return type unchanged (cloud_cache.tsuntouched).src/superadmin-apis/regions.ts:getBoundSettings(boundId)→region_bound_constsonly (5 keys),Record<string,string|null>.upsertBoundSettings(boundId, settings)→region_bound_consts(look up regionId from bound).- add
getRegionConstants(regionId)/upsertRegionConstants(regionId, rows). getEffectiveRegionSettings(regionId)→ merged region + effective bound (shape unchanged).- add
getEffectiveBoundId(regionId);getAllRegions()→ addeffectiveBoundId. createRegionWithBounds/createRegionBound→ seed default rows + version counters (1/1/1).
src/db/seed.ts+src/db/seed.sql: seed the 3 tables (incl. per-regionallItemsOrder); leftovers keep going tokey_val_store.index.ts: export the new helpers; drop removed ones.
4.2 packages/shared
types/region.types.ts:RegionSummary.effectiveBoundId?: number | null.types/const.types.ts: unchanged (Constant,ConstantUpdateResult); optional addGlobalConstKey/RegionConstKey/BoundConstKeyunion types if useful to the UIs.
4.3 apps/backend core
src/lib/const-keys.ts: mirror the four key groups (allItemsOrderinREGION_CONST_KEYS).src/lib/const-store.ts:getGlobalConstValues(),getRegionConstValues(regionId),getBoundConstValues(boundId);getConstant(key)(tagsOrder) stays onkey_val_store.src/lib/gen-store.ts:GEN_KV_KEY='essentialConsts',genKvKeyForBound(boundId),refreshGenKv(boundId?),refreshGenKvForRegion(regionId),readEssentialConstsFromKv(boundId).src/trpc/apis/common-apis/common-trpc-index.ts:scaffoldEssentialConsts(boundId);essentialConstsinput{ boundId };listRegionsreturnseffectiveBoundId;regionSettingsmerged.src/lib/cloud_cache.ts:refreshGenKvForRegion(regionId); essential-consts CDN file uses the effective bound.src/lib/flash-delivery-cron.ts:isFlashDeliveryEnablednow region-level → writeregion_constsfor all regions, thenrefreshGenKv().src/lib/seed.ts: new db seeds +refreshGenKv().src/sqliteImporter.ts: re-export new helpers.
4.4 tRPC endpoint surface (new / repointed)
Keep old admin.const.getConstants/updateConstants as backward-compat aliases (tests at
apps/backend/tests/helpers/consts.ts + any stragglers). Add clean, scoped endpoints:
| Endpoint | Kind | Scope | Notes |
|---|---|---|---|
admin.const.getGlobalConstants / updateGlobalConstants |
query/mutation | staff | global_consts (4 keys) |
admin.const.getLegacyConstants / updateLegacyConstants |
query/mutation | staff | key_val_store leftovers (tagsOrder, coupons, etc.) |
admin.const.getConstants / updateConstants |
query/mutation | staff | alias: merged global+legacy; update routes by scope |
admin.region.getRegionConstants / updateRegionConstants |
query/mutation | staff region | region_consts for ctx.staffUser.regionId |
admin.region.getBoundSettings / updateBoundSettings |
query/mutation | staff region | region_bound_consts (5 keys); add refreshGenKvForRegion after write |
superadmin.const.getGlobalConstants / updateGlobalConstants |
query/mutation | superadmin | NEW router (fixes the current admin.const guard mismatch) |
superadmin.const.getLegacyConstants / updateLegacyConstants |
query/mutation | superadmin | leftovers |
superadmin.regions.getRegionConstants / updateRegionConstants |
query/mutation | superadmin | { regionId } + constants |
superadmin.regions.boundSettings / updateBoundSettings |
query/mutation | superadmin | repointed to region_bound_consts; refreshGenKvForRegion |
update*handlers validate keys against their group (GLOBAL_CONST_KEYS/REGION_CONST_KEYS/BOUND_CONST_KEYS/LEGACY_CONST_KEYS) and refresh KV for the affected scope.admin.region.updateRegionConstantsandsuperadmin.regions.updateRegionConstantstakingisFlashDeliveryEnabled/etc. mustrefreshGenKvForRegion(regionId).- Version-counter keys (
products_version_num, etc.) are not editable via these endpoints (read-only ingetRegionConstants, ignored on write).
4.5 apps/backend routers to edit
src/trpc/apis/admin-apis/apis/const.ts— new global/legacy procedures + alias.src/trpc/apis/admin-apis/apis/region.ts—getRegionConstants/updateRegionConstants;getBoundSettings/updateBoundSettings→ bound table + KV refresh.src/trpc/apis/superadmin-apis/apis/regions.ts— bound settings repoint + region constants +refreshGenKvForRegion.- new
src/trpc/apis/superadmin-apis/apis/const.ts(superadminConstRouter) + register insuperadmin-apis/superadmin-trpc-index.ts. src/trpc/apis/admin-apis/apis/admin-trpc-index.ts— const router still mounted; nothing new needed beyond procedure additions.
5. Admin UI — apps/admin-ui
All key maps are local in app/(drawer)/dashboard/customize-app/index.tsx
(CONST_LABELS 11–33, CONST_VISIBILITY 35–58, BOUND_KEY_TYPES 61–75, REGIONAL_KEYS 77,
parseBoundValue 80–102, serializeBoundValue 105–120, local ConstantInput 122–261).
5.1 customize-app/index.tsx
- Replace the 2-way switch (
mode: 'bounds' | 'global', line 265) with 3 tabs: Global / Region / Bound. - Global tab →
admin.const.getGlobalConstants/updateGlobalConstants; rows = the 4GLOBAL_CONST_KEYS(visibility-controlled) + a "Legacy" subsection foradmin.const.getLegacyConstants(only if you wanttagsOrder/coupon keys exposed; otherwise omit). - Region tab →
admin.region.getRegionConstants/updateRegionConstants; rows =REGION_CONST_KEYSminus the 3 version counters (display-only).popularItems/allItemsOrderkeepallowSectionNavigationlinks to their editors (§5.2). - Bound tab → keep the existing per-bound tabs + Formik, but
REGIONAL_KEYSshrinks to the 5BOUND_CONST_KEYS(minRegularOrderValue,freeDeliveryThreshold,deliveryCharge,flashFreeDeliveryThreshold,flashDeliveryCharge) viaadmin.region.getBoundSettings/updateBoundSettings. Remove the 6 region-level keys fromBOUND_KEY_TYPES. - Rebuild
CONST_LABELS/CONST_VISIBILITY/type maps from the key groups (or import a small shared keys module — see §5.5); keep the localConstantInput(incl.allowSectionNavigation).
5.2 customize-app/popular-items.tsx + all-items-order.tsx
- These are now region-scoped (
region_consts): switch reads/writes fromadmin.const.*toadmin.region.getRegionConstants/updateRegionConstants(same{ key, value:number[] }payload; keep the array-or-CSV parse). Invalidateregion.getRegionConstants.
5.3 product-tags/order.tsx
tagsOrderstays a global leftover inkey_val_store→ switch toadmin.const.getLegacyConstants/updateLegacyConstants(payload unchanged; still triggersscheduleStoreInitialization()server-side).
5.4 components/OrderOptionsMenu.tsx
welcomeMessageis now inregion_consts→ read it fromadmin.region.getRegionConstantsinstead ofadmin.const.getConstants.
5.5 (optional) shared keys module
- Consider extracting the key groups + labels into a small
apps/admin-ui/src/constants/const-keys.tsto stop the label/visibility drift; not required.
6. Admin UI — apps/admin-web
Mirror of admin-ui (single file src/routes/dashboard.customize-app.tsx: CONST_LABELS 14–35,
CONST_VISIBILITY 37–59, BOUND_KEY_TYPES 64–76, REGIONAL_KEYS 78, local ConstantInput 123–256).
dashboard.customize-app.tsx: 3 tabs (Global/Region/Bound) as §5.1;handleBoundSubmit(323–354) writes the 5 bound keys;handleGlobalSubmit(356–383) writes global (+ legacy).dashboard.customize-app.popular.tsx(110–204) and.ordering.tsx(97–183): switch toadmin.region.getRegionConstants/updateRegionConstants; invalidate that key.dashboard.product-tags.order.tsx(90–174): switch toadmin.const.getLegacyConstants/updateLegacyConstants.- Keep the local
ConstantInput+allowSectionNavigation.
7. Admin UI — apps/superadmin-ui
src/routes/constants.tsx: currently callsadmin.const.*under a superadmin token, which isprotectedProcedure→ UNAUTHORIZED. Switch to the newsuperadmin.const.*(getGlobalConstants/updateGlobalConstants+getLegacyConstants/updateLegacyConstants). Split the single form into Global (+ Legacy) sections; drop the region/bound keys from this screen (they move to the Regions page).src/routes/regions.tsx:SETTING_KEYS(18–30) currently mixes region keys + bound keys. Split into:- Region constants editor (new
RegionConstantsEditor) usingsuperadmin.regions.getRegionConstants/updateRegionConstants({ regionId })for the region keys (popularItems, allItemsOrder, isFlashDeliveryEnabled, supportMobile, supportEmail, welcomeMessage). - Bound constants editor (
BoundSettingsEditor, 383–436) usesSETTING_KEYSreduced to the 5 bound keys viasuperadmin.regions.boundSettings/updateBoundSettings.
- Region constants editor (new
- Keep the
EFFECTIVEbadge logic (bounds sorted by priority; effective = first).
8. Out of scope (Part 1)
apps/user-ui— Part 2.apps/web-uistorefront — still callscommon.essentialConsts({ regionId })and will fail input validation once the input becomes{ boundId }. Not migrated here; flagged. (Optional follow-up: accept{ regionId }and map viagetEffectiveBoundId(regionId).)
9. Verification
- Append planned diffs + timestamp to
change-log.txtfirst. - Typecheck:
npx tsc --noEmit --project packages/db_helper_sqlite/tsconfig.json,... apps/backend/tsconfig.json,... apps/admin-ui/tsconfig.json,... apps/superadmin-ui/tsconfig.json,... apps/admin-web/tsconfig.json(admin-web package has its owntypecheckscript). - After migration 0009: verify the three tables populated,
key_val_storekeeps the 8 leftovers, exactly oneallItemsOrderper region. - Endpoints:
admin.const.getGlobalConstants(4 keys),admin.region.getRegionConstants(9 keys, versions read-only),admin.region.getBoundSettings(5 keys);superadmin.const.*works with a superadmin token; writes refresh KV (essentialConsts_{boundId}infreshyo_gen). - Admin smoke: Global/Region/Bound tabs save to the correct tables; popular/all-items edits hit
region_consts; tagsOrder edit still triggers cache regeneration.
10. Checklist
change-log.txt— append planned diffs.packages/db_helper_sqlite: schema,0009migration + journal, const-keys, admin-apis/const, region-cache-versions, superadmin-apis/regions, seed, index exports.packages/shared:region.types.ts(effectiveBoundId).apps/backend: const-keys, const-store, gen-store, common-trpc-index, cloud_cache, flash-delivery-cron, seed, sqliteImporter, admin const/region routers, superadmin regions router, new superadmin const router.apps/admin-ui: customize-app (3 tabs), popular-items, all-items-order, product-tags/order, OrderOptionsMenu.apps/admin-web: customize-app (3 tabs), popular, ordering, product-tags/order.apps/superadmin-ui: constants.tsx (superadmin.const.*), regions.tsx (region + bound editors).- Typecheck all five projects; fix self-introduced errors.