3474 lines
207 KiB
Text
3474 lines
207 KiB
Text
[2026-10-07 13:00:00] BACKEND per-region storefront cache generation (fixed contract; UI clients done by a second agent).
|
||
|
||
Planned diffs (backend + db_helper only; NO UI app touched; NO migration run; NO tests):
|
||
|
||
packages/shared/types/region.types.ts
|
||
- Add RegionCacheVersions { regionId, cacheVersion, availabilityVersionNum, slotsVersionNum }.
|
||
|
||
packages/db_helper_sqlite/src/db/schema.ts
|
||
- New table regionCacheVersions (region_id NOT NULL UNIQUE FK->regions.id,
|
||
cache_version / availability_version_num / slots_version_num NOT NULL DEFAULT 1).
|
||
|
||
packages/db_helper_sqlite/drizzle/0008_region_cache_versions.sql (new, NOT run)
|
||
- CREATE TABLE IF NOT EXISTS + UNIQUE index + INSERT seed row per existing region.
|
||
packages/db_helper_sqlite/drizzle/meta/_journal.json
|
||
- Append journal entry idx 8 -> 0008_region_cache_versions.
|
||
|
||
packages/db_helper_sqlite/src/lib/region-cache-versions.ts (new)
|
||
- getRegionCacheVersions(regionId) (auto-creates row when missing),
|
||
incrementRegionCacheVersion / incrementRegionAvailabilityVersionNum /
|
||
incrementRegionSlotsVersionNum. Global key_val_store counters untouched.
|
||
packages/db_helper_sqlite/index.ts — export the four helpers.
|
||
|
||
packages/db_helper_sqlite/src/stores/store-helpers.ts
|
||
- regionId FIRST param on getAllProductsForCache, getAvailabilityForCache,
|
||
getAllStoresForCache, getAllDeliverySlotsForCache, getAllSpecialDealsForCache,
|
||
getAllProductTagsForCache, getAllTagsForCache, getAllTagProductMappings,
|
||
getAllSlotsWithProductsForCache, getAllBannersForCache
|
||
(+ getAllProductCombosForCache, same treatment — needed so combo rows stay
|
||
in-region; not in the contract list, reported).
|
||
- SQL where region_id on region-owned tables; JS-filter SKU-linked rows via the
|
||
parent product_info.region_id; banner skuIds / slot skuIds / tag relatedStores
|
||
filtered to in-region ids.
|
||
packages/db_helper_sqlite/src/user-apis/stores.ts
|
||
- getStoreSummaries(regionId, ...), getStoreDetail(regionId, storeId) (null
|
||
outside region), getStoresSummary(regionId).
|
||
packages/db_helper_sqlite/src/user-apis/banners.ts — getActiveBanners(regionId).
|
||
packages/db_helper_sqlite/src/user-apis/slots.ts
|
||
- getActiveSlotsList(regionId), getProductAvailability(regionId, in-region SKUs).
|
||
packages/db_helper_sqlite/src/user-apis/product.ts
|
||
- getSuspendedSkuIds(regionId); new getSkuRegionId/getSkuRegionIds (server-side
|
||
SKU->region resolution for region-less live user endpoints; no client trust).
|
||
apps/backend/src/sqliteImporter.ts — re-export new/changed helpers.
|
||
|
||
apps/backend/src/trpc/apis/common-apis/common.ts
|
||
- scaffoldProducts(regionId): reads scoped DB helper directly (NOT the
|
||
in-memory product-store); nextDeliveryDate = latest in-region slot per SKU
|
||
(matches old DESC semantics); tags/mappings scoped; images signed.
|
||
- scaffoldAvailability(regionId). getAllProductsSummary keeps no-input shape
|
||
for admin UIs (untouched apps) by aggregating per-region scaffolds (reported).
|
||
apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
|
||
- scaffoldEssentialConsts(regionId): global consts + region's three versions +
|
||
assetsDomain/apiCacheKey + regionId + regionSettings via
|
||
getEffectiveRegionSettings. essentialConsts now REQUIRES {regionId} input
|
||
(UI callers cannot be updated here — reported for the client agent).
|
||
- getStoresSummary endpoint keeps no-input shape via per-region aggregation
|
||
(reported).
|
||
apps/backend/src/trpc/apis/user-apis/apis/stores.ts
|
||
- scaffoldStores(regionId), scaffoldStoreWithProducts(regionId, storeId)
|
||
(404/NOT_FOUND outside region).
|
||
apps/backend/src/trpc/apis/user-apis/apis/slots.ts
|
||
- scaffoldSlotsWithProducts(regionId) via scoped DB helper directly
|
||
(slot-store NOT keyed by region); getSlots endpoint aggregates per region.
|
||
apps/backend/src/trpc/apis/user-apis/apis/banners.ts — scaffoldBanners(regionId).
|
||
apps/backend/src/trpc/apis/user-apis/apis/product.ts + cart.ts (live, region-less)
|
||
- Resolve region server-side per requested SKU ids, then call region-keyed
|
||
in-memory stores (no client-region trust).
|
||
apps/backend/src/stores/product-store.ts + slot-store.ts
|
||
- regionId FIRST param on initialize*/getAll*/get*/getMultipleProductsSlots.
|
||
apps/backend/src/stores/product-tag-store.ts + banner-store.ts
|
||
- initialize*(regionId).
|
||
apps/backend/src/lib/gen-store.ts
|
||
- KV key `essential_consts:{regionId}`; refreshGenKv(regionId?) (no-arg =
|
||
all regions, kept for seed/flash/const callers); readEssentialConstsFromKv
|
||
requires regionId (throws when missing — no silent global fallback).
|
||
apps/backend/src/lib/cloud_cache.ts
|
||
- createRegionCacheFiles(regionId) writing ONLY per-region paths
|
||
({key}/regions/{id}/v-{cv}/products|stores|banners|essential-consts.json +
|
||
stores/{storeId}.json, regions/{id}/av-{av}/availability.json,
|
||
regions/{id}/slots/v-{sv}/slots.json); per-region purge + KV mirror.
|
||
- createAllCacheFiles(regionId?) iterates all regions (or one); GLOBAL file
|
||
generation REMOVED (all known consumers are the UI cache hooks being migrated
|
||
by the client agent; backend tests also read them — reported, not updated).
|
||
- createSlotsCacheFile(regionId, refresh) / createAvailabilityCacheFile(regionId,
|
||
refresh) — admin slots/product routers pass ctx.staffUser region.
|
||
apps/backend/src/stores/store-initializer.ts
|
||
- initializeAllStores(regionId?) resolves target regions (one or all) and
|
||
inits each; scheduleStoreInitialization(regionId?) forwards region to the DO.
|
||
apps/backend/src/jobs/cache-creator.ts (CacheCreator DO)
|
||
- schedule(regionId?) accumulates pendingRegions; alarm drains them (all-region
|
||
when empty). No global mutable current-region.
|
||
apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts
|
||
- create: fire-and-forget createRegionCacheFiles(newRegion.id) with error log.
|
||
apps/backend/src/trpc/apis/admin-apis/apis/{store,banner,product,slots}.ts
|
||
- Pass ctx.staffUser region into scheduleStoreInitialization /
|
||
createSlotsCacheFile / createAvailabilityCacheFile.
|
||
|
||
In-memory store decision: scaffolds read the scoped DB helpers directly; the
|
||
in-memory stores (product/slot) are keyed by region (regionId first param) and
|
||
live region-less user endpoints resolve the region server-side from SKU ids.
|
||
Global-files: REMOVED (see above).
|
||
Typecheck: tsc --noEmit for db_helper_sqlite + backend; fix own errors.
|
||
|
||
[2026-10-07 00:34:48] sqlite drizzle query logging — enable SQL logging on the current D1 instance.
|
||
|
||
File: packages/db_helper_sqlite/src/db/db_index.ts
|
||
Diff plan:
|
||
- Add isQueryLoggingDisabled() helper reading (globalThis as any).ENV?.DRIZZLE_LOG
|
||
?? (globalThis as any).process?.env?.DRIZZLE_LOG (safe on Workers, no direct
|
||
process.env access). Logging is ON unless flag is false/'false'/'0'.
|
||
- Add queryLogger = { logQuery(query, params) } printing `[drizzle] <query>` + params
|
||
via console.log.
|
||
- Pass `logger` into drizzle(database, { schema, logger }) in initDb so every query
|
||
through the current instance is logged. Set DRIZZLE_LOG=false to silence.
|
||
|
||
[2026-10-07 10:11:12] Phase 1 (superadmin) — regions, bounds, bound settings, superadmin identities.
|
||
|
||
New migration 0006 plus a new superadmin API channel and superadmin UI. Planned diffs:
|
||
|
||
packages/db_helper_sqlite/src/db/schema.ts
|
||
- Add RegionGeoJson interface and tables regions, region_bounds,
|
||
region_bound_settings (region_id + bound_id + key + value), superadmins.
|
||
- Add relations for the above.
|
||
|
||
packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql (new)
|
||
- Create the four tables + unique indexes.
|
||
- Seed region "Mahabubnagar"; two bounds (Mbnr-1 priority 1, Mbnr-2 priority 2)
|
||
with exact GeoJSON; 11 bound settings rows per bound; bootstrap superadmin.
|
||
packages/db_helper_sqlite/drizzle/meta/_journal.json
|
||
- Append journal entry idx 6 -> 0006_regions_and_superadmins.
|
||
|
||
packages/db_helper_sqlite/src/superadmin-apis/regions.ts (new)
|
||
- Region/bound/settings persistence + effective-bound (lowest priority).
|
||
packages/db_helper_sqlite/src/superadmin-apis/auth.ts (new)
|
||
- Superadmin lookup.
|
||
packages/db_helper_sqlite/index.ts
|
||
- Export the new persistence helpers.
|
||
|
||
packages/shared/types/region.types.ts (new), superadmin.types.ts (new)
|
||
packages/shared/types/index.ts
|
||
- Re-export the new types.
|
||
|
||
apps/backend/src/trpc/trpc-index.ts
|
||
- Add superadmin context field and superadminProcedure guard.
|
||
apps/backend/src/app.ts
|
||
- Resolve superadmin identity from token (identityType/superadminId).
|
||
apps/backend/src/trpc/router.ts
|
||
- Register superadmin router.
|
||
apps/backend/src/trpc/apis/superadmin-apis/apis/{auth,regions,superadmin-trpc-index}.ts (new)
|
||
apps/backend/src/sqliteImporter.ts
|
||
- Re-export new superadmin/region helpers.
|
||
|
||
apps/superadmin-ui/src/lib/trpc-client.ts
|
||
- Use a separate superadmin_token storage key.
|
||
apps/superadmin-ui/src/lib/auth-context.tsx
|
||
- Authenticate via superadmin.auth (login/me).
|
||
apps/superadmin-ui/src/routes/login.tsx
|
||
- Superadmin username/password copy.
|
||
apps/superadmin-ui/src/routes/regions.tsx (new)
|
||
apps/superadmin-ui/src/routes/dashboard.tsx, src/components/AppShell.tsx
|
||
- Add Regions navigation.
|
||
apps/superadmin-ui/src/routeTree.gen.ts
|
||
- Register the /regions route (normally regenerated by the router plugin).
|
||
|
||
[2026-10-07 10:49:25] Phase 2 (staff/admin) — per-bound regional settings in admin-ui.
|
||
|
||
apps/admin-ui/components/context/staff-auth-context.tsx
|
||
- Extend the session `Staff` shape with optional `regionId: number | null`
|
||
(login already returns it); expose `regionId` on the auth context value.
|
||
- Capture regionId from the login response (setStaff(data.staff)).
|
||
- Non-breaking: existing consumers of `staff` keep working.
|
||
|
||
apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx
|
||
- Replace the single global constants form with one tab per region bound
|
||
(admin.region.bounds, ascending priority). Each tab shows the bound
|
||
description (or "Bound #id") + priority and marks the lowest-priority
|
||
bound as "Effective" (its settings apply to checkout).
|
||
- Selected bound loads admin.region.getBoundSettings and renders the 11
|
||
regional keys as editable inputs (reuse ConstantInput; add a
|
||
`allowSectionNavigation` prop so popularItems/allItemsOrder become inline
|
||
comma-separated inputs instead of links to the global editors).
|
||
- Save via admin.region.updateBoundSettings with only changed keys
|
||
(string|null values). Default-select lowest-priority bound; reinitialize
|
||
the form (Formik enableReinitialize + key) so drafts do not leak between
|
||
tabs. Loading / error / "no bounds configured" states.
|
||
- Keep the existing global constants form reachable via a top-level
|
||
"Regional Settings" / "Global Constants" switch (admin.const.* unchanged).
|
||
- Show the current region name (admin.region.current) in the header.
|
||
- No staff-account creation UI exists in admin-ui (createStaffUser/
|
||
getRoles are unused); nothing to remove.
|
||
|
||
[2026-10-07 10:51:16] Phase 3 (user-ui) — browsing region store, selection UI, switch/reset, address region, regional checkout + history labels.
|
||
|
||
New files:
|
||
- apps/user-ui/src/store/regionStore.ts (new)
|
||
- zustand store persisted via zustand/middleware `persist` + `createJSONStorage`
|
||
over common-ui `StorageServiceCasual`. State: `selectedRegionId: number | null`,
|
||
`selectedRegion: RegionSummary | null`, monotonic `regionGeneration` marker
|
||
(race guard). Actions: `setRegion(region)`, `clearRegion()`. Persist key
|
||
`freshyo-region`, version 1.
|
||
- apps/user-ui/src/lib/region-switch.ts (new)
|
||
- Centralized `confirmRegionSwitch(region, queryClient)`: clears regular+flash
|
||
local carts (clearLocalCart), resets quick-delivery selected slot, address
|
||
selection, slot/store stores and flash-cart/flash-navigation state, calls
|
||
regionStore.setRegion, then invalidates all react-query caches.
|
||
- apps/user-ui/src/components/RegionSelector.tsx (new)
|
||
- Lists trpc.common.listRegions. `mode='gate'` renders a full-screen first-run
|
||
chooser; `mode='switch'` is dialog content and opens an Alert confirmation
|
||
stating the whole cart will be cleared, then runs confirmRegionSwitch.
|
||
- apps/user-ui/src/components/RegionGate.tsx (new)
|
||
- Hydration-aware gate: waits for persisted region, validates the saved region
|
||
against common.listRegions (clears stale ids), renders RegionSelector until a
|
||
region exists, otherwise children.
|
||
|
||
Modified files:
|
||
- packages/shared/types/app-common.types.ts
|
||
- Add optional `regionId?: number` to AddressFormProps.initialValues.
|
||
- apps/user-ui/src/components/AddressForm.tsx
|
||
- Query common.listRegions; required inline region dropdown; new addresses
|
||
default to the browsing region while edits keep the stored region unless
|
||
explicitly changed; include `regionId` in create/update payloads + Yup rule.
|
||
- apps/user-ui/components/CheckoutAddressSelector.tsx
|
||
- Region-aware selection: cross-region address prompts confirmation, runs
|
||
confirmRegionSwitch and routes home; default auto-select only for the current
|
||
region; attach-location update now sends regionId.
|
||
- apps/user-ui/components/QuickDeliveryAddressSelector.tsx
|
||
- Same cross-region address handling (confirmation + centralized switch +
|
||
navigate home); shows a switch prompt when the selected/default address
|
||
belongs to another region.
|
||
- apps/user-ui/app/(drawer)/(tabs)/me/addresses/index.tsx
|
||
- Carry regionId on the edit view-model/initialValues and include it in the
|
||
set-default updateAddress payload.
|
||
- apps/user-ui/components/PaymentAndOrderComponent.tsx
|
||
- Read selectedRegionId from regionStore, block submit without a region, and
|
||
pass `regionId` to user.order.placeOrder; surface backend errors safely.
|
||
- apps/user-ui/app/(drawer)/(tabs)/me/my-orders/index.tsx
|
||
- Render `regionName` badge on each order (list stays account-wide).
|
||
- apps/user-ui/app/(drawer)/(tabs)/me/my-orders/[id].tsx
|
||
- Show order region label in the detail header.
|
||
- apps/user-ui/components/FirstUserWrapper.tsx
|
||
- Wrap children in RegionGate so a user with no saved region is prompted.
|
||
- apps/user-ui/app/(drawer)/(tabs)/me/index.tsx
|
||
- Add a "Delivery Region" entry that opens RegionSelector in switch mode.
|
||
|
||
[2026-10-07 10:54:56] Phase 1 follow-up — backend region wiring + migrations 0006/0007.
|
||
|
||
packages/db_helper_sqlite/src/db/schema.ts
|
||
- region_id added (nullable, app-enforced) to product_info, staff_users,
|
||
store_info, vendor_snippets, product_tag_info, product_group_info,
|
||
delivery_slot_info, coupons, home_banners, addresses, orders.
|
||
- ordersRelations gains region relation.
|
||
packages/db_helper_sqlite/drizzle/0007_region_columns_backfill.sql (new)
|
||
- ALTER TABLE add nullable region_id + backfill all rows to Mahabubnagar + indexes.
|
||
packages/db_helper_sqlite/drizzle/meta/_journal.json
|
||
- journal entry idx 7 -> 0007_region_columns_backfill.
|
||
packages/db_helper_sqlite/src/admin-apis/staff-user.ts
|
||
- createStaffUserWithRegion(); getAllStaff now returns regionId.
|
||
packages/db_helper_sqlite/src/user-apis/address.ts
|
||
- createUserAddress/updateUserAddress accept and persist regionId; mapUserAddress returns regionId.
|
||
packages/db_helper_sqlite/src/user-apis/order.ts
|
||
- OrderWithRelations gains regionId/region; order reads include region relation.
|
||
packages/shared/types/user.ts
|
||
- UserAddress.regionId; UserOrderSummary.regionId/regionName.
|
||
|
||
apps/backend/src/trpc/apis/superadmin-apis/apis/staff.ts (new)
|
||
- superadmin.staff.list/roles/create (region required).
|
||
apps/backend/src/trpc/apis/admin-apis/apis/region.ts (new)
|
||
- admin.region.current/bounds/effective/getBoundSettings/updateBoundSettings (staff region scoped).
|
||
apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
|
||
- common.listRegions + common.regionSettings (public).
|
||
apps/backend/src/trpc/apis/user-apis/apis/address.ts
|
||
- createAddress/updateAddress require regionId.
|
||
apps/backend/src/trpc/apis/user-apis/apis/order.ts
|
||
- placeOrder requires regionId; address/region mismatch rejected; order stores region; history returns regionName.
|
||
apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts
|
||
- staff login returns staff.regionId.
|
||
apps/backend/src/sqliteImporter.ts
|
||
- re-export createStaffUserWithRegion and region helpers.
|
||
|
||
apps/admin-ui, apps/user-ui: region-aware screens per the two UI workstreams
|
||
(bound tabs + staff region; region store/selector/switch + address region + history labels).
|
||
|
||
Typecheck: db_helper_sqlite, backend and superadmin-ui all pass (tsc --noEmit). No migrations run, no tests run, no git.
|
||
|
||
[2026-10-07 11:12:00] Phase 1 addendum — 0007 now rebuilds the region FK subgraph with region_id NOT NULL.
|
||
|
||
packages/db_helper_sqlite/drizzle/0007_region_columns_backfill.sql
|
||
- After the nullable ADD COLUMN + backfill, rebuild every table in the region_id
|
||
FK subgraph (31 tables incl. product_skus, order_items, orders, staff_notif_creds,
|
||
coupon_* etc.) per docs/recreate-referenced-tables.md: create __new parent-first,
|
||
copy all columns, drop leaves-first, rename parents-first, recreate indexes.
|
||
- region_id is now NOT NULL (FK to regions) in the rebuilt tables.
|
||
- CHECK on product_reviews written unqualified.
|
||
|
||
Schema note: Drizzle schema keeps region_id nullable to avoid breaking existing
|
||
insert call sites; the DB is stricter. Remaining admin create paths (product, store,
|
||
banner, coupon, tag, group, slot) must be updated to supply the staff region.
|
||
|
||
[2026-10-07 11:24:00] Wire regionId into all region-owned create paths (region is required, no defaults).
|
||
|
||
DB helpers (packages/db_helper_sqlite/src):
|
||
- admin-apis/product.ts: createProduct(input, regionId), createProductTag(input, regionId),
|
||
createProductGroup(..., regionId) now write region_id.
|
||
- admin-apis/store.ts: createStore(input, products, regionId).
|
||
- admin-apis/banner.ts: createBanner(input, regionId).
|
||
- admin-apis/vendor-snippets.ts: createVendorSnippet({..., regionId}).
|
||
- admin-apis/slots.ts: createSlotWithRelations(input, regionId); snippet inserts inherit region.
|
||
- admin-apis/coupon.ts: createCouponWithRelations(..., regionId),
|
||
createReservedCouponWithProducts(..., regionId), generateCancellationCoupon(..., regionId),
|
||
createCouponForUser(..., regionId).
|
||
- admin-apis/staff-user.ts: createStaffUser(..., regionId).
|
||
- user-apis/coupon.ts: redeemReservedCoupon copies reservedCoupon.regionId into the coupon.
|
||
- schema.ts + 0007: reserved_coupons is now region-owned too (ALTER + backfill + rebuild NOT NULL + index).
|
||
- Removed all `?? 1` fallbacks; regionId is mandatory and must be supplied by the caller.
|
||
|
||
Routers (apps/backend/src/trpc/apis/admin-apis/apis):
|
||
- product.ts / store.ts / banner.ts / vendor-snippets.ts create procedures now use staffProcedure
|
||
and pass ctx.staffUser.regionId.
|
||
- slots.ts / coupon.ts / staff-user.ts pass ctx.staffUser.regionId (and order.regionId for
|
||
cancellation coupons).
|
||
|
||
Typecheck: db_helper_sqlite and backend pass.
|
||
|
||
[2026-10-07 11:27:35] Fix 0007 migration failure (FOREIGN KEY constraint failed).
|
||
|
||
Root cause (proven on a copy of the local D1 DB, statement-by-statement):
|
||
- The drop/rebuild ordering was correct; the real problem is legacy DATA written
|
||
before FK enforcement that violates the FKs the rebuilt tables declare:
|
||
* 5 orders.address_id values no longer exist in addresses.
|
||
* 11 payments rows whose order no longer exists (ALL payment rows are orphans).
|
||
The __new_orders copy (statement #75) and later __new_payments copy (#83) fail
|
||
on these live orphan rows.
|
||
- Additionally the first partial run had already committed phase 1 (ALTERs +
|
||
backfill + 19 __new_ copies), so re-running the file as-is would fail on duplicate columns.
|
||
|
||
Planned diff for packages/db_helper_sqlite/drizzle/0007_region_columns_backfill.sql:
|
||
- Remove the ALTER-ADD-COLUMN + backfill phase entirely. region_id is added by the
|
||
rebuild itself, computed at DB level in each copy SELECT
|
||
((SELECT id FROM regions WHERE name='Mahabubnagar')). No app-level defaults.
|
||
- Add a repair phase before the copy:
|
||
* DELETE FROM payments WHERE order_id NOT IN (SELECT id FROM orders);
|
||
* remove the 5 orphan orders AND their dependents: delete their
|
||
payments/order_items/order_status/refunds, null out coupon_usage.order_id /
|
||
coupon_usage.order_item_id / complaints.order_id / user_incidents.order_id.
|
||
- Drop the pre-rebuild region indexes (created after rename only).
|
||
- Journal entry unchanged (idx 7).
|
||
- After migration: user resets local D1 state and re-runs 0006 + 0007;
|
||
verify with PRAGMA foreign_key_check and row counts.
|
||
|
||
[2026-10-07 11:41:00] 0007 repair extended + proof harness run (read-only, on a COPY of the local DB).
|
||
|
||
- Repair phase also deletes order_status and refunds of the 5 orphan orders
|
||
(their copies would otherwise fail FK to __new_orders first).
|
||
- Proof harness on a copy of the actual local D1 DB (freshyo-dev, FK enforcement ON,
|
||
statement-by-statement like wrangler):
|
||
* All statements pass; PRAGMA foreign_key_check = 0 violations; zero __new_ leftovers.
|
||
* Row deltas exactly as intended: orders -5, order_items -19, order_status -5,
|
||
payments -11 (all), refunds -2; every other table unchanged.
|
||
* region_id NOT NULL enforced and FK rejection verified post-rename (writes rejected).
|
||
* All 13 original unique indexes recreated (4 table-prefixed + 9 unique_*).
|
||
- Important: wrangler runs the file in one transaction — the earlier failed run left
|
||
NO partial state, so the fixed 0007 can simply be re-run (0006 already applied).
|
||
|
||
[2026-10-07 11:45:00] Superadmin staff-user CRUD (regions reassignment + removal).
|
||
|
||
- admin-apis/staff-user.ts (db_helper_sqlite): add updateStaffUserRegion(staffId, regionId)
|
||
and deleteStaffUser(staffId). Delete removes staff_notif_creds rows, clears nullable
|
||
references (user_incidents.added_by), and refuses when the staff still owns a store
|
||
or created coupons / reserved coupons (NOT NULL dependent FKs would break).
|
||
- export both helpers from packages/db_helper_sqlite/index.ts and re-export them in
|
||
apps/backend/src/sqliteImporter.ts.
|
||
- superadmin-apis/apis/staff.ts: add superadmin.staff.update (reassign region) and
|
||
superadmin.staff.remove (delete with blockedBy reason).
|
||
- superadmin-ui: new routes/staff.tsx CRUD screen (list, add with role+region, region
|
||
reassignment, delete w/ confirmation + blocked-reason display); AppShell nav entry
|
||
"Admin Users"; routeTree.gen.ts registers /staff.
|
||
|
||
[2026-10-07 11:41:17] Enable Maestro MCP server in project opencode.jsonc.
|
||
|
||
- Ran: opencode mcp add maestro -- maestro mcp
|
||
(registers local stdio MCP server "maestro" running `maestro mcp`,
|
||
Maestro 2.11.0 built-in MCP server, project-local config).
|
||
|
||
[2026-10-07 12:03:54] Phase 4 (admin-web) — per-bound regional settings port from admin-ui.
|
||
|
||
Planned diffs:
|
||
|
||
apps/admin-web/src/components/context/staff-auth-context.tsx
|
||
- Extend session `Staff` shape with optional `regionId: number | null`
|
||
(login already returns it); expose `regionId` on the auth context value.
|
||
- Non-breaking: existing consumers of `staff` keep working.
|
||
|
||
apps/admin-web/src/routes/dashboard.customize-app.tsx
|
||
- Replace the single global constants form with one tab per region bound
|
||
(admin.region.bounds, ascending priority). Each tab shows the bound
|
||
description (or "Bound #id") + priority and marks the lowest-priority
|
||
bound as "Effective" (its settings apply to checkout).
|
||
- Selected bound loads admin.region.getBoundSettings and renders the 11
|
||
regional keys as editable inputs (ConstantInput gains an
|
||
`allowSectionNavigation` prop so popularItems/allItemsOrder become inline
|
||
comma-separated inputs instead of links to the global editors).
|
||
- Save via admin.region.updateBoundSettings with only changed keys
|
||
(string|null values). Default-select lowest-priority bound; reinitialize
|
||
the form (Formik enableReinitialize + key) so drafts do not leak between
|
||
tabs. Loading / error / "no bounds configured" states.
|
||
- Keep the existing global constants form reachable via a top-level
|
||
"Regional Settings" / "Global Constants" switch (admin.const.* unchanged).
|
||
- Show the current region name (admin.region.current) in the header.
|
||
- No staff-account creation UI exists in admin-web (createStaffUser/
|
||
getRoles unused); nothing to remove.
|
||
|
||
[2026-10-07 $(date +%H:%M:%S)] Phase 4 (web-ui) — port browsing-region features from user-ui (Expo) to web-ui (TanStack Start).
|
||
|
||
New files:
|
||
- apps/web-ui/src/lib/stores/region-store.ts (new)
|
||
- zustand `persist` store over an SSR-safe localStorage wrapper (web equivalent
|
||
of Expo's StorageServiceCasual). Same shape as user-ui regionStore:
|
||
selectedRegionId / selectedRegion / regionGeneration + setRegion / clearRegion.
|
||
Persist key `freshyo-region`, version 1.
|
||
- apps/web-ui/src/lib/region-switch.ts (new)
|
||
- Centralized `confirmRegionSwitch(region, queryClient)`: clears regular+flash
|
||
local carts (localStorage + react-query cart keys), resets quick-delivery
|
||
selected slot, address selection, slot store ids, cart-store added product,
|
||
flash-cart product, flash-navigation flag, clears central product/slot
|
||
snapshots, persists the new region, then invalidates all react-query caches.
|
||
Callers must confirm with the user before invoking.
|
||
- apps/web-ui/src/components/RegionSelector.tsx (new)
|
||
- Lists trpc.common.listRegions. mode='gate' full-screen first-run chooser
|
||
(direct select, no cart exists yet); mode='switch' dialog content with an
|
||
inline "entire cart will be cleared" confirmation before confirmRegionSwitch.
|
||
- apps/web-ui/src/components/RegionGate.tsx (new)
|
||
- Hydration-aware gate: waits for persisted region, validates saved region
|
||
against common.listRegions (clears stale ids), renders children until
|
||
hydrated (SSR-safe, avoids hydration mismatch) then a blocking overlay with
|
||
RegionSelector until a region exists.
|
||
|
||
Modified files:
|
||
- apps/web-ui/src/routes/__root.tsx
|
||
- Wrap app children in RegionGate (inside trpc/Auth providers).
|
||
- apps/web-ui/src/components/AddressForm.tsx
|
||
- Required region <select> from common.listRegions; new addresses default to
|
||
the browsing region, edits keep the stored region; regionId in
|
||
create/update payloads + Yup required rule.
|
||
- apps/web-ui/src/hooks/checkout-hooks.ts (useCheckoutAddress)
|
||
- Default auto-select only for current-region addresses; expose cross-region
|
||
helper data (addresses carry regionId).
|
||
- apps/web-ui/src/components/CheckoutAddressSelector.tsx
|
||
- Cross-region tap -> confirm (entire cart cleared) -> confirmRegionSwitch ->
|
||
navigate home; same-region selection preserves cart.
|
||
- apps/web-ui/src/routes/home.checkout.tsx + flash.checkout.tsx
|
||
- Same cross-region address handling; placeOrder payloads gain regionId;
|
||
backend mismatch errors surfaced.
|
||
- apps/web-ui/src/components/PaymentAndOrderComponent.tsx
|
||
- Reads selectedRegionId, blocks submit without a region, passes regionId to
|
||
placeOrder, surfaces backend mismatch message.
|
||
- apps/web-ui/src/routes/me.orders.tsx + me.orders.$id.tsx
|
||
- Account-wide history (no region filter) with regionName labels.
|
||
- apps/web-ui/src/routes/me.addresses.tsx
|
||
- Address view-model carries regionId; edit initialValues keep stored region;
|
||
set-default payload includes regionId (blocked with a message when missing).
|
||
- apps/web-ui/src/routes/me.tsx
|
||
- "Delivery Region" menu entry opening RegionSelector in switch mode.
|
||
- Query keys: same as Expo (version-keyed global catalog caches, no region in
|
||
keys); region switch clears central stores + invalidates all queries so no
|
||
stale cross-region snapshots survive.
|
||
|
||
Typecheck: `npx tsc --noEmit --project apps/web-ui/tsconfig.json` from repo root.
|
||
|
||
[2026-10-07 12:14:52] Browser verification fix — allow localhost:4176 in backend CORS.
|
||
|
||
apps/backend/src/app.ts
|
||
- CORS origin list gains 'http://localhost:4176' (admin-web auto-bumps to 4176
|
||
when superadmin-ui already holds 4175; without this the browser blocks API calls).
|
||
|
||
[2026-10-07 12:18:39] Browser verification (Playwright MCP): web-ui region gate + admin-web bound tabs.
|
||
- web-ui :4174 region gate renders with Mahabubnagar; selection dismisses gate.
|
||
- admin-web :4176 staff login (uitest/test1234, regionId 1) works; customize-app shows
|
||
Region: Mahabubnagar, Mbnr-1 P1 EFFECTIVE / Mbnr-2 P2 tabs, all 11 settings loaded.
|
||
- E2E save verified twice in D1 (deliveryCharge 20->25, minRegularOrderValue 300->350
|
||
on bound 1 only; bound 2 untouched), then restored to seeded values via SQL.
|
||
- test staff row 'uitest' left in local D1 for reuse (region 1, role admin).
|
||
- Note: backend CORS already included :4176. One benign console error (numberOfLines prop).
|
||
|
||
[2026-10-07 12:20:40] Isolation test fixtures in LOCAL dev D1 only (not app code).
|
||
- Region 2 'Testnagar' + 1 bound (priority 1, square GeoJSON) + 11 settings rows
|
||
(deliveryCharge 30 / minRegularOrderValue 500 to distinguish from Mahabubnagar).
|
||
- Staff 'uitest2' (region 2, role admin, password test1234) for cross-region API tests.
|
||
- All fixture rows are test-only and removable.
|
||
|
||
[2026-10-07 12:24:46] Region-scope CATALOG admin read paths (staff sees own region only).
|
||
|
||
Planned diffs:
|
||
|
||
packages/db_helper_sqlite/src/admin-apis/product.ts
|
||
- getAllProducts(regionId), getProductById(regionId, id),
|
||
getAllProductTags(regionId), getAllProductTagInfos(regionId),
|
||
getProductTagInfoById(regionId, tagId), getProductTagById(regionId, tagId),
|
||
getProductReviews(regionId, productId, limit, offset),
|
||
getAllProductGroups(regionId): regionId as FIRST param; list endpoints add
|
||
eq(<table>.regionId, regionId); single-ID reads use and(id, regionId) and
|
||
return null outside the region; reviews scoped via product_info.region_id
|
||
join (reviews + count). checkProductExistsByName /
|
||
checkProductTagExistsByName stay GLOBAL. Writes, price/stock mutations,
|
||
respondToReview untouched.
|
||
|
||
packages/db_helper_sqlite/src/admin-apis/store.ts
|
||
- getAllStores(regionId), getStoreById(regionId, id); add `and` import.
|
||
|
||
packages/db_helper_sqlite/src/admin-apis/banner.ts
|
||
- getBanners(regionId), getBannerById(regionId, id); add `and` import.
|
||
|
||
apps/backend/src/trpc/apis/admin-apis/apis/product.ts, store.ts, banner.ts
|
||
- Read procedures keep protectedProcedure (no auth restructure) and pass
|
||
ctx.staffUser!.regionId, including read-before-write existence checks in
|
||
updateStore / updateProductTag / deleteProductTag.
|
||
|
||
apps/backend/src/stores/banner-store.ts
|
||
- getBannerById wrapper threads regionId through (dead code, no callers;
|
||
updated only for typecheck).
|
||
|
||
apps/backend/src/stores/product-tag-store.ts
|
||
- getTagsByStoreId resolves the store's own regionId via storeInfo and
|
||
scopes getAllProductTags to it; user-apis callers untouched (stay working).
|
||
|
||
Typecheck: tsc --noEmit for packages/db_helper_sqlite + apps/backend.
|
||
|
||
[2026-10-07 12:24:34] Region-scope OPERATIONAL admin read paths (slots, snippets, coupons, orders, users, complaints).
|
||
|
||
Planned diffs (regionId added as FIRST param of each read helper; lists filter by
|
||
region; single-ID reads constrain by region and return null outside it; writes,
|
||
check*Exists validators, superadmin/user/region/const paths untouched):
|
||
|
||
packages/db_helper_sqlite/src/admin-apis/slots.ts
|
||
- getActiveSlotsWithProducts(regionId, limit): where isActive + region_id.
|
||
- getSlotsAfterDate(regionId|null, afterDate): region filter when non-null
|
||
(null = global, used only by the public vendor getUpcomingSlots link).
|
||
- getSlotByIdWithRelations(regionId, id): and(id, region_id), null outside.
|
||
- getSlotDeliverySequence(regionId, slotId): and(id, region_id), null outside.
|
||
|
||
packages/db_helper_sqlite/src/admin-apis/vendor-snippets.ts (add `and` import)
|
||
- getVendorSnippetById(regionId, id): and(id, region_id).
|
||
- getVendorSnippetByCode(regionId|null, code): region-verified when non-null
|
||
(null = global public vendor order-list links).
|
||
- getAllVendorSnippets(regionId): where region_id.
|
||
- getProductsByIds(regionId|null, skuIds): empty->[]; when region set, keep only
|
||
SKUs whose parent product is in-region (columns gain product.regionId).
|
||
- getVendorSlotById(regionId|null, slotId): region-verified when non-null.
|
||
- getVendorOrdersBySlotId(regionId|null, slotId): and(slot, region) when non-null.
|
||
|
||
packages/db_helper_sqlite/src/admin-apis/coupon.ts (add `sql`/`SQL` imports)
|
||
- getAllCoupons(regionId, cursor, limit, search): push region condition.
|
||
- getCouponById(regionId, id): and(id, region_id).
|
||
- getReservedCoupons(regionId, cursor, limit, search): push region condition.
|
||
- getOrderWithUser(regionId, orderId): and(id, region_id).
|
||
- getUsersForCoupon(regionId, search, limit, offset): EXISTS in-region order filter
|
||
(users scoped via orders.region_id, not addresses).
|
||
|
||
packages/db_helper_sqlite/src/admin-apis/order.ts (import deliverySlotInfo)
|
||
- getOrderDetails(regionId, orderId): and(id, region_id).
|
||
- getSlotOrders(regionId, slotId): verify slot in-region first (else empty list);
|
||
then and(slot, region) on orders.
|
||
- getAllOrders(regionId, input): seed whereCondition with region equality.
|
||
|
||
packages/db_helper_sqlite/src/admin-apis/user.ts (add `and`/`or`/`isNull` imports)
|
||
- getUnresolvedComplaintsCount(regionId): unresolved AND (orderless OR order in-region).
|
||
- getAllUsersWithFilters(regionId, limit, cursor, search): EXISTS in-region order.
|
||
- getOrderCountsByUserIds / getLastOrdersByUserIds(regionId, userIds): AND region.
|
||
- getSuspensionStatusesByUserIds(regionId, userIds): param added for uniformity;
|
||
no filter (user_details has no region; callers pass in-region users only).
|
||
- getUserBasicInfo(regionId, userId): null unless >=1 in-region order.
|
||
- getUserOrders(regionId, userId): and(user, region).
|
||
- getOrderStatusesByOrderIds / getItemCountsByOrderIds(regionId, orderIds):
|
||
prefetch in-region order ids, query only those.
|
||
- searchUsers(regionId, search): EXISTS in-region order (both branches).
|
||
- getUserIncidentsWithRelations(regionId, userId): keep orderless or in-region-order
|
||
incidents (JS filter on joined order.regionId).
|
||
|
||
packages/db_helper_sqlite/src/admin-apis/complaint.ts (add `and`/`or`/`isNull`, orders import)
|
||
- getComplaintById(regionId, id): null when order-backed and order out-of-region/missing.
|
||
- getComplaints(regionId, cursor, limit): left-join orders, keep orderless OR
|
||
in-region-order complaints (+ cursor).
|
||
|
||
apps/backend/src/trpc/apis/admin-apis/apis/{slots,vendor-snippets,coupon,order,user,complaint}.ts
|
||
- Thread ctx.staffUser.regionId (staffProcedure where imported, else
|
||
protectedProcedure + ctx.staffUser!.regionId) into every scoped helper call.
|
||
- Public vendor endpoints (getOrdersBySnippet, getOrdersBySnippetAndSlot,
|
||
getUpcomingSlots) pass null = deliberately global vendor links (no staff region).
|
||
- slots.getDeliverySequence gains the missing staff guard (needed for region).
|
||
- complaint.resolve's pre-check becomes region-scoped (write helper untouched).
|
||
- payments.ts: stub, no order reads -> no change.
|
||
- Writes (updates/deletes/invalidates/suspends), check*Exists validators, notif-cred
|
||
reads, and non-admin callers unchanged by design; residual cross-region write
|
||
paths noted in final report, not altered.
|
||
|
||
Typecheck: npx tsc --noEmit --project packages/db_helper_sqlite/tsconfig.json AND
|
||
apps/backend/tsconfig.json; fix introduced errors. No tests, no git, no migrations.
|
||
|
||
[2026-10-07 12:31:10] Region-scope admin UPDATE/DELETE-by-ID paths + cross-region relationship validation on creates.
|
||
|
||
Planned diffs (regionId as FIRST param on helpers; single-ID mutations constrain with
|
||
and(id, regionId) and return null/false outside the region; creates validate related
|
||
IDs resolve to in-region rows and throw Error('... belongs to a different region')):
|
||
|
||
packages/db_helper_sqlite/src/admin-apis/product.ts
|
||
- deleteProduct(regionId, id), updateProduct(regionId, id, input: region-scoped
|
||
pre-read + update where; cross-region combo skuIds + storeId rejected.
|
||
- createProduct: storeId must resolve to an in-region store; combo-item skuIds
|
||
must resolve via parent product_info.region_id (validation BEFORE the
|
||
generic try/catch so the message surfaces).
|
||
- createProductTag: relatedStores must be in-region stores.
|
||
- replaceTagProducts(regionId, tagId, productIds): tag must be in-region; skuIds
|
||
must be in-region (via parent product).
|
||
- updateProductTag(regionId, tagId, input) -> null outside region; validates
|
||
relatedStores in-region. deleteProductTag(regionId, tagId) -> boolean.
|
||
- createProductGroup/updateProductGroup: productIds (SKU ids) validated in-region.
|
||
- updateProductGroup(regionId, ...), deleteProductGroup(regionId, ...) scoped.
|
||
- updateProductPrices(regionId, updates): out-of-region SKUs reported as invalidIds.
|
||
- toggleProductOutOfStock(regionId, productId): null outside region.
|
||
- respondToReview(regionId, reviewId, ...): null when the review's product is
|
||
out-of-region. check*Exists validators stay global.
|
||
|
||
packages/db_helper_sqlite/src/admin-apis/store.ts
|
||
- updateStore(regionId, id, input, products?), deleteStore(regionId, id) scoped
|
||
(delete/update throw 'Store not found' when outside region, as before).
|
||
- createStore/updateStore: owner staff must be in-region; product SKU ids must
|
||
resolve to in-region products.
|
||
|
||
packages/db_helper_sqlite/src/admin-apis/banner.ts
|
||
- updateBanner(regionId, id, input) -> Banner|null; deleteBanner(regionId, id)
|
||
-> boolean. createBanner/updateBanner: skuIds validated in-region.
|
||
|
||
packages/db_helper_sqlite/src/admin-apis/slots.ts
|
||
- updateSlotWithRelations(regionId, input), updateSlotCapacity(regionId, ...),
|
||
updateSlotDeliverySequence(regionId, ...) scoped (null outside region).
|
||
- createSlotWithRelations/updateSlotWithRelations: skuIds + snippet skuIds +
|
||
groupIds validated in-region. staleSlotsCleanup left global (maintenance).
|
||
|
||
packages/db_helper_sqlite/src/admin-apis/vendor-snippets.ts
|
||
- updateVendorSnippet(regionId, id, updates) -> null outside region; new slotId +
|
||
skuIds validated in-region. deleteVendorSnippet(regionId, id) scoped.
|
||
- createVendorSnippet: slotId + skuIds validated in-region.
|
||
- updateVendorOrderItemPackaging left global (public vendor link, no staff ctx).
|
||
|
||
packages/db_helper_sqlite/src/admin-apis/coupon.ts
|
||
- updateCouponWithRelations(regionId, id, ...) -> null outside region; new
|
||
applicableProducts validated in-region. invalidateCoupon(regionId, id) ->
|
||
Coupon|null. createCouponWithRelations/createReservedCouponWithProducts:
|
||
applicableProducts validated in-region. generateCancellationCoupon verifies
|
||
the order's region matches. createCouponForUser unchanged (note).
|
||
|
||
packages/db_helper_sqlite/src/admin-apis/order.ts
|
||
- updateOrderNotes/updateOrderPackaged/updateOrderDelivered/removeDeliveryCharge/
|
||
cancelOrder/deleteOrderById(regionId, ...) scoped (null/false/order_not_found
|
||
outside region). updateOrderItemPackaging(regionId, ...) resolves the parent
|
||
order's region first. updateAddressCoords(regionId, ...) constrains
|
||
addresses.regionId. rebalanceSlots(regionId, slotIds) only touches in-region
|
||
slots/orders. deleteOrdersWithRelations left global (note: caller is the
|
||
global lib/delete-orders cleanup path).
|
||
|
||
packages/db_helper_sqlite/src/admin-apis/user.ts — untouched (upsertUserSuspension
|
||
account-global, createUserIncident no region needed — noted only).
|
||
packages/db_helper_sqlite/src/admin-apis/complaint.ts — resolveComplaint(regionId,
|
||
id, response) -> boolean, constrained via the getComplaintById region pattern.
|
||
|
||
apps/backend/src/trpc/apis/admin-apis/apis/{product,store,banner,slots,
|
||
vendor-snippets,coupon,order,complaint}.ts — thread ctx.staffUser.regionId
|
||
(staffProcedure where imported, else protectedProcedure + ctx.staffUser!.regionId)
|
||
into every changed helper; map null/false to NOT_FOUND (no cross-region leak);
|
||
create-validation Errors surface as-is.
|
||
|
||
Typecheck: npx tsc --noEmit --project packages/db_helper_sqlite/tsconfig.json AND
|
||
apps/backend/tsconfig.json; fix introduced errors. No tests, no git, no migrations.
|
||
|
||
[2026-10-07 12:52:57] Region isolation testing — two-region (Mahabubnagar + Testnagar) verification.
|
||
API (26/26 checks pass):
|
||
- Creates in both regions via admin API: stores, tags, products, slots, coupons, banners.
|
||
- Lists isolated: staff1 sees R1-only tags, staff2 sees R2-only tags.
|
||
- Cross-region reads 404 without leaking (tag by id both ways; order details both ways).
|
||
- Cross-region updates rejected (store update, slot capacity); own-region update works.
|
||
- Cross-region create validation: R1 product with R2 store rejected.
|
||
- Address saves regionId; mismatched checkout (region 1 order + region 2 address) rejected.
|
||
- Region-2 order placed end-to-end (id 2454, regionId 2); staff1 list/detail exclude it,
|
||
staff2 list/detail include it; user history carries regionName labels.
|
||
- Duplicate (region_id, priority) rejected by unique index (proven at DB level).
|
||
Browser (Playwright MCP):
|
||
- web-ui gate lists both regions; switch Testnagar->Mahabubnagar with seeded cart:
|
||
confirm dialog clears cart 1->0; cancel preserves cart + region.
|
||
- admin-web customize bound tabs + E2E save verified earlier.
|
||
- staff2 bounds endpoint returns Test-1 only; staff1 returns Mbnr-1/2 only.
|
||
Left in LOCAL dev D1 (test-only, removable): region Testnagar + bound + settings,
|
||
staff uitest/uitest2, ISO stores/tags/products/slots/coupons/banners, test address 875,
|
||
order 2454. Temp scripts removed from repo.
|
||
NOT covered: superadmin Regions/Staff UI pages (need superadmin password);
|
||
storefront browsing still serves the global cache (per-region cache files pending).
|
||
|
||
[2026-10-07 13:05:00] Region-aware storefront catalog (user-ui + web-ui) against the FIXED backend contract.
|
||
|
||
Planned diffs (frontend only; backend untouched — another agent implements the contract):
|
||
|
||
apps/user-ui/src/hooks/prominent-api-hooks.ts
|
||
- useGetEssentialConsts reads selectedRegionId from regionStore and calls
|
||
trpc.common.essentialConsts with { regionId } (cast for forward-compat;
|
||
current backend ignores the extra input at runtime). Enabled only when a
|
||
region is selected; persisted discovery key becomes per-region
|
||
(essential_consts_r<regionId>) so regions never share snapshots.
|
||
- Regional URL builders from discovery data (effectiveSettings.regionId with
|
||
selectedRegionId fallback):
|
||
products/stores/per-store files:
|
||
{assetsDomain}{apiCacheKey}/regions/{regionId}/v-{cacheVersion}/{file}
|
||
availability:
|
||
{assetsDomain}regions/{regionId}/av-{availabilityVersion}/availability.json
|
||
slots:
|
||
{assetsDomain}regions/{regionId}/slots/v-{slotsVersion}/slots.json
|
||
Null regionId -> null URL -> catalog queries stay disabled (gate covers
|
||
the no-region case).
|
||
- New useRegionalConsts(): discovery data with the 5 delivery/minimum fields
|
||
(deliveryCharge, freeDeliveryThreshold, flashDeliveryCharge,
|
||
flashFreeDeliveryThreshold, minRegularOrderValue) overridden from
|
||
effectiveSettings.settings (numeric parse, global fallback). Display-only;
|
||
backend stays authoritative for the actual charge.
|
||
|
||
apps/user-ui/src/lib/region-switch.ts
|
||
- confirmRegionSwitch additionally drops old-region react-query catalog
|
||
snapshots (removeQueries on all-products/stores/slots/availability/
|
||
store-with-products) before setRegion + invalidateQueries refetches
|
||
discovery and catalog for the new region. Central stores cleared as before.
|
||
Cancel path unchanged.
|
||
|
||
apps/user-ui/components/{cart-page,checkout-page,floating-cart-bar}.tsx
|
||
- Delivery-charge/threshold messaging reads useRegionalConsts() (regional
|
||
effective settings first, global fallback).
|
||
|
||
apps/web-ui/src/hooks/prominent-api-hooks.ts
|
||
- Mirror of the user-ui hook changes above (localStorage persisted catalog
|
||
caches stay version-gated; the versioned URL now contains the region so no
|
||
cross-region placeholder can match). Banners go through the regional URL.
|
||
apps/web-ui/src/lib/region-switch.ts
|
||
- Mirror of the user-ui switch extension.
|
||
apps/web-ui/src/components/{PaymentAndOrderComponent,FloatingCartBar}.tsx
|
||
- Delivery-charge/threshold display prefers effectiveSettings via
|
||
useRegionalConsts(); submit logic (regionId payload) untouched.
|
||
|
||
Admin apps: grep apps/admin-ui + apps/admin-web for essentialConsts/cache-file
|
||
consumers — report only, no edits.
|
||
|
||
Typecheck: npx tsc --noEmit --project apps/user-ui/tsconfig.json AND
|
||
apps/web-ui/tsconfig.json. No tests, no git, no migrations.
|
||
|
||
[2026-10-07 13:06:59] Per-region storefront cache phase — backend + clients implemented, pending 0008.
|
||
Backend: region_cache_versions table + 0008 migration (NOT run); all *ForCache
|
||
helpers + scaffolds region-first; KV essential_consts:{regionId}; regional paths
|
||
regions/{id}/...; createRegionCacheFiles/createAllCacheFiles(regionId?);
|
||
essentialConsts now REQUIRES {regionId}; CacheCreator DO drains per-region queue.
|
||
Clients (user-ui + web-ui): discovery passes browsing regionId; regional URL builders;
|
||
switch refetches discovery+catalog; checkout display uses effectiveSettings.
|
||
Verified: all 4 typechecks pass; new code live on :8787 (regionId required; versions
|
||
query fails until 0008 applied — expected).
|
||
NEXT: user runs 0008 on dev D1, then per-region generation is triggered and verified.
|
||
|
||
[2026-10-07 13:13:31] Per-region storefront verified end-to-end.
|
||
- 0008 applied by user; per-region generation triggered (store updates) — all
|
||
counters 1->2 in both regions; regional files live on CDN.
|
||
- File partition proven: r1 products.json 150 rows incl ISOProdR1, tags ISOTagR1 only;
|
||
r2 1 row (ISOProdR2), tags ISOTagR2 only; zero cross-leaks either way.
|
||
- Browser (web-ui): Testnagar storefront shows ISOTagR2+ISOProdR2, no R1 leaks;
|
||
Mahabubnagar shows ISOTagR1, no R2 leaks. (ISOProdR1 below render window;
|
||
present in-file; its tag mapping empty by fixture design.)
|
||
- Cross-region tag mapping rejected: 'Product 152 belongs to a different region'.
|
||
|
||
[2026-10-07 13:39:44] Closed loop: region-1 product verified rendered in UI.
|
||
- web-ui search 'ISOProdR1' while browsing Mahabubnagar: 1 result (ISOProdR1,
|
||
Rs 100, 500g), no ISOProdR2. Screenshot verified then removed.
|
||
- Earlier home-page absence explained: new SKU shows Out of Stock (no
|
||
availability/stock row), so it never surfaces in the purchasable list.
|
||
Not a region issue.
|
||
|
||
[2026-10-07 13:45:12] user-ui location bar on all top-level tabs.
|
||
- src/components/LocationBar.tsx (new): pin + region name row; tap opens
|
||
BottomDialog with RegionSelector mode=switch (lazily mounted; sheet handles
|
||
its own cart-clear confirmation). Rendered inside scroll content so it
|
||
scrolls out instead of sticking.
|
||
- Insert at top of scroll content: home listHeader, order-again ScrollView,
|
||
FlashDeliveryProducts ListHeader, stores ListHeader, me ScrollView.
|
||
|
||
[2026-10-07 13:49:26] home: LocationBar vertically first — moved static SearchBar into
|
||
the FlatList header below LocationBar so both scroll out together.
|
||
|
||
[2026-10-07T14:07:48+05:30] Home: scroll location away and stick the second (search) section header.
|
||
--- apps/user-ui/app/(drawer)/(tabs)/home/index.tsx
|
||
+++ apps/user-ui/app/(drawer)/(tabs)/home/index.tsx
|
||
@@ -1,5 +1,5 @@
|
||
import React, { useState, useCallback, useMemo, memo, useRef, useEffect } from "react";
|
||
-import { View, Dimensions, Image, RefreshControl } from "react-native";
|
||
+import { View, Dimensions, Image, RefreshControl, SectionList } from "react-native";
|
||
import { ScrollView } from "react-native-gesture-handler";
|
||
import { useRouter } from "expo-router";
|
||
import {
|
||
@@ -653,8 +653,6 @@
|
||
], [pageTint]);
|
||
|
||
const listHeader = useMemo(() => (
|
||
- <>
|
||
- <LocationBar />
|
||
<ListHeader
|
||
dashboardTags={dashboardTags}
|
||
activeTagId={activeTagId}
|
||
@@ -666,7 +664,6 @@
|
||
storesData={storesData}
|
||
sortedSlots={sortedSlots}
|
||
/>
|
||
- </>
|
||
), [dashboardTags, activeTagId, productsByTagId, expandedByTagId, handleToggleExpand, handleProductPress, storesData, sortedSlots]);
|
||
|
||
const listContentContainerStyle = useMemo(() => [
|
||
@@ -698,34 +695,52 @@
|
||
return (
|
||
<TabLayoutWrapper style={{ backgroundColor: '#FFFFFF' }}>
|
||
<View style={pageTintStyle}>
|
||
- <View
|
||
- style={searchBarContainerStyle}
|
||
- >
|
||
- <SearchBar
|
||
- testID="home-search"
|
||
- value={""}
|
||
- onChangeText={() => { }}
|
||
- onPress={handleSearchPress}
|
||
- editable={false}
|
||
- containerStyle={tw`bg-white`}
|
||
- onSubmitEditing={() => {
|
||
- if (inputQuery.trim()) {
|
||
- router.push(`/(drawer)/(tabs)/home/search-results?q=${encodeURIComponent(inputQuery.trim())}`);
|
||
- }
|
||
- }}
|
||
- returnKeyType="search"
|
||
- />
|
||
- </View>
|
||
-
|
||
- <MyFlatList
|
||
- data={displayedProducts.slice(0, visibleCount)}
|
||
- keyExtractor={(item) => item.id.toString()}
|
||
- numColumns={3}
|
||
+ <SectionList
|
||
+ sections={[{ data: [[], ...Array.from(
|
||
+ { length: Math.ceil(Math.min(displayedProducts.length, visibleCount) / 3) },
|
||
+ (_, index) => displayedProducts.slice(index * 3, Math.min(index * 3 + 3, visibleCount))
|
||
+ )] }]}
|
||
+ keyExtractor={(row, index) => row.length ? row.map((item) => item.id).join('-') : 'catalog-header'}
|
||
+ stickySectionHeadersEnabled
|
||
style={{ backgroundColor: '#FFFFFF' }}
|
||
contentContainerStyle={listContentContainerStyle}
|
||
- columnWrapperStyle={staticStyles.columnWrapper}
|
||
- renderItem={renderProductItem}
|
||
- ListHeaderComponent={listHeader}
|
||
+ ListHeaderComponent={<LocationBar />}
|
||
+ renderSectionHeader={() => (
|
||
+ <View style={searchBarContainerStyle}>
|
||
+ <SearchBar
|
||
+ testID="home-search"
|
||
+ value={""}
|
||
+ onChangeText={() => { }}
|
||
+ onPress={handleSearchPress}
|
||
+ editable={false}
|
||
+ containerStyle={tw`bg-white`}
|
||
+ onSubmitEditing={() => {
|
||
+ if (inputQuery.trim()) {
|
||
+ router.push(`/(drawer)/(tabs)/home/search-results?q=${encodeURIComponent(inputQuery.trim())}`);
|
||
+ }
|
||
+ }}
|
||
+ returnKeyType="search"
|
||
+ />
|
||
+ </View>
|
||
+ )}
|
||
+ renderItem={({ item: row, index }) => index === 0 ? (
|
||
+ <>
|
||
+ {listHeader}
|
||
+ {displayedProducts.length === 0 && (
|
||
+ <View style={tw`items-center py-8`}>
|
||
+ <MyText style={tw`text-gray-500`}>No products available</MyText>
|
||
+ </View>
|
||
+ )}
|
||
+ </>
|
||
+ ) : (
|
||
+ <View style={[staticStyles.columnWrapper, { flexDirection: 'row' }]}>
|
||
+ {row.map((item) => (
|
||
+ <React.Fragment key={item.id}>
|
||
+ {renderProductItem({ item })}
|
||
+ </React.Fragment>
|
||
+ ))}
|
||
+ </View>
|
||
+ )}
|
||
ListFooterComponent={
|
||
hasMore ? (
|
||
<View style={tw`items-center py-4`}>
|
||
@@ -748,11 +763,6 @@
|
||
colors={[theme.colors.brand500]}
|
||
/>
|
||
}
|
||
- ListEmptyComponent={
|
||
- <View style={tw`items-center py-8`}>
|
||
- <MyText style={tw`text-gray-500`}>No products available</MyText>
|
||
- </View>
|
||
- }
|
||
// NOTE: do not add removeClippedSubviews here - it breaks touch
|
||
// delivery to the nested horizontal scrollables in ListHeaderComponent
|
||
// (tag tabs / slots) on Android.
|
||
|
||
[2026-10-07 14:13:37] user-ui: single region source-of-truth hook.
|
||
- NEW src/hooks/useRegion.ts: useRegion() returns { region, regionId,
|
||
regionGeneration, hydrated, setRegion, clearRegion }. Wraps useRegionStore;
|
||
owns the persist-hydration subscription so consumers no longer touch the store.
|
||
- Routed all region/location reads through useRegion: LocationBar, RegionGate,
|
||
RegionSelector (dropped selectedRegionId prop, reads hook), AddressForm,
|
||
QuickDeliveryAddressSelector, PaymentAndOrderComponent, CheckoutAddressSelector,
|
||
me/index.tsx, prominent-api-hooks (useGetEssentialConsts, useDiscoveryRegionId).
|
||
- region-switch.ts keeps useRegionStore.getState() (non-hook lib, cannot call hooks).
|
||
|
||
[2026-10-07 14:26:08] location-based region resolution (backend + user-ui).
|
||
Backend:
|
||
- shared: add RegionBoundSummary + ResolvedRegion types (region.types.ts).
|
||
- db_helper_sqlite: add getAllRegionsWithBounds() (regions ordered by id,
|
||
each region's bounds ordered by ascending numeric priority); export it.
|
||
- common tRPC: add public resolveRegionByLocation({lat,lng}) -> { region,
|
||
bound } | null. Iterates every region, and within each region checks bounds
|
||
least-priority-first; first containing bound wins. GeoJSON features
|
||
(Polygon/MultiPolygon) converted with @turf.
|
||
user-ui:
|
||
- NEW src/store/locationStore.ts: zustand singleton that owns expo-location
|
||
permission + watchPosition fixes (coords/status/error), start/stop/refresh.
|
||
- src/hooks/useRegion.ts: now the location-aware single source of truth. While
|
||
no region is chosen it starts tracking + calls resolveRegionByLocation and
|
||
auto-sets the region; exposes coords/status/bound/isResolvingRegion. Stops
|
||
tracking once a region exists.
|
||
- RegionGate: shows spinner while resolving; only falls back to the chooser
|
||
when location is unavailable/denied/no match.
|
||
|
||
[2026-10-07 15:02:02] user-ui: LocationTestWrapper owns the region chooser fallback.
|
||
- NEW src/lib/is-emulator.ts: extracted emulator/simulator detection.
|
||
- store/locationStore.ts: skip requesting location on emulators (status
|
||
'unavailable'); check Location.hasServicesEnabledAsync(); race the first fix
|
||
against a timeout so a missing GPS fix can no longer hang 'locating'.
|
||
- LocationTestWrapper: rewritten as the region gate. Renders app once a region
|
||
exists; spinner while deriving it from location; full-screen RegionSelector
|
||
when location services are off, permission denied, on a simulator, or no
|
||
bound contains the coordinates. Keeps the stale-region validation.
|
||
- Moved LocationTestWrapper up (FirstUserWrapper) so the gate sits above
|
||
Auth/Notification providers; removed it from app/_layout.tsx.
|
||
- Removed src/components/RegionGate.tsx (superseded by LocationTestWrapper).
|
||
|
||
[2026-10-07 15:20:00] fix: region spinner stuck / infinite re-render.
|
||
- regionStore: setRegion/clearRegion are now no-ops when nothing changes,
|
||
so they no longer bump regionGeneration (and re-render) on every call.
|
||
- useRegion: add resolvedAttempt flag -> isResolvingRegion flips false after
|
||
the first definitive answer and never latches back on 'idle'; stop location
|
||
tracking once settled; memoize/round the resolve query input; 8s resolve
|
||
timeout fallback.
|
||
- locationStore: round coords to ~1m and skip store updates when unchanged,
|
||
so GPS jitter no longer churns a new query key every watch callback.
|
||
- LocationTestWrapper: validation is membership-only (no setRegion in the
|
||
effect), removing a possible self-triggering loop.
|
||
|
||
[2026-10-07 15:24:00] RegionSelector is controlled again (selectedRegionId prop) so
|
||
the chooser no longer calls useRegion / starts location tracking; callers
|
||
(LocationTestWrapper, LocationBar, me) pass the id from their useRegion.
|
||
|
||
[2026-10-07 15:42:21] regions cannot be created without bounds.
|
||
- shared: add RegionBoundSeedInput + CreateRegionWithBoundsInput.
|
||
- db_helper_sqlite: add createRegionWithBounds() (region + bounds inserted
|
||
atomically in one transaction); export it.
|
||
- superadmin regions.create: now requires bounds (min 1, valid GeoJSON +
|
||
numeric priority) and returns { region, bounds }; duplicate priority -> 409.
|
||
- superadmin-ui Regions page: create form now collects at least one bound
|
||
(description/priority/GeoJSON supports multiple rows); legacy empty create
|
||
removed.
|
||
|
||
[2026-10-07 15:58:00] admin-ui logout debug logging added temporarily.
|
||
- (drawer)/_layout.tsx: log on drawer Logout item tap.
|
||
- staff-auth-context.tsx: log on logout() entry and after deleteJWT resolves.
|
||
|
||
[2026-10-07 16:03:00] admin-ui logout: removed the temporary debug console.logs
|
||
(drawer Logout handler and staff-auth-context logout()).
|
||
|
||
[2026-10-07 16:40:00] admin pickers leak cross-region data: fixed.
|
||
- Root cause: three admin-only pickers used public, unscoped common endpoints.
|
||
- common.getStoresSummary: public PROCEDURE aggregating ALL regions -> now
|
||
protectedProcedure returning only the caller staff region's stores.
|
||
- common.product.getAllProductsSummary: aggregated ALL regions -> now
|
||
protectedProcedure returning scaffolledProducts(ctx.staffUser.regionId) only.
|
||
- common.product.getAllSkusSummary: returned ALL SKUs -> protectedProcedure +
|
||
new regionId arg on getAllSkusSummary (default null keeps old signature).
|
||
- Affects admin-ui AND admin-web (both attach the staff JWT). The customer apps
|
||
never call these (they use regional CDN cache files), so no public surface lost.
|
||
|
||
[2026-10-07 17:10:00] fix: essentialConsts returned region-1 values for region 3.
|
||
Root cause: backend scaffold sent per-region settings as `regionSettings`
|
||
but user-ui/web-ui read `effectiveSettings` -> override never applied, so the
|
||
global (region-1-authored) top-level consts showed for every region.
|
||
- backend scaffoldEssentialConsts now returns `effectiveSettings` (canonical)
|
||
plus `regionSettings` alias for KV-cached payloads.
|
||
- user-ui + web-ui read effectiveSettings ?? regionSettings, so even stale KV
|
||
entries resolve correctly without waiting for a KV refresh.
|
||
- After deploy, refresh KV (any const update / cache regen / seed calls
|
||
refreshGenKv) so new payloads carry the canonical field.
|
||
|
||
[2026-10-07 17:25:00] fix: bound mutations now refresh KV.
|
||
- updateBoundSettings wrote D1 only; KV mirror kept stale values.
|
||
Now looks up the bound's region and awaits refreshGenKv(regionId).
|
||
- Same staleness class fixed for createBound and updateBound (a new/changed
|
||
bound can become the effective lowest-priority one).
|
||
|
||
[2026-10-07 17:40:00] fix: essentialConsts top-level fields now carry effective regional values.
|
||
- scaffoldEssentialConsts resolved each business field as bound setting ??
|
||
global const ?? default (numbers parsed, booleans coerced, raw passthrough
|
||
otherwise), instead of storing globals flat next to the nested block.
|
||
- Also exposes minRegularOrderValue/allItemsOrder/welcomeMessage top-level
|
||
(previously nested-only). Helper return types stay `any` so the client
|
||
contract is unchanged; only values changed.
|
||
- Nested effectiveSettings (+regionSettings alias) retained for provenance
|
||
and the client override path. Requires KV refresh post-deploy (any const
|
||
save / cache regen / seed) to rewrite stored payloads.
|
||
|
||
[2026-10-07 17:55:00] essentialConsts payload is now flat: removed the nested
|
||
effectiveSettings/regionSettings block. Top-level fields are the region's
|
||
effective values (bound setting ?? global), so there is nothing nested left
|
||
to re-appear. Clients keep reading the optional nested block only as a
|
||
backward-compat fallback for payloads already cached in KV.
|
||
|
||
[2026-10-08 00:10:10] Part 1/2 - split consts model into three tables (global_consts / region_consts / region_bound_consts) + per-bound flat JSON in KV.
|
||
|
||
Planned diffs (backend + db_helper + admin-ui + admin-web + superadmin-ui; NO migration run; NO tests; NO git):
|
||
|
||
packages/db_helper_sqlite/src/db/schema.ts
|
||
- Add globalConsts(key PK, value), regionConsts(region_id,key PK), regionBoundConsts(bound_id,key PK) tables.
|
||
- Remove regionCacheVersions + regionBoundSettings tables and relations.
|
||
packages/db_helper_sqlite/drizzle/0009_three_const_tables.sql (new, NOT run) + meta/_journal.json idx 9.
|
||
- CREATE 3 tables; copy global / region (versions + region-level keys incl allItemsOrder from effective bound) / bound rows;
|
||
DELETE migrated keys from key_val_store (keep leftovers); DROP region_bound_settings + region_cache_versions.
|
||
packages/db_helper_sqlite/src/lib/const-keys.ts
|
||
- Add GLOBAL_CONST_KEYS / REGION_CONST_KEYS / BOUND_CONST_KEYS / LEGACY_CONST_KEYS; rename cacheVersion -> products_version_num; keep merged CONST_KEYS.
|
||
packages/db_helper_sqlite/src/admin-apis/const.ts
|
||
- Add getAllGlobalConsts/upsertGlobalConsts, getRegionConsts/upsertRegionConsts, getBoundConsts/upsertBoundConsts, getLegacyConsts/upsertLegacyConsts;
|
||
getAllConstants/upsertConstants route by scope. Remove dead global version counters.
|
||
packages/db_helper_sqlite/src/lib/region-cache-versions.ts
|
||
- Back get/incrementRegion* with region_consts rows (products_version_num / availability_version_num / slots_version_num).
|
||
packages/db_helper_sqlite/src/superadmin-apis/regions.ts
|
||
- getBoundSettings/upsertBoundSettings -> region_bound_consts; add getRegionConstants/upsertRegionConstants;
|
||
getEffectiveRegionSettings merged region+bound; add getEffectiveBoundId; getAllRegions + effectiveBoundId; seed defaults on create.
|
||
packages/db_helper_sqlite/src/db/seed.ts + seed.sql, index.ts exports.
|
||
packages/shared/types/region.types.ts - RegionSummary.effectiveBoundId.
|
||
apps/backend/src/lib/const-keys.ts, lib/const-store.ts, lib/gen-store.ts (essentialConsts_{boundId}),
|
||
trpc/apis/common-apis/common-trpc-index.ts (scaffoldEssentialConsts(boundId), essentialConsts {boundId}, listRegions effectiveBoundId, regionSettings merged),
|
||
lib/cloud_cache.ts, lib/flash-delivery-cron.ts, lib/seed.ts, sqliteImporter.ts,
|
||
trpc/apis/admin-apis/apis/const.ts (global/legacy procedures + compat alias), admin-apis/apis/region.ts (region + bound constants),
|
||
superadmin-apis/apis/regions.ts, new superadmin-apis/apis/const.ts router.
|
||
apps/admin-ui + apps/admin-web: customize-app 3 tabs (Global/Region/Bound); popular-items/all-items-order region-scoped; tagsOrder via legacy.
|
||
apps/superadmin-ui: constants.tsx -> superadmin.const.*; regions.tsx region + bound editors.
|
||
Typecheck: db_helper_sqlite, backend, admin-ui, superadmin-ui, admin-web.
|
||
|
||
[2026-10-08 00:29:40] Part 1/2 follow-up — finish the admin UIs (admin-ui, admin-web, superadmin-ui) + move tagsOrder into region_consts.
|
||
|
||
Backend/db (tagsOrder is now region-scoped, per user decision; overrides the plan which kept it legacy):
|
||
packages/db_helper_sqlite/src/lib/const-keys.ts
|
||
- CONST_KEYS/LABELS/TYPES/VISIBILITY/DEFAULTS: add tagsOrder (string, hidden, default '[]').
|
||
- REGION_CONST_KEYS: add 'tagsOrder'; LEGACY_CONST_KEYS: remove 'tagsOrder'.
|
||
apps/backend/src/lib/const-keys.ts
|
||
- REGION_CONST_KEYS: add 'tagsOrder'; LEGACY_CONST_KEYS: remove 'tagsOrder'.
|
||
packages/db_helper_sqlite/drizzle/0009_three_const_tables.sql (NOT run)
|
||
- Copy tagsOrder from key_val_store into region_consts per region; delete it from key_val_store.
|
||
packages/db_helper_sqlite/src/db/seed.ts
|
||
- Remove tagsOrder from legacy seed list (region_defaults now seeds it).
|
||
apps/backend/src/lib/seed.ts
|
||
- Remove tagsOrder from legacy seed list.
|
||
apps/backend/src/trpc/apis/admin-apis/apis/region.ts
|
||
- updateRegionConstants: trigger scheduleStoreInitialization when tagsOrder changes; ignore version-counter keys.
|
||
apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts
|
||
- updateRegionConstants: ignore version-counter keys (read-only).
|
||
apps/backend/src/trpc/apis/common-apis/common.ts
|
||
- scaffoldProducts: read tagsOrder from region_consts (region-scoped) instead of the global key_val_store.
|
||
|
||
Admin UIs (3 tabs Global/Region/Bound; Global holds legacy keys, globals hidden; Region hides version counters; Bound = 5 keys):
|
||
apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx
|
||
- Replace 2-way switch with 3 tabs; global uses admin.const.getGlobalConstants/getLegacyConstants, region uses admin.region.getRegionConstants/updateRegionConstants, bound keeps per-bound Formik; hide tab if no visible keys.
|
||
apps/admin-ui/app/(drawer)/dashboard/customize-app/popular-items.tsx
|
||
apps/admin-ui/app/(drawer)/dashboard/customize-app/all-items-order.tsx
|
||
- Read/write popularItems/allItemsOrder via admin.region.getRegionConstants/updateRegionConstants.
|
||
apps/admin-ui/app/(drawer)/dashboard/product-tags/order.tsx
|
||
- Read/write tagsOrder via admin.region.getRegionConstants/updateRegionConstants.
|
||
apps/admin-ui/components/OrderOptionsMenu.tsx
|
||
- welcomeMessage read via admin.region.getRegionConstants.
|
||
apps/admin-web/src/routes/dashboard.customize-app.tsx
|
||
- 3 tabs as above.
|
||
apps/admin-web/src/routes/dashboard.customize-app.popular.tsx
|
||
apps/admin-web/src/routes/dashboard.customize-app.ordering.tsx
|
||
- Region-scoped popularItems/allItemsOrder.
|
||
apps/admin-web/src/routes/dashboard.product-tags.order.tsx
|
||
- Region-scoped tagsOrder.
|
||
apps/superadmin-ui/src/routes/constants.tsx
|
||
- Use superadmin.const.getGlobalConstants/updateGlobalConstants + getLegacyConstants/updateLegacyConstants; drop region/bound keys.
|
||
apps/superadmin-ui/src/routes/regions.tsx
|
||
- Split into RegionConstantsEditor (superadmin.regions.getRegionConstants/updateRegionConstants, version counters hidden) and BoundSettingsEditor (5 bound keys).
|
||
|
||
web-ui and user-ui untouched. No migrations run. No tests run.
|
||
|
||
[2026-10-08 00:41:00] Part 1/2 follow-up completed. Backend/db_helper/admin-ui/admin-web/superadmin-ui typecheck clean (tsc --noEmit). Migration 0009 NOT run (user runs it). web-ui + user-ui untouched.
|
||
Notes/decisions:
|
||
- Global tab in admin-ui/admin-web shows the legacy leftovers (platformFeePercent,
|
||
minOrderAmountForCoupon, flashDeliverySlotId); the 4 global keys stay hidden there and are
|
||
managed in superadmin-ui. Tab is hidden entirely if it would render no visible keys.
|
||
- Region tab hides the 3 version counters; tagsOrder is edited on the Tag Orders screen
|
||
(admin apps) and in the superadmin Region settings editor (no dedicated tags screen there).
|
||
- List screens send comma-joined ids to the region endpoint (input is a strict scalar union).
|
||
- Stale: apps/admin-ui/tests/** still mock admin.const.getConstants/updateConstants (tests not run).
|
||
|
||
[2026-10-08 00:44:05] Part 2/2 — apps/user-ui consumes the per-bound flat JSON.
|
||
|
||
apps/user-ui/src/store/regionStore.ts
|
||
- Add selectedBoundId (persisted); setRegion(region, boundId?) compares+stores it; clearRegion resets it.
|
||
apps/user-ui/src/hooks/useRegion.ts
|
||
- Expose boundId from the store; on resolve persist setRegion(resolved.region, resolved.bound.id); setRegion signature gains boundId.
|
||
apps/user-ui/src/lib/region-switch.ts
|
||
- confirmRegionSwitch(region, queryClient, boundId?) forwards boundId to setRegion.
|
||
apps/user-ui/src/components/RegionSelector.tsx
|
||
apps/user-ui/components/CheckoutAddressSelector.tsx
|
||
apps/user-ui/components/QuickDeliveryAddressSelector.tsx
|
||
- Pass region.effectiveBoundId to confirmRegionSwitch.
|
||
apps/user-ui/src/hooks/prominent-api-hooks.ts
|
||
- useGetEssentialConsts reads boundId from useRegion, queries { boundId }, persists under essential_consts_b{boundId}.
|
||
- useDiscoveryRegionId reads flat data.regionId (fallback useRegion().regionId).
|
||
- Cache URLs use products_version_num / availability_version_num / slots_version_num.
|
||
- useRegionalConsts is a thin passthrough of the flat payload.
|
||
- Drop DiscoveryData extension + discoverySettings + EffectiveRegionSettings import.
|
||
No tests run. web-ui untouched.
|
||
|
||
[2026-10-08 00:49:00] Part 2/2 completed. apps/user-ui typechecks clean; backend/db/admin apps still clean.
|
||
Deviations/notes:
|
||
- confirmRegionSwitch(region, queryClient, boundId?) defaults boundId to region.effectiveBoundId,
|
||
so the address-selector call sites needed no change; RegionSelector passes it explicitly.
|
||
- useRegion derives boundId = stored ?? region.effectiveBoundId ?? null and backfills a missing
|
||
bound via common.listRegions (covers region state persisted before selectedBoundId existed).
|
||
- useRegionalConsts keeps a loose (any) return so cart/checkout/floating-cart need no edits.
|
||
|
||
[2026-10-08 00:57:00] Globals are superadmin-only: removed the Global tab from the admin apps.
|
||
apps/admin-ui/.../customize-app/index.tsx and apps/admin-web/.../dashboard.customize-app.tsx
|
||
- Drop the Global tab, renderGlobal, global/legacy queries+mutations, GLOBAL_KEYS/LEGACY_KEYS,
|
||
CONST_VISIBILITY; tab switcher is now Region | Bound only. tsc clean.
|
||
- Global + legacy constants remain editable in apps/superadmin-ui/src/routes/constants.tsx.
|
||
Backend note: staff `admin.const.*` (compat getConstants/updateConstants + the new
|
||
getGlobalConstants/updateGlobalConstants/getLegacyConstants/updateLegacyConstants) still exist and
|
||
are pinned by apps/backend/tests; not changed (no production UI caller remains).
|
||
|
||
[2026-10-08 01:12:47] Added packages/db_helper_sqlite/drizzle/merged_regions.sql — one squashed migration replacing 0006_regions_and_superadmins + 0007_region_columns_backfill + 0008_region_cache_versions + 0009_three_const_tables.
|
||
- Drops the two throwaway staging tables (region_bound_settings, region_cache_versions) that the originals created only to copy from and then drop; global_consts / region_consts / region_bound_consts are seeded directly instead.
|
||
- Phase order preserved: (1) regions/region_bounds/superadmins + seeds (from 0006), (2) 0007 region_id rebuild verbatim, (3) const tables + direct seeds (from 0008+0009).
|
||
- Verification: rebuilt SQLite from apps/backend/dumps/latest.sql; applied 0006..0009 -> expected; applied merged_regions.sql -> merged. Python comparison: schema objects 86/86, tables 55/55, rows 21795/21795, IDENTICAL apart from CURRENT_TIMESTAMP seeds (regions.created_at, superadmins.created_at). Also validated D1-style splitting on the statement-breakpoint marker: 187 chunks, 0 failures, integrity ok, same-result. No migrations run against any real DB. No tests run.
|
||
- Follow-up (exact-data check): re-ran 0006..0009 vs merged_regions.sql back-to-back in the same second and compared every row of the 6 new tables + 31 rebuilt tables + key_val_store with no masking -> EXACTLY IDENTICAL (rows: regions 1, region_bounds 2, superadmins 1, global_consts 3, region_consts 10, region_bound_consts 10; all 31 rebuilt tables match row-for-row, e.g. delivery_slot_info 1569, orders 2283, order_items 7959, order_status 2277, reserved_coupons 739; key_val_store 7 leftovers).
|
||
- Squash applied: removed migrations 0006/0007/0008/0009 and replaced them with one file.
|
||
* Backed up the pre-removal contents of 0006_regions_and_superadmins.sql,
|
||
0007_region_columns_backfill.sql, 0008_region_cache_versions.sql and
|
||
0009_three_const_tables.sql into
|
||
packages/db_helper_sqlite/drizzle/stale/removed_region_migrations.txt
|
||
(single txt, one section per file, verbatim).
|
||
* Deleted those four .sql files.
|
||
* Renamed packages/db_helper_sqlite/drizzle/merged_regions.sql ->
|
||
packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql (same
|
||
verified squashed content; staging tables removed).
|
||
* drizzle/meta/_journal.json still lists tags 0007_region_columns_backfill,
|
||
0008_region_cache_versions and 0009_three_const_tables; left untouched
|
||
(user handles migrations) but needs those entries removed to stay consistent.
|
||
* docs/consts-three-tables-part1-backend-admin.md still references
|
||
`0009_three_const_tables`; left as-is.
|
||
No migrations run. No tests run.
|
||
|
||
[2026-10-08 19:28:11] user-ui: startup-only location check (no movement tracking).
|
||
apps/user-ui/src/store/locationStore.ts
|
||
- Remove watchPositionAsync subscription (movement tracking) and coordsEqual; keep a single
|
||
getCurrentPositionAsync (8s timeout). start() idempotent via a per-launch `started` flag.
|
||
apps/user-ui/src/hooks/useRegion.ts
|
||
- Run the location check once on hydration EVEN when a region is saved; never stop/start on regionId.
|
||
- Apply outcome once per launch: same region -> no-op; different -> confirmRegionSwitch(resolved.region,
|
||
queryClient, resolved.bound.id) (clears carts, invalidates region queries); null/denied/unavailable
|
||
-> keep saved region. Single-flight switch guard (module flag) + manual-pick race guard.
|
||
- Rename resolvedAttempt -> startupResolved; isResolvingRegion only for the true first run.
|
||
No backend changes. No tests run.
|
||
|
||
[2026-10-08 19:34:00] startup-only location check implemented. user-ui typecheck clean.
|
||
- locationStore: single getCurrentPositionAsync per launch, no watchPositionAsync.
|
||
- useRegion: check runs on every launch (saved region included); same -> no-op,
|
||
different -> confirmRegionSwitch (option a: clears carts, refreshes screens);
|
||
unusable/null -> keep saved region (or chooser when none). Single-flight switch + manual-pick race guard.
|
||
|
||
[2026-10-08 20:05:00] Checkout constants now come from the DELIVERY ADDRESS's bound (effective bound fallback).
|
||
packages/db_helper_sqlite/src/superadmin-apis/regions.ts
|
||
- add getRegionSettingsForBound(regionId, boundId): region_consts + that bound's region_bound_consts
|
||
(null when the bound does not belong to the region).
|
||
packages/db_helper_sqlite/index.ts - export it.
|
||
apps/backend/src/lib/region-resolve.ts (new)
|
||
- boundToPolygons + resolveBoundForRegionPoint(regionId, lat, lng): first containing bound in
|
||
priority-ascending order.
|
||
apps/backend/src/trpc/apis/user-apis/apis/order.ts
|
||
- placeOrderUtil resolves the bound from the address coords (adminLatitude/Longitude ?? latitude/longitude),
|
||
falls back to getEffectiveBoundId(regionId); bound-level constants (delivery charge/thresholds/min order)
|
||
read via getRegionSettingsForBound. Region-level constants unchanged.
|
||
apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
|
||
- new protectedProcedure common.resolveAddressBound({ addressId }) -> { regionId, boundId } (same resolver).
|
||
apps/user-ui/src/hooks/prominent-api-hooks.ts
|
||
- useGetEssentialConsts uses the selected address's bound (when its region matches) else the browsing bound,
|
||
so displayed delivery constants match what checkout charges.
|
||
Typechecks: db_helper, backend, user-ui clean.
|
||
|
||
[2026-10-08 20:23:32] user-ui: emulators/simulators are treated like physical devices for location.
|
||
apps/user-ui/src/store/locationStore.ts - remove the isEmulator() short-circuit (and import); emulators
|
||
go through the normal permission + getCurrentPositionAsync path (they can supply a mock fix).
|
||
apps/user-ui/components/LocationTestWrapper.tsx - drop the emulator check from the spinner condition
|
||
(and import); update the doc comment.
|
||
apps/user-ui/src/lib/is-emulator.ts left in place (now unused by location code).
|
||
|
||
[2026-10-08 20:30:00] user-ui: log the bound id used for essentialConsts.
|
||
apps/user-ui/src/hooks/prominent-api-hooks.ts - console.log the resolved boundId (+ source/region).
|
||
|
||
[2026-10-08 20:55:00] Active-bound model: addresses carry a bound_id; checkout uses the active bound.
|
||
Data model
|
||
- schema.ts: addresses.boundId (FK region_bounds.id, nullable).
|
||
- shared/types/user.ts: UserAddress.boundId.
|
||
- drizzle/0007_addresses_bound_id.sql (new, NOT run): ADD COLUMN bound_id; backfill existing rows to 1.
|
||
- meta/_journal.json: drop stale 0007/0008/0009 entries; add idx 7 = 0007_addresses_bound_id.
|
||
db_helper (user-apis/address.ts): mapUserAddress.boundId; create/update accept+persist boundId.
|
||
backend
|
||
- user-apis/apis/address.ts: createAddress/updateAddress accept boundId; FIRST address becomes default.
|
||
- user-apis/apis/order.ts: placeOrder accepts boundId; placeOrderUtil uses getRegionSettingsForBound(regionId,boundId)
|
||
(fallback effective). Remove the address-coordinate bound resolution.
|
||
- common-apis/common-trpc-index.ts: remove resolveAddressBound; lib/region-resolve.ts removed.
|
||
user-ui
|
||
- prominent-api-hooks: useGetEssentialConsts uses the active bound only (drop resolveAddressBound override).
|
||
- RegionSelector / region-switch: manual region pick uses the default address's bound (fallback effective).
|
||
- AddressForm / CheckoutAddressSelector / me addresses: send boundId = active bound on create/update.
|
||
- Checkout + quick-delivery address lists filtered to the active bound.
|
||
|
||
[2026-10-08 21:10:00] Active-bound model implemented. Typechecks: db_helper, backend, admin-ui, admin-web,
|
||
superadmin-ui, user-ui clean. (web-ui still has the known flat-JSON errors; out of scope.)
|
||
- addresses.bound_id column + migration 0007 (backfill 1); journal tail fixed.
|
||
- user-ui: manual region pick uses the default address's bound else effective; new addresses get the
|
||
active bound; checkout/quick-delivery lists filtered to the active bound; order sends active boundId.
|
||
- first address a user adds becomes their default.
|
||
- startup location still wins for the active bound.
|
||
|
||
[2026-10-08 21:15:00] user-ui: log coords alongside the bound id in useGetEssentialConsts.
|
||
|
||
[2026-10-09 10:00:00] Active bound from the user's addresses (least-priority bound in the region).
|
||
backend
|
||
- common-apis/common-trpc-index.ts: new common.activeBound({ regionId }) (protected) ->
|
||
least-priority bound among the user's addresses in that region, else the region's effective bound.
|
||
user-ui
|
||
- useRegion: region from location/manual; active bound from common.activeBound (fallback effective),
|
||
persisted via setRegion; no longer uses the location's bound. Derivation runs on region change.
|
||
- prominent-api-hooks: essentialConsts bound = selected checkout address's bound (same region) ?? active bound.
|
||
- CheckoutAddressSelector / QuickDeliveryAddressSelector: show ALL addresses (no bound filter);
|
||
same-region bound selection just re-adjusts consts, cross-region still confirms + switches.
|
||
- PaymentAndOrderComponent: send boundId = the bound used for the displayed consts.
|
||
- RegionSelector: manual pick no longer computes an address bound (derivation handles it).
|
||
|
||
[2026-10-09 10:15:00] activeBound model implemented. Typechecks: db_helper, backend, user-ui clean.
|
||
- common.activeBound({regionId}) -> least-priority bound among the user's addresses in the region,
|
||
else the region's effective bound.
|
||
- useRegion derives the active bound from common.activeBound (fallback effective); location only sets region.
|
||
- useGetEssentialConsts: bound = selected checkout address's bound (same region) ?? active bound.
|
||
- Checkout/quick-delivery address lists show all addresses (all regions/bounds); same-region bound
|
||
selection re-adjusts consts; cross-region still confirms then switches.
|
||
- placeOrder boundId = constsData.boundId (the displayed bound).
|
||
|
||
[2026-10-09 10:30:00] fix: hooks rendered above AuthProvider no longer require it.
|
||
- AuthContext: add useAuthOptional() (returns null instead of throwing when there is no provider).
|
||
- useRegion + prominent-api-hooks use useAuthOptional so UpdateChecker (mounted above AuthProvider)
|
||
no longer throws "useAuth must be used within an AuthProvider". Typecheck clean.
|
||
|
||
[2026-10-09 10:35:00] user-ui: comment out the essentialConsts boundId/coords console log (kept for later).
|
||
|
||
[2026-10-09 10:45:00] user-ui: address selector moves to the cart page; checkout shows it read-only.
|
||
- new components/CheckoutAddressDisplay.tsx: read-only card for the selected (or default) address.
|
||
- components/cart-page.tsx: render CheckoutAddressSelector (interactive) at the top of the scroll.
|
||
- components/checkout-page.tsx: replace CheckoutAddressSelector with CheckoutAddressDisplay;
|
||
drop the add-address dialog + AddressForm from checkout (no changing there).
|
||
|
||
[2026-10-09 10:55:00] done. user-ui typecheck clean.
|
||
- cart-page shows the interactive CheckoutAddressSelector (top of the scroll, non-empty cart).
|
||
- checkout-page shows CheckoutAddressDisplay (read-only; selected or default address); add-address
|
||
dialog + AddressForm removed from checkout.
|
||
|
||
[2026-10-09 11:05:00] user-ui: cart page behind the login wall (useAuthenticatedRoute), covering both routes.
|
||
|
||
[2026-10-09 11:20:00] user-ui: fix cart login-wall back-loop. Replace the push-based useAuthenticatedRoute
|
||
on the cart with an inline gate (renders a login prompt when signed out) so back navigation works.
|
||
|
||
[2026-10-09 11:35:00] user-ui: extract the login wall into components/LoginWall.tsx; use it on the cart and the me tab.
|
||
- cart-page uses <LoginWall onBack=... />; me/_layout renders <LoginWall /> when signed out (replaces
|
||
the push-based useAuthenticatedRoute on the me tab).
|
||
|
||
[2026-10-09 11:45:00] done. components/LoginWall.tsx (title/message/onBack); cart-page + me/_layout use it.
|
||
me/_layout no longer uses useAuthenticatedRoute (checkout still does). user-ui typecheck clean.
|
||
|
||
[2026-10-09 12:00:00] user-ui: post-login returns to the intended page.
|
||
- LoginWall records the current pathname in AUTH_REDIRECT_KEY before pushing /(auth)/login.
|
||
- AuthContext.handlePostLoginRedirect now router.replace(targetPath) (was router.back()), so the
|
||
user lands on the page they were gated from (cart/me/checkout), not home. user-ui typecheck clean.
|
||
|
||
[2026-10-09 12:10:00] user-ui cart: address selector moved below the items; "Go to 1 Hr Delivery" switcher
|
||
card hidden ({false && ...}). user-ui typecheck clean.
|
||
|
||
[2026-10-09 12:20:00] user-ui CheckoutAddressSelector: show "No Location is attached to address" above the
|
||
Attach Current Location button when the selected address has no coordinates.
|
||
|
||
[2026-10-09 12:30:00] user-ui cart: move the address selector to just above the Bill Details section.
|
||
|
||
[2026-10-09 12:45:00] user-ui: instructions move to the cart; checkout becomes a read-only summary.
|
||
- new src/store/checkoutStore.ts (userNotes) shared between cart + checkout.
|
||
- cart-page: "Delivery Instructions" input above the address selector (bound to checkoutStore).
|
||
- PaymentAndOrderComponent: read userNotes from the store; remove its inline instructions input.
|
||
- checkout-page: read-only summary cards for Items, Delivery Slot, Coupon (address + bill already shown).
|
||
|
||
[2026-10-09 12:55:00] done. user-ui typecheck clean.
|
||
- checkoutStore (userNotes); cart has the Delivery Instructions input above the address selector;
|
||
PaymentAndOrderComponent reads userNotes from the store (input removed) and still sends it with the order.
|
||
- checkout-page shows read-only Items / Delivery Slot / Coupon cards + address + bill.
|
||
|
||
[2026-10-09 13:05:00] user-ui cart: move the Delivery Slot Summary to right after the items (before coupons).
|
||
(Checkout page already shows Items -> Delivery Slot -> Coupon -> Address -> Bill.) typecheck clean.
|
||
|
||
[2026-10-09 13:15:00] user-ui checkout: Items section now groups by delivery slot (slot time header, then its
|
||
items), slots sorted by time; removed the separate Delivery Slot card. typecheck clean.
|
||
|
||
[2026-10-09 13:20:00] user-ui checkout: give the slot-time header a subtle spotlight (pill background,
|
||
brand icon, semibold text).
|
||
|
||
[2026-10-09 13:30:00] user-ui checkout: add a "Back to Cart" button above the Place Order button.
|
||
|
||
[2026-10-09 13:40:00] BUG B02 fix: signed-out users had no active bound (consts/products empty).
|
||
- common.activeBound publicProcedure: signed-in -> least-priority address bound; signed-out -> region effective bound.
|
||
- useRegion: propagate the location-resolved bound again (same-region -> setRegion(region,bound.id);
|
||
region change -> confirmRegionSwitch(region,qc,resolved.bound.id)); activeBound query no longer auth-gated.
|
||
|
||
[2026-10-10 12:35:00] Testing session round 1 (docs/test-cases-multi-region.md).
|
||
- Verified: superadmin login + regions editors (SU-1..SU-3), user-app fresh-start region resolve,
|
||
me-tab login wall, wall -> login navigation (U-1, U-6 Me-tab, U-7 up to credentials).
|
||
- Found + fixed B02 (signed-out users had no active bound -> no consts/products; activeBound now
|
||
public + location bound propagated). Verified products + free-delivery threshold on device.
|
||
- Blocked: password typing into the secure field on the iOS simulator never lands (harness quirk);
|
||
password login could not be automated -> cart/checkout cases pending a manual sign-in or OTP.
|
||
- Environment notes: openLink required for chromium flows; scrollUntilVisible on the admin regions
|
||
page; text-node assertions unreliable on the RN app -> driven by point-taps + screenshots.
|
||
|
||
[2026-10-10 00:20:52 +0530] Added docs/e2e-sanity-test-plan.md following workflow/code inspection.
|
||
- Cross-app journey checklist covering configuration, auth, catalog publication, slots, carts,
|
||
addresses/bounds, bill parity, coupons, COD fulfillment, flash, vendors, support and recovery.
|
||
- Separate API authorization/invariant release gates and future payment/refund readiness cases.
|
||
- Recommended daily sanity subset, staging fixtures, bounded cache waits, evidence and policy gaps.
|
||
- No application source changed; no tests, migrations or git commands executed.
|
||
|
||
[2026-10-10 00:31:41 +0530] Updated docs/e2e-sanity-test-plan.md per user request.
|
||
- All login/setup flows are password-only; OTP/SMS testing explicitly excluded.
|
||
- Replaced OTP authentication and OTP-created-account cases with password identifier
|
||
coverage and password-change/re-login coverage, preserving existing case IDs.
|
||
|
||
[2026-10-10 01:31:35 +0530] Added docs/e2e-sanity-test-results.md (execution results for the plan).
|
||
- Ran high-risk + daily-sanity subset via Maestro (iOS customer/admin apps) and direct
|
||
tRPC probes: RG-01/02/03/06/10, SEC-01..05, BL-01/02/03/06, CP-01, AU-01/05,
|
||
CT-01/04/08/09, AD-05, OR-01, SL-01, PD-01/02, PAY-01.
|
||
- Confirmed 9 defects (D1..D9): customer token can mutate global consts (critical);
|
||
cross-region SKU + unassigned/OOS SKU accepted by placeOrder; client/backend
|
||
delivery-fee formula divergence (₹200 / ₹20 mismatches); min-order not enforced;
|
||
non-atomic region create on D1; 500-instead-of-404; instructions persist post-order.
|
||
- No application source changed. Created test-only staff/products/slots/coupon/orders
|
||
in the disposable local DB via the app's own admin/superadmin APIs. Removed the
|
||
half-created region (id 4) left by the RG-02 bug.
|
||
|
||
[2026-10-10 09:25:57 +0530] Continued docs/e2e-sanity-test-results.md — full second pass (~108/133 cases).
|
||
- Added results for categories B (auth), C (products), D (discovery), E (slots),
|
||
G (addresses), H (bill), I (coupons), J (orders), K (flash), L (vendor/support),
|
||
and SEC-06/07/08. Extended the defect list to D1..D19.
|
||
- New confirmed defects: D12 deleteProductTag FK failure; D13 deleteStore orphans
|
||
products; D14 frozen slot accepted by placeOrder; D15 updatePassword duplicates
|
||
user_creds (no effect); D16 updateProfile 500 (ctx.req.header); D17 no order
|
||
idempotency; D18 incoherent address region/bound; D19 auth 500 vs 401.
|
||
- Restored the disposable DB to baseline after testing (store 1 + 41 products,
|
||
region consts, slot membership, product flags). No source changed.
|
||
|
||
[2026-10-10 09:52:53 +0530] Third pass on docs/e2e-sanity-test-results.md (~120/133 cases).
|
||
- Ran the remaining API cases (BL-04/05, CP-02/07/08, PD-07/10/11, DS-05/07, FL-04)
|
||
and UI cases (AU-02 cart-survives-login, AU-06 logout, AU-07 edit-profile, CT-03/06/07/10,
|
||
DS-08 search) plus simulator GPS cases (RG-04, RG-08).
|
||
- New defect D20: the cart does not reflect an out-of-stock item (stays orderable).
|
||
- Notes: region B bound has an empty polygon (GPS can never resolve to B); logout does
|
||
not clear the local cart; first-order/SKU/user/region coupon restrictions partly missing.
|
||
- Restored flash=false, removed extra slots/fixtures. No application source changed.
|
||
|
||
[2026-10-10 09:58:00 +0530] Added docs/e2e-sanity-failed-cases.md (detailed failure report).
|
||
- One section per FAIL case (FC-01..FC-20): symptom, repro steps, expected vs actual,
|
||
evidence (order/entity ids), root cause with file/function, and suggested fix.
|
||
- Cross-linked from docs/e2e-sanity-test-results.md. No application source changed.
|
||
|
||
[2026-10-10 10:05:00 +0530] Added docs/maestro-mcp-agent-guidelines.md (field guide for future agents).
|
||
- Environment map, golden rules, working Maestro run patterns, iOS/web gotchas
|
||
(hideKeyboard, masked secure fields, eraseText/pasteText, deep-link alert,
|
||
screenshots/inspect_screen, permissions, simctl location), tRPC wire format,
|
||
cache/versioning, fixtures, verified recipes, false-positive list, run checklist.
|
||
- No application source changed.
|
||
|
||
[2026-10-10 10:26:19 +0530] .gitignore: ignore generated Expo native iOS projects (prebuild/CocoaPods output).
|
||
- These are created by `expo run:ios` (Podfile, Podfile.lock, Pods/, xcodeproj, build/)
|
||
and are build artifacts, not source; matches the existing apps/*/android/ rules.
|
||
|
||
--- a/.gitignore
|
||
+++ b/.gitignore
|
||
@@
|
||
apps/user-ui/android/
|
||
apps/admin-ui/android/
|
||
+apps/user-ui/ios/
|
||
+apps/admin-ui/ios/
|
||
.maestro-output/*
|
||
|
||
[2026-10-10 10:35:35 +0530] FC-01 (SEC-01): lock down admin.const router; delete dead global/legacy procedures.
|
||
- No production UI caller existed (admin apps use admin.region.*; superadmin UI uses
|
||
superadmin.const.*), so the four admin global/legacy procedures are removed. The two
|
||
surviving compat procedures now require a staff token; updateConstants additionally
|
||
rejects global-scope keys (globals are superadmin-only).
|
||
|
||
--- a/apps/backend/src/trpc/apis/admin-apis/apis/const.ts
|
||
+++ b/apps/backend/src/trpc/apis/admin-apis/apis/const.ts
|
||
@@
|
||
-import { router, protectedProcedure } from '@/src/trpc/trpc-index'
|
||
+import { router, staffProcedure } from '@/src/trpc/trpc-index'
|
||
import { z } from 'zod';
|
||
+import { TRPCError } from '@trpc/server'
|
||
import { computeConstants } from '@/src/lib/const-store'
|
||
import { refreshGenKv, refreshGenKvForRegion } from '@/src/lib/gen-store'
|
||
import { CONST_SCOPE } from '@/src/lib/const-keys'
|
||
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
|
||
import {
|
||
getAllConstants as getAllConstantsFromDb,
|
||
upsertConstants as upsertConstantsInDb,
|
||
- getAllGlobalConsts,
|
||
- upsertGlobalConsts,
|
||
- getLegacyConsts,
|
||
- upsertLegacyConsts,
|
||
} from '@/src/dbService'
|
||
@@
|
||
-const toRows = (constants: Constant[]) =>
|
||
- constants.map((c) => ({ key: c.key, value: c.value == null ? null : String(c.value) }))
|
||
-
|
||
export const constRouter = router({
|
||
// Backward-compat: merged global + legacy view. Writes route by key scope.
|
||
- getConstants: protectedProcedure
|
||
+ getConstants: staffProcedure
|
||
.query(async (): Promise<Constant[]> => {
|
||
return getAllConstantsFromDb();
|
||
}),
|
||
|
||
- updateConstants: protectedProcedure
|
||
+ updateConstants: staffProcedure
|
||
.input(constantsInput)
|
||
.mutation(async ({ input, ctx }): Promise<ConstantUpdateResult> => {
|
||
const { constants } = input;
|
||
|
||
const invalidKeys = constants
|
||
.filter(c => !CONST_SCOPE[c.key])
|
||
.map(c => c.key);
|
||
|
||
if (invalidKeys.length > 0) {
|
||
throw new Error(`Invalid constant keys: ${invalidKeys.join(', ')}`);
|
||
}
|
||
|
||
+ // Global constants (versionNum, playStoreUrl, …) are superadmin-only and are
|
||
+ // managed via superadmin.const.*. Never let a region staff token write them
|
||
+ // through the merged route.
|
||
+ const globalKeys = constants
|
||
+ .filter((c) => CONST_SCOPE[c.key] === 'global')
|
||
+ .map((c) => c.key)
|
||
+
|
||
+ if (globalKeys.length > 0) {
|
||
+ throw new TRPCError({
|
||
+ code: 'FORBIDDEN',
|
||
+ message: `Global constants are superadmin-only: ${globalKeys.join(', ')}`,
|
||
+ })
|
||
+ }
|
||
+
|
||
const regionId = ctx.staffUser?.regionId ?? null
|
||
await upsertConstantsInDb(constants, regionId ?? undefined)
|
||
...
|
||
}),
|
||
-
|
||
- // Global consts (global_consts table).
|
||
- getGlobalConstants: protectedProcedure
|
||
- .query(async (): Promise<Constant[]> => {
|
||
- const values = await getAllGlobalConsts()
|
||
- return Object.entries(values).map(([key, value]) => ({ key, value }))
|
||
- }),
|
||
-
|
||
- updateGlobalConstants: protectedProcedure
|
||
- .input(constantsInput)
|
||
- .mutation(async ({ input }): Promise<ConstantUpdateResult> => {
|
||
- await upsertGlobalConsts(toRows(input.constants))
|
||
- await computeConstants()
|
||
- await refreshGenKv()
|
||
- return {
|
||
- success: true,
|
||
- updatedCount: input.constants.length,
|
||
- keys: input.constants.map(c => c.key),
|
||
- }
|
||
- }),
|
||
-
|
||
- // Legacy leftovers (key_val_store table).
|
||
- getLegacyConstants: protectedProcedure
|
||
- .query(async (): Promise<Constant[]> => {
|
||
- const values = await getLegacyConsts()
|
||
- return Object.entries(values).map(([key, value]) => ({ key, value }))
|
||
- }),
|
||
-
|
||
- updateLegacyConstants: protectedProcedure
|
||
- .input(constantsInput)
|
||
- .mutation(async ({ input }): Promise<ConstantUpdateResult> => {
|
||
- await upsertLegacyConsts(toRows(input.constants))
|
||
- await computeConstants()
|
||
- if (input.constants.some((c) => CACHE_AFFECTING_KEYS.includes(c.key))) {
|
||
- await scheduleStoreInitialization()
|
||
- }
|
||
- return {
|
||
- success: true,
|
||
- updatedCount: input.constants.length,
|
||
- keys: input.constants.map(c => c.key),
|
||
- }
|
||
- }),
|
||
});
|
||
|
||
--- a/apps/backend/tests/api/authorization-matrix.test.ts
|
||
+++ b/apps/backend/tests/api/authorization-matrix.test.ts
|
||
@@
|
||
- it('pins: a user token CAN change config via admin.const.updateConstants', async () => {
|
||
- const before = await getConstants()
|
||
- const original = before.minOrderAmountForCoupon
|
||
-
|
||
- try {
|
||
- await apiClient(userToken).admin.const.updateConstants.mutate({
|
||
- constants: [{ key: 'minOrderAmountForCoupon', value: 4321 }],
|
||
- })
|
||
- expect(asNumber((await getConstants()).minOrderAmountForCoupon)).toBe(4321)
|
||
- } finally {
|
||
- if (original !== undefined) await setConst('minOrderAmountForCoupon', original)
|
||
- }
|
||
- })
|
||
-
|
||
// ...moved to the "staff-guarded admin procedures" block, inverted:
|
||
+ it('rejects a user token on admin.const.updateConstants', async () => {
|
||
+ const error = await captureError(() =>
|
||
+ apiClient(userToken).admin.const.updateConstants.mutate({
|
||
+ constants: [{ key: 'minOrderAmountForCoupon', value: 4321 }],
|
||
+ })
|
||
+ )
|
||
+ expect(error.message).toMatch(/UNAUTHORIZED|unauthorized/i)
|
||
+ })
|
||
+
|
||
+ it('rejects a staff token writing a global constant via admin.const.updateConstants', async () => {
|
||
+ const staff = await staffSession()
|
||
+ const error = await captureError(() =>
|
||
+ apiClient(staff.token).admin.const.updateConstants.mutate({
|
||
+ constants: [{ key: 'versionNum', value: '9.9.9' }],
|
||
+ })
|
||
+ )
|
||
+ expect(error.message).toMatch(/superadmin-only/i)
|
||
+ })
|
||
- it('rejects a user token on admin.coupon.create', async () => { ... }) [kept]
|
||
(also drops now-unused imports asNumber/getConstants/setConst if no longer referenced)
|
||
|
||
Docs (no code): apps/backend/tests/BUGS.md entry #1 (drop admin.const.updateConstants from
|
||
the reachable list); docs/e2e-sanity-failed-cases.md FC-01 + docs/e2e-sanity-test-results.md D1
|
||
marked fixed. No migrations run. No tests run.
|
||
|
||
[2026-10-10 10:45:42 +0530] FC-02/FC-03/FC-13: validate order items and slots in placeOrderUtil.
|
||
- New helper getDeliverySlotById (raw slot row) in user-apis/slots.ts, exported as
|
||
getUserDeliverySlotById. placeOrderUtil now:
|
||
* per item: product region must equal the order region (409); product must not be
|
||
isDeleted / isOutOfStock / isSuspended (400).
|
||
* per slot (scheduled only): slotId must be non-null; slot must exist, belong to the
|
||
region (409), be isActive, have freezeTime > now and deliveryTime > now, and carry
|
||
every ordered skuId in slot.skuIds (400).
|
||
Covers FC-02 (cross-region SKU), FC-03 (unassigned/OOS) and FC-13 (frozen slot).
|
||
- No schema/migration changes.
|
||
|
||
--- a/packages/db_helper_sqlite/src/user-apis/slots.ts
|
||
+++ b/packages/db_helper_sqlite/src/user-apis/slots.ts
|
||
@@
|
||
export async function getActiveSlotsList(regionId: number): Promise<UserDeliverySlot[]> {
|
||
+
|
||
+export async function getDeliverySlotById(slotId: number): Promise<SlotRow | null> {
|
||
+ const slot = await db.query.deliverySlotInfo.findFirst({
|
||
+ where: eq(deliverySlotInfo.id, slotId),
|
||
+ })
|
||
+ return slot ?? null
|
||
+}
|
||
|
||
--- a/packages/db_helper_sqlite/index.ts
|
||
+++ b/packages/db_helper_sqlite/index.ts
|
||
@@
|
||
export {
|
||
// User Slots
|
||
getActiveSlotsList as getUserActiveSlotsList,
|
||
getProductAvailability as getUserProductAvailability,
|
||
+ getDeliverySlotById as getUserDeliverySlotById,
|
||
} from './src/user-apis/slots'
|
||
|
||
--- a/apps/backend/src/trpc/apis/user-apis/apis/order.ts
|
||
+++ b/apps/backend/src/trpc/apis/user-apis/apis/order.ts
|
||
@@
|
||
import {
|
||
...
|
||
getUserSlotCapacityStatus,
|
||
+ getUserDeliverySlotById,
|
||
...
|
||
} from "@/src/dbService";
|
||
@@
|
||
for (const item of selectedItems) {
|
||
const product = await getOrderProductById(item.skuId);
|
||
if (!product) {
|
||
throw new ApiError(`Product ${item.skuId} not found`, 400);
|
||
}
|
||
+
|
||
+ // SEC-04: the SKU must belong to the region being ordered into.
|
||
+ if ((product.product?.regionId ?? null) !== params.regionId) {
|
||
+ throw new ApiError(`Product ${item.skuId} is not available in this region`, 409);
|
||
+ }
|
||
+
|
||
+ // SEC-05: never sell a deleted, out-of-stock or suspended product.
|
||
+ if (product.isDeleted || product.isOutOfStock || product.marketStats?.isSuspended) {
|
||
+ throw new ApiError(`Product ${item.skuId} is unavailable`, 400);
|
||
+ }
|
||
+
|
||
if (!ordersBySlot.has(item.slotId)) { ... }
|
||
}
|
||
@@
|
||
if (params.isFlash) { ... }
|
||
+
|
||
+// SEC-05 / SL-04: validate every scheduled slot (existence, region, state,
|
||
+// freeze/delivery time) and that it carries the ordered SKUs.
|
||
+if (!params.isFlash) {
|
||
+ for (const [slotId, items] of ordersBySlot) {
|
||
+ if (slotId == null) throw new ApiError("A delivery slot is required for scheduled orders", 400);
|
||
+ const slot = await getUserDeliverySlotById(slotId);
|
||
+ if (!slot) throw new ApiError("Selected delivery slot not found", 400);
|
||
+ if (slot.regionId !== params.regionId)
|
||
+ throw new ApiError("Selected delivery slot belongs to a different region", 409);
|
||
+ if (!slot.isActive) throw new ApiError("Selected delivery slot is not available", 400);
|
||
+ const now = Date.now();
|
||
+ if (slot.freezeTime.getTime() <= now)
|
||
+ throw new ApiError("Selected delivery slot is closed for orders", 400);
|
||
+ if (slot.deliveryTime.getTime() <= now)
|
||
+ throw new ApiError("Selected delivery slot has already passed", 400);
|
||
+ const slotSkuIds = new Set(slot.skuIds ?? []);
|
||
+ for (const item of items) {
|
||
+ if (!slotSkuIds.has(item.skuId))
|
||
+ throw new ApiError(`Product ${item.skuId} is not available in the selected delivery slot`, 400);
|
||
+ }
|
||
+ }
|
||
+}
|
||
|
||
--- a/apps/backend/tests/api/place-order-edge-cases.test.ts
|
||
+++ b/apps/backend/tests/api/place-order-edge-cases.test.ts
|
||
@@
|
||
- const place = (over) => apiClient(userToken).user.order.placeOrder.mutate({
|
||
- selectedItems: [{ skuId, quantity: 1, slotId }], addressId, paymentMethod: 'cod', ...over })
|
||
+ const place = (over) => apiClient(userToken).user.order.placeOrder.mutate({
|
||
+ selectedItems: [{ skuId, quantity: 1, slotId }], addressId, regionId: 1,
|
||
+ paymentMethod: 'cod', ...over })
|
||
@@
|
||
- it('pins: an out-of-stock product is still orderable', ... expect(res.success).toBe(true)
|
||
+ it('rejects an out-of-stock product', ... expect(error.message).toMatch(/unavailable/i)
|
||
- it('pins: an inactive slot is accepted', ... expect(res.success).toBe(true)
|
||
+ it('rejects an inactive slot', ... expect(error.message).toMatch(/not available/i)
|
||
- it('pins: a slot whose delivery time has passed is accepted', ...
|
||
+ it('rejects a slot whose delivery time has passed', ...
|
||
- it('pins: a slot that does not carry the ordered SKU is accepted', ...
|
||
+ it('rejects a slot that does not carry the ordered SKU', ... /not available in the selected/i)
|
||
|
||
Docs (no code): apps/backend/tests/BUGS.md #13/#16; docs/e2e-sanity-failed-cases.md
|
||
FC-02/FC-03/FC-13 + docs/e2e-sanity-test-results.md SEC-04/SEC-05/SL-04/D2/D3/D14.
|
||
No migrations run. No tests run.
|
||
|
||
[2026-10-10 10:52:10 +0530] Test fixtures: pass the now-required regionId (1) to user.address.createAddress.
|
||
- Pre-existing staleness (createAddress requires regionId since the multi-region work);
|
||
matches the existing Mahabubnagar/region-1 assumption in these fixtures.
|
||
|
||
--- a/apps/backend/tests/helpers/fixtures.ts
|
||
+++ b/apps/backend/tests/helpers/fixtures.ts
|
||
@@
|
||
const created = await client.user.address.createAddress.mutate({
|
||
+ regionId: 1,
|
||
name: 'API Test Address',
|
||
phone: '9999999999',
|
||
addressLine1: '1 API Test Street',
|
||
city: 'Mahabubnagar',
|
||
state: 'Telangana',
|
||
pincode: '509001',
|
||
isDefault: true,
|
||
})
|
||
(applied to both ensureUserAddress and registerUserWithAddress)
|
||
|
||
[2026-10-10 11:24:13 +0530] FC-07/FC-08: backend placeOrder now uses the customer app's pricing model.
|
||
- Threshold key: minRegularOrderValue -> freeDeliveryThreshold (flash unchanged).
|
||
- Discount computed on the whole cart subtotal (frontend formula: percent
|
||
min(subtotal*pct/100, maxValue || Infinity); flat min(flat, maxValue || subtotal)),
|
||
then delivery decided on the post-discount total: finalTotal < threshold ? charge : 0.
|
||
- Per suborder: discount allocated by subtotal proportion; delivery charge kept on the
|
||
first suborder; total = subOrderTotal - orderDiscount + orderDelivery.
|
||
- Drops the applyDiscountToUserOrder call (percent coupon no longer discounts delivery).
|
||
- No nested ternaries. No schema/migration changes.
|
||
|
||
--- a/apps/backend/src/trpc/apis/user-apis/apis/order.ts
|
||
+++ b/apps/backend/src/trpc/apis/user-apis/apis/order.ts
|
||
@@
|
||
import {
|
||
- applyDiscountToUserOrder,
|
||
cancelUserOrderTransaction,
|
||
...
|
||
} from "@/src/dbService";
|
||
@@
|
||
- const minOrderValue = isFlashDelivery
|
||
+ const freeDeliveryThreshold = isFlashDelivery
|
||
? numSetting(CONST_KEYS.flashFreeDeliveryThreshold)
|
||
- : numSetting(CONST_KEYS.minRegularOrderValue);
|
||
+ : numSetting(CONST_KEYS.freeDeliveryThreshold);
|
||
@@
|
||
const appliedCoupon = await validateAndGetUserCoupon(couponId, userId, totalAmount);
|
||
-const expectedDeliveryCharge = totalAmount < minOrderValue ? deliveryCharge : 0;
|
||
-const totalWithDelivery = totalAmount + expectedDeliveryCharge;
|
||
+let discountAmount = 0;
|
||
+if (appliedCoupon) {
|
||
+ const maxValue = appliedCoupon.maxValue ? parseFloat(appliedCoupon.maxValue.toString()) : 0;
|
||
+ if (appliedCoupon.discountPercent) {
|
||
+ const percentDiscount = (totalAmount * parseFloat(appliedCoupon.discountPercent.toString())) / 100;
|
||
+ discountAmount = Math.min(percentDiscount, maxValue || Infinity);
|
||
+ } else if (appliedCoupon.flatDiscount) {
|
||
+ const flat = parseFloat(appliedCoupon.flatDiscount.toString());
|
||
+ discountAmount = Math.min(flat, maxValue || totalAmount);
|
||
+ }
|
||
+}
|
||
+const finalTotal = totalAmount - discountAmount;
|
||
+const expectedDeliveryCharge = finalTotal < freeDeliveryThreshold ? deliveryCharge : 0;
|
||
+const totalWithDelivery = finalTotal + expectedDeliveryCharge;
|
||
@@
|
||
- const subOrderTotalWithDelivery = subOrderTotal + expectedDeliveryCharge;
|
||
- const orderGroupProportion = subOrderTotal / totalAmount;
|
||
- const orderTotalAmount = isFirstOrder ? subOrderTotalWithDelivery : subOrderTotal;
|
||
- const { finalOrderTotal: finalOrderAmount } = applyDiscountToUserOrder(
|
||
- orderTotalAmount, appliedCoupon, orderGroupProportion)
|
||
+ const orderGroupProportion = totalAmount > 0 ? subOrderTotal / totalAmount : 0;
|
||
+ const orderDiscount = discountAmount * orderGroupProportion;
|
||
+ const orderDelivery = isFirstOrder ? expectedDeliveryCharge : 0;
|
||
+ const finalOrderAmount = subOrderTotal - orderDiscount + orderDelivery;
|
||
@@
|
||
- deliveryCharge: isFirstOrder ? expectedDeliveryCharge.toString() : "0",
|
||
+ deliveryCharge: orderDelivery.toString(),
|
||
|
||
--- a/apps/backend/tests/api/coupon-math.test.ts
|
||
+++ b/apps/backend/tests/api/coupon-math.test.ts
|
||
@@
|
||
apiClient(userToken).user.order.placeOrder.mutate({
|
||
selectedItems: items,
|
||
addressId,
|
||
+ regionId: 1,
|
||
paymentMethod: 'cod',
|
||
@@
|
||
-it('pins: a percentage coupon discounts the delivery fee too', ...
|
||
- expect(total(res)).toBeCloseTo((UNIT_PRICE + deliveryCharge) * 0.9, 6)
|
||
+it('applies a percentage coupon to the goods subtotal only', ...
|
||
+ expect(total(res)).toBeCloseTo(UNIT_PRICE * 0.9 + deliveryCharge, 6)
|
||
@@
|
||
-it('pins: a 100% coupon zeroes the order without going negative', ...
|
||
- expect(total(res)).toBe(0)
|
||
+it('a 100% coupon zeroes the goods but still adds delivery', ...
|
||
+ expect(total(res)).toBe(deliveryCharge)
|
||
(header comment updated; coupon-math is otherwise stale w.r.t. the region/bound refactor)
|
||
|
||
Docs (no code): apps/backend/tests/BUGS.md #6 (fixed); docs/e2e-sanity-failed-cases.md
|
||
FC-07/FC-08 + docs/e2e-sanity-test-results.md BL-03/BL-06/D4/D5/D10.
|
||
No migrations run. No tests run.
|
||
|
||
[2026-10-10 11:32:49 +0530] Remove the dead `minRegularOrderValue` bound constant (resolves FC-06).
|
||
- It was not enforced as a minimum and no longer used as the delivery threshold.
|
||
Removed from both const-key registries, the essential-consts payload, the web-ui
|
||
hook, the three admin/superadmin bound editors, the sqlite/postgres seeds, and the
|
||
two tests that read it (now use freeDeliveryThreshold).
|
||
- NOT touched: applied migration 0006 (still seeds a row) — a future migration should
|
||
stop seeding it / delete the orphan region_bound_consts rows; user owns migrations.
|
||
|
||
--- a/apps/backend/src/lib/const-keys.ts
|
||
+++ b/apps/backend/src/lib/const-keys.ts
|
||
@@ CONST_KEYS / CONST_LABELS / CONST_TYPES / CONST_VISIBILITY / BOUND_CONST_KEYS
|
||
- minRegularOrderValue: 'minRegularOrderValue',
|
||
- minRegularOrderValue: 'Minimum Regular Order Value',
|
||
- minRegularOrderValue: 'number',
|
||
- minRegularOrderValue: true,
|
||
- 'minRegularOrderValue', 'freeDeliveryThreshold', 'deliveryCharge',
|
||
+ 'freeDeliveryThreshold', 'deliveryCharge',
|
||
|
||
--- a/packages/db_helper_sqlite/src/lib/const-keys.ts
|
||
+++ b/packages/db_helper_sqlite/src/lib/const-keys.ts
|
||
@@ CONST_KEYS / CONST_LABELS / CONST_TYPES / CONST_VISIBILITY / CONST_DEFAULTS / BOUND_CONST_KEYS
|
||
- minRegularOrderValue: 'minRegularOrderValue',
|
||
- minRegularOrderValue: 'Minimum Regular Order Value',
|
||
- minRegularOrderValue: 'number',
|
||
- minRegularOrderValue: true,
|
||
- minRegularOrderValue: 300,
|
||
- 'minRegularOrderValue', 'freeDeliveryThreshold', 'deliveryCharge',
|
||
+ 'freeDeliveryThreshold', 'deliveryCharge',
|
||
|
||
--- a/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
|
||
+++ b/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
|
||
@@
|
||
- minRegularOrderValue: pickNumber(boundConsts['minRegularOrderValue'], 0),
|
||
freeDeliveryThreshold: pickNumber(boundConsts['freeDeliveryThreshold'], 200),
|
||
|
||
--- a/apps/web-ui/src/hooks/prominent-api-hooks.ts
|
||
+++ b/apps/web-ui/src/hooks/prominent-api-hooks.ts
|
||
@@
|
||
- minRegularOrderValue: pickNumber('minRegularOrderValue', (data as any)?.minRegularOrderValue),
|
||
}
|
||
|
||
--- a/apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx
|
||
+++ a/apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx
|
||
@@ BOUND_KEYS / CONST_LABELS / KEY_TYPES
|
||
- 'minRegularOrderValue', 'freeDeliveryThreshold', 'deliveryCharge',
|
||
+ 'freeDeliveryThreshold', 'deliveryCharge',
|
||
- minRegularOrderValue: 'Minimum Regular Order Value',
|
||
- minRegularOrderValue: 'number',
|
||
|
||
--- a/apps/admin-web/src/routes/dashboard.customize-app.tsx
|
||
+++ b/apps/admin-web/src/routes/dashboard.customize-app.tsx
|
||
@@ (same three removals as admin-ui)
|
||
|
||
--- a/apps/superadmin-ui/src/routes/regions.tsx
|
||
+++ b/apps/superadmin-ui/src/routes/regions.tsx
|
||
@@ SETTING_KEYS / SETTING_LABELS
|
||
- 'minRegularOrderValue',
|
||
- minRegularOrderValue: 'Minimum Regular Order Value',
|
||
|
||
--- a/packages/db_helper_sqlite/src/db/seed.sql
|
||
+++ b/packages/db_helper_sqlite/src/db/seed.sql
|
||
@@
|
||
-INSERT OR IGNORE INTO key_val_store (key, value) VALUES ('minRegularOrderValue', '300');
|
||
|
||
--- a/packages/db_helper_postgres/src/db/seed.ts
|
||
+++ b/packages/db_helper_postgres/src/db/seed.ts
|
||
@@
|
||
- { key: CONST_KEYS.minRegularOrderValue, value: minOrderValue },
|
||
|
||
--- a/apps/backend/tests/api/order-rules.test.ts
|
||
+++ b/apps/backend/tests/api/order-rules.test.ts
|
||
@@
|
||
- let minOrder = 0
|
||
+ let freeDeliveryThreshold = 0
|
||
- minOrder = asNumber(consts.minRegularOrderValue)
|
||
+ freeDeliveryThreshold = asNumber(consts.freeDeliveryThreshold)
|
||
- expect(minOrder).toBeGreaterThan(UNIT_PRICE)
|
||
+ expect(freeDeliveryThreshold).toBeGreaterThan(UNIT_PRICE)
|
||
- const quantity = Math.ceil(minOrder / UNIT_PRICE) + 1
|
||
+ const quantity = Math.ceil(freeDeliveryThreshold / UNIT_PRICE) + 1
|
||
(comments updated)
|
||
|
||
--- a/apps/backend/tests/api/coupon-math.test.ts
|
||
+++ b/apps/backend/tests/api/coupon-math.test.ts
|
||
@@
|
||
- let minOrderValue = 0
|
||
+ let freeDeliveryThreshold = 0
|
||
- minOrderValue = asNumber(consts.minRegularOrderValue)
|
||
+ freeDeliveryThreshold = asNumber(consts.freeDeliveryThreshold)
|
||
(assertions/comments updated)
|
||
|
||
Docs (no code): docs/e2e-sanity-failed-cases.md FC-06 (resolved by removal);
|
||
docs/e2e-sanity-test-results.md BL-02/D6; apps/user-ui/tests/KNOWN-GAPS.md.
|
||
No migrations run. No tests run.
|
||
|
||
[2026-10-10 11:52:42 +0530] FC-04 (SEC-06): enforce user-based coupon scope at redemption.
|
||
- validateAndGetCoupon now loads the coupon's applicableUsers and rejects when the
|
||
coupon isUserBased (and not isApplyForAll) and the ordering user is not listed.
|
||
- SKU (FC-09) and region (FC-10) scoping deliberately NOT enforced: SKU-specific
|
||
coupons are not created today and region-scoped coupons are not wanted; those are
|
||
false flags for now.
|
||
|
||
--- a/packages/db_helper_sqlite/src/user-apis/order.ts
|
||
+++ b/packages/db_helper_sqlite/src/user-apis/order.ts
|
||
@@
|
||
const coupon = await db.query.coupons.findFirst({
|
||
where: eq(coupons.id, couponId),
|
||
with: {
|
||
usages: { where: eq(couponUsage.userId, userId) },
|
||
+ applicableUsers: true,
|
||
},
|
||
})
|
||
if (!coupon) throw new Error('Invalid coupon')
|
||
+
|
||
+// User-based coupons are only spendable by their listed users (the display
|
||
+// endpoints already hide them from everyone else).
|
||
+if (coupon.isUserBased && !coupon.isApplyForAll) {
|
||
+ const applicableUsers = coupon.applicableUsers ?? []
|
||
+ if (!applicableUsers.some((au) => au.userId === userId)) {
|
||
+ throw new Error('This coupon is not applicable to your account')
|
||
+ }
|
||
+}
|
||
+
|
||
if (coupon.isInvalidated) throw new Error('Coupon is no longer valid')
|
||
|
||
--- a/apps/backend/tests/api/coupon-ux.test.ts
|
||
+++ b/apps/backend/tests/api/coupon-ux.test.ts
|
||
@@
|
||
apiClient(user.token).user.order.placeOrder.mutate({
|
||
selectedItems: [{ skuId, quantity, slotId }],
|
||
addressId: user.addressId,
|
||
+ regionId: 1,
|
||
paymentMethod: 'cod',
|
||
@@
|
||
-it('pins: user B can apply a coupon issued to user A', ... expect(total).toBe(295)
|
||
+it('rejects a user B applying a coupon issued to user A', ...
|
||
+ expect(error.message).toMatch(/not applicable/i)
|
||
(header comment updated)
|
||
|
||
Docs (no code): apps/backend/tests/BUGS.md #8 (fixed); docs/e2e-sanity-failed-cases.md
|
||
FC-04 (fixed) + FC-09/FC-10 (false flags); docs/e2e-sanity-test-results.md SEC-06/CP-04/
|
||
CP-05/CP-11 + the matching defect row.
|
||
No migrations run. No tests run.
|
||
|
||
[2026-10-10 12:03:04 +0530] FC-11/FC-12: stop store-delete orphaning; make tag delete work.
|
||
- deleteStore now refuses to delete a store that still has products (plain Error,
|
||
500) and no longer nulls product_info.store_id.
|
||
- deleteProductTag now deletes the product_tags junction rows first (transaction),
|
||
so the FK no longer blocks deleting a tag that has products.
|
||
- No schema/migration changes (no FK cascade added).
|
||
|
||
--- a/packages/db_helper_sqlite/src/admin-apis/store.ts
|
||
+++ b/packages/db_helper_sqlite/src/admin-apis/store.ts
|
||
@@
|
||
-import { eq, inArray, and } from 'drizzle-orm'
|
||
+import { eq, inArray, and, sql } from 'drizzle-orm'
|
||
@@
|
||
export async function deleteStore(regionId: number, id: number): Promise<{ message: string }> {
|
||
const existing = await db.query.storeInfo.findFirst({
|
||
where: and(eq(storeInfo.id, id), eq(storeInfo.regionId, regionId)),
|
||
columns: { id: true },
|
||
})
|
||
if (!existing) {
|
||
throw new Error('Store not found')
|
||
}
|
||
-
|
||
- return await db.transaction(async (tx) => {
|
||
- await tx.update(productInfo).set({ storeId: null }).where(eq(productInfo.storeId, id))
|
||
- const [deletedStore] = await tx.delete(storeInfo).where(eq(storeInfo.id, id)).returning()
|
||
- if (!deletedStore) throw new Error('Store not found')
|
||
- return { message: 'Store deleted successfully' }
|
||
- })
|
||
+
|
||
+ // A store cannot be deleted while products still reference it — that would
|
||
+ // orphan them. Reassign or remove the products first.
|
||
+ const [{ count }] = await db
|
||
+ .select({ count: sql<number>`count(*)` })
|
||
+ .from(productInfo)
|
||
+ .where(eq(productInfo.storeId, id))
|
||
+ if (Number(count) > 0) {
|
||
+ throw new Error('Cannot delete a store that still has products. Remove or reassign them first.')
|
||
+ }
|
||
+
|
||
+ await db.delete(storeInfo).where(eq(storeInfo.id, id))
|
||
+
|
||
+ return { message: 'Store deleted successfully' }
|
||
}
|
||
|
||
--- a/packages/db_helper_sqlite/src/admin-apis/product.ts
|
||
+++ b/packages/db_helper_sqlite/src/admin-apis/product.ts
|
||
@@
|
||
export async function deleteProductTag(regionId: number, tagId: number): Promise<boolean> {
|
||
- const [deleted] = await db.delete(productTagInfo)
|
||
- .where(and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId)))
|
||
- .returning({ id: productTagInfo.id })
|
||
- return !!deleted
|
||
+ return db.transaction(async (tx) => {
|
||
+ const tag = await tx.query.productTagInfo.findFirst({
|
||
+ where: and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId)),
|
||
+ columns: { id: true },
|
||
+ })
|
||
+ if (!tag) return false
|
||
+
|
||
+ // Drop the product associations first; the product_tags FK blocks the tag
|
||
+ // delete otherwise.
|
||
+ await tx.delete(productTags).where(eq(productTags.tagId, tagId))
|
||
+ await tx.delete(productTagInfo)
|
||
+ .where(and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId)))
|
||
+ return true
|
||
+ })
|
||
}
|
||
|
||
--- a/apps/backend/tests/api/admin-ops.test.ts
|
||
+++ b/apps/backend/tests/api/admin-ops.test.ts
|
||
@@ (after "deletes a store")
|
||
+ it('rejects deleting a store that still has products', async () => {
|
||
+ const target = await createStoreWithSku()
|
||
+ const error = await captureError(() =>
|
||
+ admin.admin.store.deleteStore.mutate({ storeId: target.storeId })
|
||
+ )
|
||
+ expect(error.message).toMatch(/still has products/i)
|
||
+ })
|
||
|
||
--- a/apps/backend/tests/api/admin-tags.test.ts
|
||
+++ b/apps/backend/tests/api/admin-tags.test.ts
|
||
@@
|
||
+import { createStoreWithSku } from '../helpers/fixtures'
|
||
@@ beforeAll
|
||
+ const store = await createStoreWithSku()
|
||
+ skuId = store.skuId
|
||
@@ (new test)
|
||
+ it('deleteProductTag removes a tag that has products', async () => {
|
||
+ const created = await admin.admin.product.createProductTag.mutate({
|
||
+ tagName: `API Tag w/ product ${uniqueSuffix()}`,
|
||
+ isDashboardTag: true,
|
||
+ productIds: [skuId],
|
||
+ })
|
||
+ const id = (created as { tag: { id: number } }).tag.id
|
||
+ const res = await admin.admin.product.deleteProductTag.mutate({ id })
|
||
+ expect((res as { message?: string }).message ?? '').toMatch(/deleted/i)
|
||
+ })
|
||
|
||
Docs (no code): docs/e2e-sanity-failed-cases.md FC-11/FC-12 + docs/e2e-sanity-test-results.md
|
||
PD-13/DS-02/D12/D13.
|
||
No migrations run. No tests run.
|
||
|
||
[2026-10-10 12:35:14 +0530] FC-14 (CT-07) closed as a false flag (docs only, no source).
|
||
- Reproduced on the simulator: cart held sku 155; toggleOutOfStock{id:155} bumped availability
|
||
av-17 -> av-18 (published av-18 shows isOutOfStock:true); relaunch + open cart showed the line
|
||
normally, then ~70 s later (the app's essentialConsts refetchInterval of 60 s) it correctly
|
||
rendered "Out of Stock". The cart already flags/filters/blocks OOS; the E2E observed the
|
||
pre-propagation window. Report's root cause was inaccurate.
|
||
- docs/e2e-sanity-failed-cases.md FC-14 + summary row + fix-order line;
|
||
docs/e2e-sanity-test-results.md CT-07 + D20. Stock restored; no source changed.
|
||
|
||
[2026-10-10 12:41:56 +0530] FC-15 (AU-07) + FC-16 (AU-08): fix profile update and password change.
|
||
FC-15:
|
||
- Context.req is the tRPC fetch adapter's Request (not HonoRequest); corrected the
|
||
type in trpc-index.ts and switched auth.ts to ctx.req.headers.get('authorization').
|
||
- Relaxed the optional email: the backend now treats an empty email as "no change"
|
||
(zod no longer forces .email() on ''), and the client form only requires email in
|
||
registration mode, not edit.
|
||
FC-16:
|
||
- upsertUserPassword now does an explicit select-then-update-or-insert (updates ALL
|
||
rows for the user, repairing existing duplicates) instead of relying on Postgres
|
||
error 23505.
|
||
- Added a unique index on user_creds.user_id in the schema (migration handled by the
|
||
user; existing duplicate rows must be deduped before the index can be created).
|
||
|
||
--- a/apps/backend/src/trpc/trpc-index.ts
|
||
+++ b/apps/backend/src/trpc/trpc-index.ts
|
||
@@
|
||
- req: HonoContext['req'];
|
||
+ req: Request;
|
||
|
||
--- a/apps/backend/src/trpc/apis/user-apis/apis/auth.ts
|
||
+++ b/apps/backend/src/trpc/apis/user-apis/apis/auth.ts
|
||
@@
|
||
- email: z.string().email('Invalid email format').optional(),
|
||
+ email: z.string().optional(),
|
||
@@
|
||
- if (email) { ... regex ... }
|
||
+ const cleanEmail = email?.trim() || undefined
|
||
+ if (cleanEmail) { ... regex ... }
|
||
@@
|
||
- email: email?.toLowerCase().trim(),
|
||
+ email: cleanEmail?.toLowerCase(),
|
||
@@
|
||
- const authHeader = ctx.req.header('authorization');
|
||
+ const authHeader = ctx.req.headers.get('authorization');
|
||
|
||
--- a/apps/user-ui/components/registration-form.tsx
|
||
+++ a/apps/user-ui/components/registration-form.tsx
|
||
@@
|
||
- // Validate email
|
||
- if (!data.email.trim()) { setError("email", { message: "Email is required" }); return; }
|
||
- if (!validateEmail(data.email)) { ... }
|
||
+ // Email is required on registration only; optional when editing.
|
||
+ if (!isEdit && !data.email.trim()) { setError("email", { message: "Email is required" }); return; }
|
||
+ if (data.email.trim() && !validateEmail(data.email)) { ... }
|
||
|
||
--- a/packages/db_helper_sqlite/src/user-apis/auth.ts
|
||
+++ b/packages/db_helper_sqlite/src/user-apis/auth.ts
|
||
@@
|
||
-export async function upsertUserPassword(userId, hashedPassword) {
|
||
- try { await db.insert(userCreds).values({ userId, userPassword: hashedPassword }); return }
|
||
- catch (error) { if (error.code === '23505') { await db.update(...).where(eq(userCreds.userId, userId)); return } throw error }
|
||
-}
|
||
+export async function upsertUserPassword(userId, hashedPassword) {
|
||
+ const existing = await db.select({ id: userCreds.id }).from(userCreds)
|
||
+ .where(eq(userCreds.userId, userId)).limit(1)
|
||
+ if (existing.length > 0) {
|
||
+ await db.update(userCreds).set({ userPassword: hashedPassword }).where(eq(userCreds.userId, userId))
|
||
+ } else {
|
||
+ await db.insert(userCreds).values({ userId, userPassword: hashedPassword })
|
||
+ }
|
||
+}
|
||
|
||
--- a/packages/db_helper_sqlite/src/db/schema.ts
|
||
+++ b/packages/db_helper_sqlite/src/db/schema.ts
|
||
@@ userCreds
|
||
-export const userCreds = sqliteTable('user_creds', { ... })
|
||
+export const userCreds = sqliteTable('user_creds', { ... }, (t) => ({
|
||
+ unq_user_creds_user: uniqueIndex('unique_user_creds_user').on(t.userId),
|
||
+}))
|
||
|
||
--- a/apps/backend/tests/api/misc-procedures.test.ts
|
||
+++ a/apps/backend/tests/api/misc-procedures.test.ts
|
||
@@
|
||
-it('pins: updateProfile crashes after writing the change', ... expect(error).toMatch(/ctx.req.header is not a function/)
|
||
+it('updates the profile and returns the new name', ... expect(res.success).toBe(true); getSelfData reflects it
|
||
-it('pins: updatePassword reports success but the old password still works', ...)
|
||
+it('updatePassword: new password works and the old one fails', ...)
|
||
|
||
Docs (no code): apps/backend/tests/BUGS.md #3/#4; docs/e2e-sanity-failed-cases.md
|
||
FC-15/FC-16; docs/e2e-sanity-test-results.md AU-07/AU-08 + D15/D16.
|
||
No migrations run. No tests run.
|
||
|
||
[2026-10-10 12:50:42 +0530] Added hand-written migration 0008_user_creds_unique.sql.
|
||
- Collapses existing duplicate user_creds rows (keep MAX(id) per user) and creates
|
||
the unique index on user_creds(user_id) matching the schema declaration.
|
||
Required because CREATE UNIQUE INDEX fails while duplicates exist (users 379, 908, 1311).
|
||
- Not run (user applies migrations). No journal/meta edit; SQL-only as requested.
|
||
|
||
--- a/packages/db_helper_sqlite/drizzle/0008_user_creds_unique.sql
|
||
+++ b/packages/db_helper_sqlite/drizzle/0008_user_creds_unique.sql
|
||
@@
|
||
+-- Migration: enforce one credentials row per user.
|
||
+-- ...
|
||
+DELETE FROM `user_creds`
|
||
+WHERE `id` NOT IN (SELECT MAX(`id`) FROM `user_creds` GROUP BY `user_id`);
|
||
+--> statement-breakpoint
|
||
+CREATE UNIQUE INDEX `unique_user_creds_user` ON `user_creds` (`user_id`);
|
||
|
||
[2026-10-10 12:53:21 +0530] Added migration 0009_remove_min_regular_order_value.sql.
|
||
- minRegularOrderValue was removed from the app earlier this session, leaving orphan
|
||
region_bound_consts rows (4) and a legacy key_val_store row. This migration deletes
|
||
them; it runs after 0006 (which seeds the bound rows), so fresh installs are cleaned too.
|
||
- Not run (user applies migrations). SQL-only.
|
||
|
||
--- a/packages/db_helper_sqlite/drizzle/0009_remove_min_regular_order_value.sql
|
||
+++ b/packages/db_helper_sqlite/drizzle/0009_remove_min_regular_order_value.sql
|
||
@@
|
||
+DELETE FROM `region_bound_consts` WHERE `key` = 'minRegularOrderValue';
|
||
+--> statement-breakpoint
|
||
+DELETE FROM `key_val_store` WHERE `key` = 'minRegularOrderValue';
|
||
|
||
[2026-10-10 12:54:31 +0530] Merged 0008 + 0009 into one migration file (applied as a single go).
|
||
- Removed 0008_user_creds_unique.sql and 0009_remove_min_regular_order_value.sql.
|
||
- Added 0008_user_creds_unique_and_min_order_cleanup.sql containing both the
|
||
user_creds dedupe + unique index and the minRegularOrderValue row cleanup.
|
||
- Not run (user applies migrations). SQL-only.
|
||
|
||
[2026-10-10 12:58:04 +0530] FC-17 (OR-12): client-side double-submit guard (server idempotency deferred).
|
||
- PaymentAndOrderComponent: handlePlaceOrder now early-returns while a submit is in
|
||
flight (a synchronous useRef guard + placeOrderMutation.isPending), and the Place
|
||
Order button is disabled while pending. Stops accidental double-taps; the server
|
||
still has no idempotency key, so API replays/network retries are not covered.
|
||
- Added a test asserting a second press while in flight does not re-call placeOrder.
|
||
|
||
--- a/apps/user-ui/components/PaymentAndOrderComponent.tsx
|
||
+++ a/apps/user-ui/components/PaymentAndOrderComponent.tsx
|
||
@@
|
||
-import React, { useState, useMemo } from 'react';
|
||
+import React, { useState, useMemo, useRef } from 'react';
|
||
@@
|
||
+ const submittingRef = useRef(false);
|
||
@@ onSettled
|
||
- setIsLoadingDialogOpen(false);
|
||
+ submittingRef.current = false;
|
||
+ setIsLoadingDialogOpen(false);
|
||
@@
|
||
const handlePlaceOrder = () => {
|
||
+ if (submittingRef.current || placeOrderMutation.isPending) return;
|
||
+ submittingRef.current = true;
|
||
if (!selectedAddress) { ... }
|
||
@@ button
|
||
- disabled={!selectedAddress}
|
||
+ disabled={!selectedAddress || placeOrderMutation.isPending}
|
||
(opacity also keyed on the same condition)
|
||
|
||
--- a/apps/user-ui/tests/components/payment-and-order.test.tsx
|
||
+++ a/apps/user-ui/tests/components/payment-and-order.test.tsx
|
||
@@
|
||
+ it('ignores a second press while the order is in flight', async () => { ... procCount === 1 })
|
||
|
||
Docs (no code): docs/e2e-sanity-failed-cases.md FC-17 + summary row;
|
||
docs/e2e-sanity-test-results.md OR-12 + its defect row; apps/backend/tests/BUGS.md #17.
|
||
No migrations run. No tests run.
|
||
|
||
[2026-10-10 13:03:57 +0530] FC-19 (RG-02): make createRegionWithBounds atomic on D1.
|
||
- Reproduced: superadmin.regions.create with two bounds at priority "1" returned the
|
||
unique-priority error but left region 5 with zero bounds (D1 does not roll back the
|
||
region insert with the failed bound insert).
|
||
- Fix: validate bounds before any insert (>=1 bound, unique priorities) and add a
|
||
compensating cleanup that removes the region + its child rows if a later insert
|
||
fails, so a failed create never leaves a half-created region.
|
||
|
||
--- a/packages/db_helper_sqlite/src/superadmin-apis/regions.ts
|
||
+++ a/packages/db_helper_sqlite/src/superadmin-apis/regions.ts
|
||
@@
|
||
export async function createRegionWithBounds(input) {
|
||
+ // Validate before touching the DB: D1 does not reliably roll back a
|
||
+ // multi-statement drizzle transaction, so a bad payload must never reach the
|
||
+ // inserts (it would leave a region with no bounds behind).
|
||
+ if (!input.bounds || input.bounds.length === 0)
|
||
+ throw new Error('A region must be created with at least one bound')
|
||
+ const priorities = input.bounds.map((b) => String(b.priority))
|
||
+ if (new Set(priorities).size !== priorities.length)
|
||
+ throw new Error('Each bound priority must be unique within the region')
|
||
+
|
||
return db.transaction(async (tx) => {
|
||
const [region] = await tx.insert(regions).values(...).returning()
|
||
+ try {
|
||
const inserted = await tx.insert(regionBounds).values(...).returning()
|
||
await tx.insert(regionConsts).values(defaultRegionRows(region.id)).onConflictDoNothing()
|
||
const boundRows = inserted.flatMap(...)
|
||
if (boundRows.length > 0) await tx.insert(regionBoundConsts).values(boundRows).onConflictDoNothing()
|
||
return { region: toSummary(region), bounds: inserted.map(toBoundDto) }
|
||
+ } catch (error) {
|
||
+ await tx.delete(regionBoundConsts).where(eq(regionBoundConsts.regionId, region.id))
|
||
+ await tx.delete(regionConsts).where(eq(regionConsts.regionId, region.id))
|
||
+ await tx.delete(regionBounds).where(eq(regionBounds.regionId, region.id))
|
||
+ await tx.delete(regions).where(eq(regions.id, region.id))
|
||
+ throw error
|
||
+ }
|
||
})
|
||
}
|
||
|
||
Docs (no code): docs/e2e-sanity-failed-cases.md FC-19 + summary row;
|
||
docs/e2e-sanity-test-results.md RG-02 + its defect row.
|
||
No migrations run. No tests run.
|
||
|
||
[2026-10-10 13:12:28 +0530] Moved + timestamped the E2E reports into docs/test reports/.
|
||
- docs/e2e-sanity-failed-cases.md -> docs/test reports/e2e-sanity-failed-cases-2026-10-10-1310.md
|
||
- docs/e2e-sanity-test-results.md -> docs/test reports/e2e-sanity-test-results-2026-10-10-1310.md
|
||
- Updated cross-references in both files and in docs/maestro-mcp-agent-guidelines.md.
|
||
(Historical change-log entries above keep the old paths.) No application source changed.
|
||
|
||
[2026-10-10 13:42:06 +0530] Move `is_offer` from product_skus -> product_market_stats (the
|
||
availability table). isOffer is dropped from products.json and now travels in
|
||
availability.json only; the apps read it from the availability merge. Combo-item
|
||
isOffer and the admin SKU payload stay (different payloads), still sourced from
|
||
product_market_stats. New hand-written migration 0009 (NOT run).
|
||
|
||
--- a/packages/db_helper_sqlite/src/db/schema.ts
|
||
+++ b/packages/db_helper_sqlite/src/db/schema.ts
|
||
@@ productSkus
|
||
- isOffer: integer('is_offer', { mode: 'boolean' }).notNull().default(false),
|
||
isComboOnly: ...
|
||
@@ productMarketStats
|
||
+ isOffer: integer('is_offer', { mode: 'boolean' }).notNull().default(false),
|
||
isSuspended: ...
|
||
|
||
--- a/packages/shared/types/user.ts
|
||
+++ b/packages/shared/types/user.ts
|
||
@@ ProductDetailCore
|
||
- isOffer?: boolean;
|
||
isComboOnly?: boolean;
|
||
@@ ProductPriceFlags
|
||
+ isOffer: boolean;
|
||
|
||
--- a/packages/db_helper_sqlite/src/stores/store-helpers.ts
|
||
+++ b/packages/db_helper_sqlite/src/stores/store-helpers.ts
|
||
@@ ProductBasicData
|
||
- isOffer: boolean
|
||
@@ getAllProductsForCache
|
||
- isOffer: sku.isOffer ?? false,
|
||
@@ getAllProductCombosForCache
|
||
- isOffer: ci.sku?.isOffer ?? false,
|
||
+ isOffer: ci.sku?.marketStats?.isOffer ?? false,
|
||
@@ getAvailabilityForCache
|
||
+ isOffer: stat.isOffer,
|
||
|
||
--- a/packages/db_helper_sqlite/src/user-apis/product.ts
|
||
+++ b/packages/db_helper_sqlite/src/user-apis/product.ts
|
||
- isOffer: ci.sku?.isOffer ?? false,
|
||
+ isOffer: ci.sku?.marketStats?.isOffer ?? false,
|
||
|
||
--- a/packages/db_helper_sqlite/src/admin-apis/product.ts
|
||
+++ b/packages/db_helper_sqlite/src/admin-apis/product.ts
|
||
@@ mapSku
|
||
- isOffer: sku.isOffer,
|
||
+ isOffer: marketStats?.isOffer ?? false,
|
||
@@ createProduct / updateProduct
|
||
- isOffer in the productSkus insert/update
|
||
+ isOffer moved into the productMarketStats insert/marketStatsValues
|
||
|
||
--- a/apps/backend/src/trpc/apis/common-apis/common.ts
|
||
+++ b/apps/backend/src/trpc/apis/common-apis/common.ts
|
||
- isOffer: product.isOffer, (products.json no longer carries it)
|
||
|
||
--- a/apps/backend/src/stores/product-store.ts
|
||
+++ b/apps/backend/src/stores/product-store.ts
|
||
- isOffer: boolean (interface) and - isOffer: product.isOffer, (mapping)
|
||
|
||
--- a/apps/user-ui/src/hooks/prominent-api-hooks.ts
|
||
+++ b/apps/user-ui/src/hooks/prominent-api-hooks.ts
|
||
--- a/apps/web-ui/src/hooks/prominent-api-hooks.ts
|
||
+++ b/apps/web-ui/src/hooks/prominent-api-hooks.ts
|
||
@@ merge
|
||
+ isOffer: availability?.isOffer ?? false,
|
||
|
||
New file: packages/db_helper_sqlite/drizzle/0009_move_is_offer_to_market_stats.sql
|
||
ALTER TABLE product_market_stats ADD COLUMN is_offer ...; backfill from product_skus;
|
||
ALTER TABLE product_skus DROP COLUMN is_offer.
|
||
No migrations run. No tests run.
|
||
|
||
Type fix: both apps' useAllProducts merged-data cast changed from
|
||
`ProductsResponse & { products: MergedProduct[] }` to
|
||
`Omit<ProductsResponse, 'products'> & { products: MergedProduct[] }` — with isOffer
|
||
gone from the base product, the array intersection otherwise resolved .products to
|
||
the base element type (user-ui order-again filter failed typecheck).
|
||
Verified: migration run on a COPY of the local D1 (SQLite 3.42) — column moved,
|
||
backfill of a synthetic offer sku + the orphan-offer safety net both correct.
|
||
tsc --noEmit: backend, admin-ui, user-ui PASS; web-ui has 12 pre-existing unrelated
|
||
errors (cacheVersion/freeDeliveryThreshold), none isOffer-related. No live probe
|
||
(dev DB not migrated).
|
||
|
||
[2026-10-10 14:09:38 +0530] Docs only (no code): added the global-stores-and-products
|
||
implementation plans under docs/impl-plans/ — README + phase-1 (per-region
|
||
product_market_stats), phase-2 (global stores/products backend), phase-3 (admin UI),
|
||
phase-4 (superadmin UI). No source changed. No migrations run. No tests run.
|
||
|
||
[2026-10-10 14:13:30 +0530] Docs only (no code): resolved the Phase-2 new-region seeding
|
||
decision — on region create, replicate the least-id region's global data (its
|
||
per-region product_market_stats rows for global SKUs) into the new region. Updated
|
||
docs/impl-plans/README.md, phase-2 §3, phase-4 §7. No source changed.
|
||
|
||
[2026-10-10 14:16:37 +0530] Docs only (no code): since migration 0006 (merged regionalization,
|
||
recreates store_info/product_info/product_market_stats/...) is not applied yet, revised the
|
||
plans to fold all schema changes into 0006's __new_* rebuilds instead of separate 0010/0011
|
||
recreate migrations. Updated docs/impl-plans/README.md (migration strategy), phase-1 §4/§8,
|
||
phase-2 §3/§10/§11. Noted 0009 (is_offer move) as a candidate to fold into 0006 too (open
|
||
question). No source changed. No migrations run.
|
||
|
||
[2026-10-10 14:22:19 +0530] Fold the 0009 (is_offer move) into the unapplied 0006 migration;
|
||
delete 0009_move_is_offer_to_market_stats.sql. Phase 1/2 schema folds (region_id /
|
||
is_suspended_in_region / is_global) intentionally NOT applied yet — they stay documented as
|
||
build-time edits to 0006 because region_id NOT NULL would break current market-stats writes.
|
||
|
||
--- a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
|
||
+++ b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
|
||
@@ __new_product_skus (is_offer removed)
|
||
- `is_offer` integer DEFAULT false NOT NULL,
|
||
- INSERT INTO `__new_product_skus` (...,`is_offer`,...) SELECT ...,`is_offer`,...
|
||
+ INSERT INTO `__new_product_skus` (...,...) SELECT ...,...
|
||
@@ __new_product_market_stats (is_offer added + backfilled from old product_skus)
|
||
+ `is_offer` integer DEFAULT false NOT NULL,
|
||
@@ copy
|
||
- INSERT ... SELECT id,sku_id,market_price,our_price,is_flash_available,flash_price,is_out_of_stock,is_suspended FROM product_market_stats;
|
||
+ INSERT ... (...,`is_offer`) SELECT ms.id,ms.sku_id,ms.market_price,ms.our_price,ms.is_flash_available,ms.flash_price,ms.is_out_of_stock,ms.is_suspended,COALESCE(ps.is_offer,false)
|
||
+ FROM product_market_stats ms JOIN product_skus ps ON ps.id = ms.sku_id; (JOIN also prunes the 3 orphan rows)
|
||
(index `product_market_stats_sku_id_unique` left unchanged)
|
||
|
||
Deleted: packages/db_helper_sqlite/drizzle/0009_move_is_offer_to_market_stats.sql
|
||
Docs: docs/impl-plans/README.md + phase-1 updated. No migrations run. No tests run.
|
||
|
||
[2026-10-10 14:25:07 +0530] Phase 1 — per-region product_market_stats (region-scoped market data).
|
||
Adds region_id (NOT NULL) + is_suspended_in_region to product_market_stats, moves the unique
|
||
key to (sku_id, region_id), folds the DDL into the pending 0006 rebuild, changes the
|
||
productSkus.marketStats relation one->many, and region-scopes every read/write.
|
||
|
||
--- a/packages/db_helper_sqlite/src/db/schema.ts
|
||
+++ b/packages/db_helper_sqlite/src/db/schema.ts
|
||
@@ productMarketStats
|
||
- skuId: integer('sku_id').notNull().references(() => productSkus.id).unique(),
|
||
+ skuId: integer('sku_id').notNull().references(() => productSkus.id),
|
||
+ regionId: integer('region_id').notNull().references(() => regions.id),
|
||
... isSuspended ...
|
||
+ isSuspendedInRegion: integer('is_suspended_in_region', { mode: 'boolean' }).notNull().default(false),
|
||
isOffer: ...
|
||
-})
|
||
+}, (t) => ({ unq_sku_region: uniqueIndex('product_market_stats_sku_region').on(t.skuId, t.regionId) }))
|
||
@@ relations
|
||
- marketStats: one(productMarketStats),
|
||
+ marketStats: many(productMarketStats),
|
||
@@ productMarketStatsRelations
|
||
+ region: one(regions, { fields: [productMarketStats.regionId], references: [regions.id] }),
|
||
|
||
--- a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
|
||
+++ a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
|
||
@@ __new_product_market_stats
|
||
+ `region_id` integer NOT NULL,
|
||
+ `is_suspended_in_region` integer DEFAULT false NOT NULL,
|
||
+ FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ...
|
||
@@ copy
|
||
+ region_id=(SELECT id FROM regions WHERE name='Mahabubnagar'), is_suspended_in_region=false
|
||
@@ index
|
||
- CREATE UNIQUE INDEX `product_market_stats_sku_id_unique` ON `product_market_stats` (`sku_id`);
|
||
+ CREATE UNIQUE INDEX `product_market_stats_sku_region` ON `product_market_stats` (`sku_id`,`region_id`);
|
||
|
||
New file: packages/db_helper_sqlite/src/lib/market-stats.ts (marketStatsForRegion helper)
|
||
|
||
Region-scoped reads/writes (pick the region row; check isSuspended + isSuspendedInRegion):
|
||
- stores/store-helpers.ts: getAllProductsForCache, getAvailabilityForCache (region filter),
|
||
getAllProductCombosForCache, suspended-sku set, getAllSlotsWithProductsForCache.
|
||
- user-apis/product.ts: getProductDetailById, combo items, getProductById, getAllProductsWithUnits
|
||
(+ regionId param), getSuspendedSkuIds (region filter), getAllSkusSummary.
|
||
- user-apis/order.ts: getProductById (derive region from product).
|
||
- user-apis/stores.ts: getStoreSummaries, getStoreDetail.
|
||
- user-apis/slots.ts: getProductAvailability (region filter).
|
||
- admin-apis/product.ts: mapSku callers, getAllProducts, getProductById, createProduct,
|
||
updateProduct, updateProductPrices, toggleProductOutOfStock, tags/groups mapSku callers.
|
||
- admin-apis/order.ts: latest-price lookups region-scoped.
|
||
- apps/backend/.../user-apis/apis/order.ts: unavailability check adds isSuspendedInRegion.
|
||
|
||
No migrations run. No tests run.
|
||
|
||
[2026-10-10 14:32:30 +0530] Revise Phase 1 suspension model: global `is_suspended` moves to
|
||
product_skus; product_market_stats keeps only the per-region `is_suspended_in_region`
|
||
(drop its `is_suspended`). Phase-1 admin write still targets the global flag (superadmin/
|
||
region split stays Phase 2).
|
||
|
||
--- a/packages/db_helper_sqlite/src/db/schema.ts
|
||
+++ a/packages/db_helper_sqlite/src/db/schema.ts
|
||
@@ productSkus
|
||
+ isSuspended: integer('is_suspended', { mode: 'boolean' }).notNull().default(false),
|
||
@@ productMarketStats
|
||
- isSuspended: integer('is_suspended', { mode: 'boolean' }).notNull().default(false),
|
||
isSuspendedInRegion: ... (kept)
|
||
|
||
--- a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
|
||
+++ a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
|
||
@@ __new_product_skus
|
||
+ `is_suspended` integer DEFAULT false NOT NULL,
|
||
+ copy: is_suspended = COALESCE((SELECT is_suspended FROM product_market_stats WHERE sku_id=product_skus.id), false)
|
||
@@ __new_product_market_stats
|
||
- `is_suspended` integer DEFAULT false NOT NULL, (and dropped from its copy)
|
||
|
||
--- a/packages/db_helper_sqlite/src/lib/market-stats.ts
|
||
+++ ...
|
||
- isMarketStatsSuspended(stats)
|
||
+ isSkuSuspended(globalSuspended, stats) // global (sku) OR per-region
|
||
|
||
Reads/writes updated so a SKU is suspended when product_skus.is_suspended (global) OR
|
||
product_market_stats.is_suspended_in_region (region):
|
||
- store-helpers.ts (products cache, availability cache, combos suspended-set, slots)
|
||
- user-apis/product.ts (detail, getAllProductsWithUnits, getSuspendedSkuIds, getAllSkusSummary)
|
||
- user-apis/stores.ts
|
||
- admin-apis/product.ts: mapSku reads sku.isSuspended; createProduct/updateProduct write the
|
||
global flag (productSkus) and drop it from market stats; combo-suspend check uses both.
|
||
- apps/backend/.../user-apis/apis/order.ts: product.isSuspended || marketStats.isSuspendedInRegion
|
||
|
||
No migrations run. No tests run.
|
||
|
||
[2026-10-10 14:37:08 +0530] Phase 2 (global stores/products, backend) + remove the store->admin
|
||
owner attachment.
|
||
|
||
OWNER REMOVAL:
|
||
- schema.ts: storeInfo drops `owner` (and storeInfoRelations.owner).
|
||
- 0006: `__new_store_info` drops `owner` (column, FK, copy).
|
||
- shared: Store.owner removed; CreateStoreInput/UpdateStoreInput.owner removed.
|
||
- db_helper_sqlite admin-apis/store.ts: drop assertOwnerInRegion + owner from reads/mapping.
|
||
- admin-apis/product.ts mapStore: drop owner. staff-user.ts deleteStaffUser: drop the
|
||
store-owner block.
|
||
- backend admin store.ts: drop owner from zod/create/update.
|
||
- admin-ui + admin-web StoreForm/screens + tests: drop the owner picker.
|
||
|
||
PHASE 2 (global stores/products):
|
||
- schema.ts: storeInfo gains `isGlobal` (region_id/owner nullable); productInfo.regionId
|
||
nullable (already in schema).
|
||
- 0006: `__new_store_info` region_id nullable + `is_global`; `__new_product_info` region_id
|
||
nullable.
|
||
- NEW packages/db_helper_sqlite/src/superadmin-apis/{global-stores,global-products}.ts
|
||
(CRUD + per-region market-stats seeding + isGlobalStore).
|
||
- NEW superadmin routers globalStores/globalProducts; registered in superadmin-trpc-index.
|
||
- regions.ts createRegionWithBounds: seed new region's global-SKU market rows from the
|
||
least-id region (compensating cleanup).
|
||
- Visibility/guards: admin product/store reads include global; assert*/resolve* accept
|
||
global; store-helpers/user stores include global; getAllSkusSummary includes global.
|
||
- Write scoping: admin updateProduct on a global product applies only market-stats fields.
|
||
- Region resolution: getOrderProductById + getProductDetailById accept a regionId.
|
||
- Cache regen: global structural writes regen all regions.
|
||
|
||
No migrations run. No tests run.
|
||
|
||
[2026-10-10 14:44:58 +0530] Phase 2 follow-ups (region resolution + edit paths).
|
||
- user-apis/order.ts getProductById(skuId, regionId?) + placeOrderUtil passes the order
|
||
region (both call sites) -> global SKUs price from the order region's row.
|
||
- user-apis/product.ts getProductDetailById(skuId, regionId?) and the public
|
||
user.product.getProductDetails input now accepts an optional regionId; region =
|
||
sku product region ?? client region.
|
||
- admin-apis/product.ts updateProduct(regionId | null, id, input): global product edited by
|
||
a regional admin -> updateProductMarketDataForRegion (market fields only, their region);
|
||
regionId null (superadmin structural edit) leaves each region's market data untouched and
|
||
seeds new SKUs to every region. createProduct|updateProduct return picks
|
||
regionId ?? targetRegionIds[0].
|
||
- superadmin-apis/global-products.ts updateGlobalProduct (structural) + globalProducts.update
|
||
router procedure; exported from the package index.
|
||
No migrations run. No tests run.
|
||
|
||
[2026-10-10 14:50:23 +0530] Phase 3 — admin UI for global products/stores (admin-ui + admin-web).
|
||
- shared: AdminProduct gains isGlobal; admin-apis/product.ts mapProduct sets it
|
||
(product.regionId == null).
|
||
- admin-ui: NEW src/components/GlobalProductForm.tsx (read-only structure + editable
|
||
market fields for the admin's region); products/edit.tsx branches to it when
|
||
product.isGlobal; products/index.tsx shows a GLOBAL badge; stores/edit.tsx renders a
|
||
read-only view for global stores.
|
||
- admin-web: NEW src/components/GlobalProductForm.tsx; dashboard.products.edit.tsx
|
||
branches to it; dashboard.products.tsx shows a GLOBAL badge; dashboard.stores.edit.tsx
|
||
renders a read-only view for global stores.
|
||
tsc --noEmit: admin-ui, admin-web, backend PASS. No migrations run. No tests run.
|
||
|
||
[2026-10-10 14:51:58 +0530] Phase 3 polish.
|
||
- Products list: added a "Global" filter chip (All / In Stock / Out of Stock / Global) in
|
||
admin-ui products/index.tsx and admin-web dashboard.products.tsx.
|
||
- Stores list: global store rows no longer show delete and are not navigable to edit
|
||
(admin-ui stores/index.tsx, admin-web dashboard.stores.tsx): the edit screen stays
|
||
read-only and delete is superadmin-only.
|
||
- user-ui ProductDetail passes the active regionId to user.product.getProductDetails so
|
||
global SKUs resolve price/availability for the user's region.
|
||
tsc --noEmit: backend, admin-ui, admin-web, user-ui PASS. No migrations run. No tests run.
|
||
|
||
[2026-10-10 14:54:10 +0530] Phase 4 — superadmin UI for global stores/products (apps/superadmin-ui).
|
||
- NEW src/routes/global-stores.tsx: list + create/edit/delete global stores
|
||
(superadmin.globalStores.*), GLOBAL badge, image URL field.
|
||
- NEW src/routes/global-products.tsx: list + create/delete global products
|
||
(superadmin.globalProducts.*) with a global-store select and per-SKU price/stock/
|
||
quantity-feature; deleting confirms; shows per-SKU region-row count.
|
||
- AppShell NAV + dashboard cards gain Global Stores / Global Products (Store, Package icons).
|
||
- routeTree.gen.ts updated with /global-stores + /global-products
|
||
(TanStack Router regenerated it cleanly; no duplicates).
|
||
tsc --noEmit: superadmin-ui PASS. No migrations run. No tests run.
|
||
|
||
[2026-10-10 14:55:15 +0530] Phase 4 — superadmin global-product EDIT UI (full parity).
|
||
- superadmin-apis/global-products.ts: list/get payload now includes sku comboItems.
|
||
- apps/superadmin-ui/src/routes/global-products.tsx: shared GlobalProductForm now
|
||
create + edit; edit prefills name/descriptions/store/type and every SKU (name, price,
|
||
marketPrice, features add/remove, out-of-stock, offer, combo-only, deleted, global
|
||
suspended) and calls superadmin.globalProducts.update; list has an Edit action + cancel.
|
||
tsc --noEmit: superadmin-ui, backend PASS. No migrations run. No tests run.
|
||
|
||
[2026-10-10 14:57:27 +0530] Superadmin UI — image upload for global products.
|
||
- backend: trpc-index.ts adds authenticatedProcedure (user | staff | superadmin);
|
||
common.generateUploadUrls now uses it so superadmins can request presigned URLs.
|
||
- superadmin global-products router (create/update) stores sku.images as-is (keys) instead
|
||
of running extractKeyFromPresignedUrl (the UI uploads and sends keys).
|
||
- apps/superadmin-ui: NEW src/hooks/useUploadToObjectStorage.ts (presigned PUT helper);
|
||
global-products.tsx adds per-SKU image picking (existing keys + new uploads with previews +
|
||
remove) and uploads on submit with contextString 'product_info'.
|
||
tsc --noEmit: superadmin-ui, backend PASS. No migrations run. No tests run.
|
||
|
||
[2026-10-10 15:01:22 +0530] Superadmin: list all products (all regions) + elevate a regional product
|
||
to global (attach to a global store).
|
||
|
||
- schema.ts: productInfoRelations gains `region` (one regions via productInfo.regionId).
|
||
- NEW packages/db_helper_sqlite/src/superadmin-apis/products.ts:
|
||
listAllProducts(regionId?) — global + regional products with store/region/skus.
|
||
elevateProductToGlobal(productId, globalStoreId) — set region_id NULL + store to the
|
||
global store, seed each other region's market-stats row from the source region
|
||
(copy price/stock/offer/flash, is_suspended_in_region=false), compensating revert.
|
||
- index.ts: export listAllProducts, elevateProductToGlobal.
|
||
- NEW apps/backend/.../superadmin-apis/apis/products.ts router (list, elevate) registered in
|
||
superadmin-trpc-index.ts; elevate regenerates ALL regions.
|
||
- apps/superadmin-ui/src/routes/global-products.tsx: "All Products" / "Global Products" tabs;
|
||
All tab lists every product (region + store + GLOBAL/REGIONAL badge) with an Elevate action
|
||
(pick global store + confirm).
|
||
No migrations run. No tests run.
|
||
|
||
[2026-10-10 16:16:11 +0530] Enable Maestro MCP server for pi in this project.
|
||
|
||
Planned diffs:
|
||
|
||
.pi/mcp.json (NEW)
|
||
+ {
|
||
+ "mcpServers": {
|
||
+ "maestro": {
|
||
+ "command": "maestro",
|
||
+ "args": ["mcp"],
|
||
+ "description": "Maestro mobile/web UI automation: list devices, drive and inspect
|
||
+ the screen, run YAML flows locally or on Maestro Cloud."
|
||
+ }
|
||
+ }
|
||
+ }
|
||
(pi equivalent of the opencode.jsonc "maestro" local MCP entry:
|
||
opencode `"type": "local", "command": ["maestro", "mcp"]`
|
||
-> pi stdio `command` + `args`. Project-scoped, so it needs project trust.)
|
||
|
||
No source files touched. No migrations run. No tests run.
|
||
|
||
[2026-10-10 18:17:00 +0530] Fix A1: `admin.product.deleteProduct` (500, FK violation) by making it a soft delete.
|
||
Root cause: D1 enforces FK constraints; `deleteProduct` issued a bare `DELETE FROM product_info`
|
||
while `product_skus.product_id` (NOT NULL, ON DELETE no action) and its child rows still referenced it.
|
||
Decision (user): soft delete; order history must keep showing the product name + billed amount.
|
||
|
||
Planned diff: packages/db_helper_sqlite/src/admin-apis/product.ts
|
||
|
||
- import: add `type SQL` to the drizzle-orm import.
|
||
- replace hard delete with:
|
||
+ async function softDeleteProduct(where: SQL): Promise<AdminProduct | null> {
|
||
+ const product = await db.query.productInfo.findFirst({ where, with: { skus: { columns: { id: true } } } })
|
||
+ if (!product) return null
|
||
+ const skuIds = product.skus.map((sku) => sku.id)
|
||
+ if (skuIds.length > 0) {
|
||
+ await db.batch([
|
||
+ db.delete(productMarketStats).where(inArray(productMarketStats.skuId, skuIds)),
|
||
+ db.delete(cartItems).where(inArray(cartItems.skuId, skuIds)),
|
||
+ db.delete(couponApplicableProducts).where(inArray(couponApplicableProducts.skuId, skuIds)),
|
||
+ db.delete(productTags).where(inArray(productTags.productId, skuIds)),
|
||
+ db.delete(productGroupMembership).where(inArray(productGroupMembership.productId, skuIds)),
|
||
+ db.delete(productCombos).where(inArray(productCombos.skuId, skuIds)),
|
||
+ db.delete(productCombos).where(inArray(productCombos.comboSkuId, skuIds)),
|
||
+ db.delete(specialDeals).where(inArray(specialDeals.skuId, skuIds)),
|
||
+ db.update(productSkus).set({ isDeleted: true }).where(inArray(productSkus.id, skuIds)),
|
||
+ ] as any)
|
||
+ }
|
||
+ return mapProduct(product)
|
||
+ }
|
||
+ export async function deleteProduct(regionId, id) { return softDeleteProduct(and(eq(productInfo.id, id), eq(productInfo.regionId, regionId))) }
|
||
+ export async function deleteGlobalProduct(id) { return softDeleteProduct(and(eq(productInfo.id, id), isNull(productInfo.regionId))) }
|
||
- (old bodies: single db.delete(productInfo)...returning() for both)
|
||
(kept: product_skus + sku_features rows -> order_items join still renders the name/unit;
|
||
kept product_info row -> parent FK; removed: market stats, carts, coupon applicability,
|
||
tags, group membership, combos, special deals)
|
||
- getAllProducts(regionId): hide fully-deleted products
|
||
- return products.map((product) => ({
|
||
+ return products.filter((product) => product.skus.some((sku) => !sku.isDeleted)).map((product) => ({
|
||
- checkProductExistsByName(name): ignore fully-deleted products so names can be reused
|
||
- db.query.productInfo.findFirst({ where: eq(productInfo.name, name), columns: { id: true } })
|
||
+ db.select({ id: productInfo.id }).from(productInfo)
|
||
+ .innerJoin(productSkus, eq(productSkus.productId, productInfo.id))
|
||
+ .where(and(eq(productInfo.name, name), eq(productSkus.isDeleted, false))).limit(1)
|
||
|
||
No other files: customer/store/slot/banner read paths already filter `productSkus.isDeleted`
|
||
(user-apis/product.ts, user-apis/stores.ts, stores/store-helpers.ts, admin-apis/slots.ts,
|
||
admin-apis/vendor-snippets.ts) and the order router already rejects deleted SKUs at checkout
|
||
(apps/backend/src/trpc/apis/user-apis/apis/order.ts SEC-05). No migration. No tests run.
|
||
|
||
[2026-10-10 18:26:00 +0530] Implemented the A1 soft-delete fix exactly as planned (packages/db_helper_sqlite/src/admin-apis/product.ts).
|
||
Verified against the running dev server (hot reloaded):
|
||
- `deleteProduct {152}` -> {"message":"Product deleted successfully"}; same for 151. (was HTTP 500)
|
||
- `getProductById {152}` -> skus 153/154 `isDeleted: true`, marketStats 0, features ["500 g","1 kg"] KEPT
|
||
(order history composes name/unit from these rows, so historical lines keep the product name).
|
||
- `admin.product.getProducts` -> 150 items, max id 150; fixtures 151/152 hidden.
|
||
- `user.product.getProductDetails {153}` -> "Product not found" (customer catalog hides tombstones).
|
||
- Name reuse: `createProduct` with the deleted product's name + bogus storeId -> "Invalid store ID: 999999"
|
||
(i.e. the name check passed; nothing was created).
|
||
- `deleteProduct {999999}` -> "Product not found" (404 preserved); re-deleting 152 still succeeds.
|
||
- No cache/store-init errors in the wrangler log after the deletes.
|
||
Still stranded by other known blockers (not part of this change): region-2 product 153 (no region-2 staff token),
|
||
stores 11/12 (store guard counts products), tag 10 (F4 image delete), region 2 (no delete API).
|
||
No migration. No tests run.
|
||
|
||
[2026-10-10 18:41:00 +0530] Fix A2/F2 (option A): order-detail coupon discount must be computed on the item subtotal, not on the paid total.
|
||
Root cause: the discount is not stored; both order-detail read paths recompute it as
|
||
`order.totalAmount * pct / 100`, but `orders.total_amount` holds the final payable
|
||
(items − discount + delivery). For order 2495 that reported 10% × 473.6 = 47.36 instead of the
|
||
10% × 304 = 30.4 that was charged. Fix: base = Σ(order_items.price × quantity) for this order,
|
||
cap prorated by `orders.order_group_proportion` (mathematically identical to what placeOrder charged),
|
||
reusing the existing (previously unused) applyDiscountToOrder() helper.
|
||
|
||
Planned diff: packages/db_helper_sqlite/src/user-apis/order.ts
|
||
+ export type CouponDiscountFields = Pick<CouponValidationResult, 'discountPercent' | 'flatDiscount' | 'maxValue'>
|
||
export function applyDiscountToOrder(
|
||
orderTotal: number,
|
||
- appliedCoupon: CouponValidationResult | null,
|
||
+ appliedCoupon: CouponDiscountFields | null,
|
||
proportion: number
|
||
)
|
||
|
||
Planned diff: packages/db_helper_sqlite/src/admin-apis/order.ts (getOrderByIdWithFullData, ~line 161-197)
|
||
- const orderTotal = parseFloat((orderData.totalAmount ?? '0').toString())
|
||
+ const itemsSubtotal = orderData.orderItems.reduce((sum, item) =>
|
||
+ sum + parseFloat(item.price?.toString() || '0') * parseFloat(item.quantity?.toString() || '0'), 0)
|
||
+ const proportion = Number(orderData.orderGroupProportion || 1)
|
||
for (const usage of couponUsageData) {
|
||
- let discountAmount = 0
|
||
- if (usage.coupon.discountPercent) { discountAmount = (orderTotal * pct) / 100 }
|
||
- else if (usage.coupon.flatDiscount) { discountAmount = parseFloat(usage.coupon.flatDiscount) }
|
||
- if (maxValue && discountAmount > maxValue) { discountAmount = maxValue }
|
||
- totalDiscountAmount += discountAmount
|
||
+ const { finalOrderTotal } = applyDiscountToOrder(itemsSubtotal, usage.coupon, proportion)
|
||
+ totalDiscountAmount += itemsSubtotal - finalOrderTotal
|
||
}
|
||
(import { applyDiscountToOrder } from '../user-apis/order')
|
||
|
||
Planned diff: apps/backend/src/trpc/apis/user-apis/apis/order.ts (getOrderById, ~line 547-577)
|
||
- const orderTotal = parseFloat(order.totalAmount.toString())
|
||
- ... manual per-coupon percent/flat/cap math on orderTotal ...
|
||
+ const itemsSubtotal = order.orderItems.reduce((sum, item) =>
|
||
+ sum + parseFloat(item.price.toString()) * parseFloat(item.quantity.toString()), 0)
|
||
+ const proportion = Number(order.orderGroupProportion || 1)
|
||
+ const { finalOrderTotal } = applyDiscountToUserOrder(itemsSubtotal, usage.coupon, proportion)
|
||
+ totalDiscountAmount += itemsSubtotal - finalOrderTotal
|
||
(add `applyDiscountToUserOrder` to the @/src/dbService import list)
|
||
|
||
Out of scope, reported only: admin-apis/order.ts rebalanceSlots (~line 684) recomputes each order's
|
||
`totalAmount` from latest prices minus discount but never adds the delivery charge, so a rebalance
|
||
overwrites the payable with a delivery-exclusive value (separate defect, same money area).
|
||
No migration. No tests run.
|
||
|
||
[2026-10-10 18:47:00 +0530] Implemented the A2/F2 fix as planned (option A) and verified live.
|
||
Files: packages/db_helper_sqlite/src/user-apis/order.ts (helper: CouponDiscountFields param +
|
||
discountAmount in the return so callers don't re-subtract and get 30.399999999999977),
|
||
packages/db_helper_sqlite/src/admin-apis/order.ts (getOrderByIdWithFullData coupon block),
|
||
apps/backend/src/trpc/apis/user-apis/apis/order.ts (getOrderById coupon block + import
|
||
applyDiscountToUserOrder from @/src/dbService).
|
||
Verified:
|
||
- admin.order.getOrderDetails {2495}: totalAmount 273.6, deliveryCharge 200, discountAmount 30.4
|
||
(was 47.36); items 304 - 30.4 + 200 = 473.6 ✓
|
||
- user.order.getOrderById {2495}: orderAmount/totalAmount 473.6, deliveryCharge 200,
|
||
discountAmount 30.4 (was 47.36) ✓
|
||
- no-coupon regression, admin.order.getOrderDetails {2496}: discountAmount null, couponCode null,
|
||
233 + 69 = 302 ✓
|
||
- proration equivalence checked numerically: read-path formula == write-path formula for a 10%/cap-50
|
||
coupon over splits (304@1), (304@0.5+0.5), (950@0.4+0.6) and for a flat-20/cap-50 coupon at p=1/0.5.
|
||
Still open (separate, reported): rebalanceSlots (~line 684 of the admin order helper) recomputes
|
||
orders.total_amount as latestItems − discount with no delivery charge, so a rebalance overwrites the
|
||
payable and would reintroduce a mismatch at read time. Needs its own decision/fix.
|
||
No migration. No tests run.
|
||
|
||
[2026-10-10 19:12:00 +0530] Fix `user.slots.getSlots` returning every region's slots (incl. past ones).
|
||
Problem: the procedure looped over all regions and returned the raw active-slot rows with no time
|
||
filter, so the checkout page received thousands of ids across regions, including full and long-past
|
||
slots (verified live: response contained [8..2032] while only 2032 is a future-active region-1 slot).
|
||
|
||
Planned diff: apps/backend/src/trpc/apis/user-apis/apis/slots.ts
|
||
getSlots: publicProcedure
|
||
+ .input(z.object({
|
||
+ // Caller's selected region. Omitted by admin tools -> staff region is used.
|
||
+ regionId: z.number().int().positive().optional(),
|
||
+ }).optional())
|
||
- .query(async (): Promise<UserSlotsListResponse> => {
|
||
- const regions = await getAllRegions()
|
||
- const perRegion = await Promise.all(regions.map((r) => getUserActiveSlotsListInDb(r.id)))
|
||
- return { slots: perRegion.flat(), count: perRegion.reduce((n, list) => n + list.length, 0) }
|
||
- })
|
||
+ .query(async ({ input, ctx }): Promise<UserSlotsListResponse> => {
|
||
+ const regionId = input?.regionId ?? ctx.staffUser?.regionId ?? null
|
||
+ if (regionId == null) return { slots: [], count: 0 }
|
||
+ const now = Date.now()
|
||
+ const slots = (await getUserActiveSlotsListInDb(regionId)).filter(
|
||
+ (slot) => new Date(slot.deliveryTime).getTime() > now && new Date(slot.freezeTime).getTime() > now,
|
||
+ )
|
||
+ return { slots, count: slots.length }
|
||
+ })
|
||
|
||
Planned diff: apps/user-ui/components/checkout-page.tsx
|
||
+ import { useRegion } from '@/src/hooks/useRegion';
|
||
...
|
||
+ const { regionId } = useRegion();
|
||
- const { data: slotsData, refetch: refetchSlots } = trpc.user.slots.getSlots.useQuery();
|
||
+ const { data: slotsData, refetch: refetchSlots } = trpc.user.slots.getSlots.useQuery(
|
||
+ { regionId: regionId ?? undefined },
|
||
+ { enabled: regionId != null }
|
||
+ );
|
||
(same region the order itself is placed with: PaymentAndOrderComponent sends
|
||
`regionId: selectedRegionId` from the same useRegion() hook)
|
||
No migration. No tests run.
|
||
|
||
[2026-10-10 19:20:00 +0530] Implemented the `user.slots.getSlots` scoping fix (backend + checkout caller).
|
||
During implementation the worker was briefly down: the new input schema used `z.object` without
|
||
importing zod in apps/backend/src/trpc/apis/user-apis/apis/slots.ts (Uncaught ReferenceError: z is not
|
||
defined) — fixed by adding `import { z } from 'zod'`. Server reloaded cleanly afterwards.
|
||
Verified live (temporarily set fixture slot 2033 to a future window with skuIds [148], then restored it
|
||
to deliveryTime 2026-10-11T13:30:00Z / freezeTime 2026-10-11T13:00:00Z / isActive false / skuIds null):
|
||
- active + future (freeze +30m, delivery +2h): regionId=1 -> count 1 [2033]; regionId=2 -> count 0;
|
||
staff token without input -> count 1 (falls back to the staff's own region);
|
||
no auth without input -> count 0 (previously: thousands of ids from every region)
|
||
- active but freeze time passed (freeze -1h): regionId=1 -> count 0
|
||
- inactive with a future window: regionId=1 -> count 0
|
||
- after restore: no future slots in any region -> count 0 for every variant (correct)
|
||
Response shape unchanged ({ slots: UserDeliverySlot[], count }) so the admin vendor-snippet forms keep
|
||
working (they now get their own region instead of every region).
|
||
NOT fixed by this change: the stale `slots.json` version pointer consumed by AddToCartDialog
|
||
(`essentialConsts.slots_version_num` stuck at 13 while newer files exist) and the hide-vs-show decision
|
||
for full slots. No migration. No tests run.
|
||
|
||
[2026-10-10 19:45:00 +0530] Fix A4/F4: tag images — normalise on write, make scaffoldAssetUrl idempotent, make image cleanup non-fatal.
|
||
Root cause recap (re-verified live): createProductTag/updateProductTag store the caller's imageUrl verbatim
|
||
(tag 10 holds a presigned URL); the tag read endpoints run scaffoldAssetUrl() which blindly prefixed
|
||
ASSETS_DOMAIN (-> https://assets2.freshyo.in/https://<r2>/...); deleteProductTag passed that same string to
|
||
deleteImageUtil as an object key, S3 rejected it, and the mutation 500s ("Failed to delete image") before
|
||
the row is deleted, so tag 10 is undeletable. Legacy tags 1 and 4 carry `tags/<file>%3FX-Amz-...` (encoded
|
||
presigned query baked into the value).
|
||
|
||
Planned diff: apps/backend/src/lib/s3-client.ts
|
||
+ export function normalizeAssetRef(input: string | null | undefined): string
|
||
+ // trims, drops a real query (`?`) or an encoded one (`%3F`), and for absolute URLs keeps the
|
||
+ // path minus host/bucket, so it works for presigned URLs, asset-domain URLs, legacy encoded
|
||
+ // values and plain keys alike.
|
||
scaffoldAssetUrl: - const normalizedKey = input.replace(/^\/+/, '')
|
||
+ const normalizedKey = normalizeAssetRef(input)
|
||
deleteImageUtil: iterate `keys.map(normalizeAssetRef).filter(Boolean)` instead of raw keys
|
||
(404 already tolerated; real failures still throw, callers decide)
|
||
|
||
Planned diff: apps/backend/src/trpc/apis/admin-apis/apis/product.ts
|
||
- import: add normalizeAssetRef to the '@/src/lib/s3-client' import
|
||
createProductTag: imageUrl: imageUrl ? normalizeAssetRef(imageUrl) : null (was: imageUrl ?? null)
|
||
updateProductTag: normalize before compare/write, and make the old-image cleanup non-fatal:
|
||
+ const normalizedImageUrl = imageUrl ? normalizeAssetRef(imageUrl) : imageUrl
|
||
+ ... if (normalizedImageUrl !== undefined && normalizedImageUrl !== currentTag.imageUrl) {
|
||
+ if (currentTag.imageUrl) { try { await deleteImageUtil({ keys: [currentTag.imageUrl] }) }
|
||
+ catch (err) { console.error('Failed to clean up previous tag image:', err) } }
|
||
+ }
|
||
- imageUrl: imageUrl ?? undefined -> imageUrl: normalizedImageUrl ?? undefined
|
||
deleteProductTag: wrap deleteImageUtil in try/catch (log + continue) so the tag row is always deleted.
|
||
|
||
Data repair (same session, recorded values):
|
||
- delete fixture tag 10 "E2E Deals 1715" (its stored value was the presigned URL above)
|
||
- clear imageUrl on tag 1 (was .../tags/1770321659633-1763869265110-e22b6d94-...jpeg%3FX-Amz-...) and
|
||
tag 4 (was .../tags/1770323410499-1763869436182-bf82f7b4-...jpeg%3FX-Amz-...): both objects return 404
|
||
at the clean key, so they need a re-upload; clearing stops the broken image. Tags 2/5/8/9 untouched.
|
||
No migration. No tests run.
|
||
|
||
[2026-10-10 20:00:00 +0530] A4/F4 implemented and verified live.
|
||
- tag 10 read: now `https://assets2.freshyo.in/tags/1791632636038.png` (was
|
||
`https://assets2.freshyo.in/https://<r2>/...?X-Amz-...`) — scaffolding is idempotent.
|
||
- `deleteProductTag {id:10}`: now "Tag deleted successfully" and the tag is gone (was 500
|
||
"Failed to delete image"); image cleanup 404 is tolerated and can no longer block the delete.
|
||
- write path: created tag 11 with a presigned imageUrl -> read back `https://assets2.freshyo.in/tags/999-test.png`
|
||
(key normalised on write); deleted tag 11 successfully.
|
||
- legacy repair: tags 1 "Chicken" and 4 "Fish" imageUrl cleared via updateProductTag (their objects return
|
||
404 at the clean key, so they need a re-upload; the previous image cleanup of the corrupted value no
|
||
longer throws). Tags 2/5/8 keep their images, tag 9 had none.
|
||
- regression: product images still scope correctly (`https://assets2.freshyo.in/product-images/1788767922579.png`);
|
||
update/delete of a tag still call scheduleStoreInitialization, so the customer tag cache regenerates
|
||
(subject to the A3 cache-version caveat we agreed to leave).
|
||
Data left: tag 10 removed (it was an E2E fixture), tags 1/4 need new images from the admin UI.
|
||
|
||
[2026-10-10 20:20:00 +0530] A5/F5 option 1: pre-validate upload URLs before the write, then claim best-effort.
|
||
Plan:
|
||
- packages/db_helper_sqlite/src/helper_methods/upload-url.ts: add
|
||
getPendingUploadUrlKeys(keys: string[]): Promise<string[]>
|
||
(single inArray query for the keys that exist with status 'pending').
|
||
- export it from packages/db_helper_sqlite/index.ts and apps/backend/src/sqliteImporter.ts.
|
||
- apps/backend/src/lib/s3-client.ts: add
|
||
findUnclaimableUploadUrls(urls): Promise<string[]> // unknown or already-claimed keys
|
||
assertUploadUrlsClaimable(urls): Promise<void> // throws ApiError 400 naming them
|
||
claimUploadUrls(urls): Promise<void> // Promise.allSettled, logs failures
|
||
replacing the fatal Promise.all(...claimUploadUrl) pattern.
|
||
- call sites: assert before the write, claimUploadUrls after:
|
||
admin createProduct:204 (allUploadUrls), updateProduct:298 (newImageUrls),
|
||
respondToReview:356, createProductTag:534, updateProductTag:600 (uploadUrls)
|
||
and user createReview:120 — there the existing contract is lenient (claim failures were already
|
||
swallowed), so it only logs the unclaimable keys before writing instead of throwing.
|
||
- upload_url_status is a write-only ledger (no readers, no cleanup job), so a claim failure never broke
|
||
an image; the fix targets the orphaned record + misleading 500.
|
||
No migration. No tests run.
|
||
|
||
[2026-10-10 20:35:00 +0530] A5/F5 option 1 implemented and verified live.
|
||
- repro (was: 500 "Failed to claim upload URL" + product created):
|
||
`createProduct` with a never-uploaded image -> 400
|
||
"These images were not uploaded through the app (unknown or already used):
|
||
product-images/999-nonexistent.png. Upload them again and retry."
|
||
product count 150 before and after; retrying the same name still reports the upload problem
|
||
(not "already exists"), so nothing was written.
|
||
- positive path: generated a real pending URL, created tag 12 with it -> success, imageUrl normalised
|
||
to https://assets2.freshyo.in/tags/1791639791557.png; reused the same URL for a second tag -> 400
|
||
"unknown or already used: tags/1791639791557.png" and no tag created; deleted tag 12 -> clean
|
||
(tag list back to the 9 legacy tags, no ZZ leftovers).
|
||
- replaced the fatal `Promise.all(...claimUploadUrl)` pattern at all six sites
|
||
(createProduct, updateProduct, respondToReview, createProductTag, updateProductTag, user createReview);
|
||
assertions run before destructive steps (updateProduct's deletedImageKeys cleanup and
|
||
updateProductTag's old-image cleanup now happen only after the new uploads validate).
|
||
- user createReview keeps its lenient contract: unclaimable upload URLs are logged, not rejected.
|
||
No migration. No tests run.
|
||
|
||
[2026-10-10 20:55:00 +0530] A6/F6 fix: reject out-of-scope constant keys instead of silently storing them, and allow null to delete a key.
|
||
Problem: each constant resolves from the table its scope names (CONST_SCOPE), but four endpoints
|
||
upsert into their own table without checking: superadmin.regions.updateBoundSettings /
|
||
updateRegionConstants and admin.region.updateBoundSettings / updateRegionConstants. Writing
|
||
`isFlashDeliveryEnabled` (region scope) through a bound endpoint returns {success:true,updatedCount:1},
|
||
stores a row nobody reads, and leaves the effective value unchanged (verified live; bound 1 still holds
|
||
a stray row from the E2E run). The region endpoints additionally dropped version keys silently.
|
||
Plan:
|
||
- apps/backend/src/lib/const-keys.ts: add assertConstantKeysInScope(keys, expected, endpoint) ->
|
||
ApiError 400 naming the correct endpoint per key (and rejecting version counters on region writes).
|
||
- packages/db_helper_sqlite/src/superadmin-apis/regions.ts: upsertBoundSettings/upsertRegionConstants now
|
||
delete the row when value === null and return { updated, deleted }.
|
||
- the four procedures call the guard first and return { success, updatedCount, deletedCount }.
|
||
Then clean up the stray bound row via value: null.
|
||
No migration. No tests run.
|
||
|
||
[2026-10-10 21:10:00 +0530] A6/F6 implemented and verified live.
|
||
Validation (all four endpoints) — wrong scope now returns 400 with the right endpoint named:
|
||
- superadmin.regions.updateBoundSettings + isFlashDeliveryEnabled -> "writes bound-scoped constants only:
|
||
isFlashDeliveryEnabled is a region constant — use updateRegionConstants" (was {success:true})
|
||
- ... + versionNum -> "... is a global constant — use the global constants endpoint"
|
||
- superadmin.regions.updateRegionConstants + deliveryCharge -> "... is a bound constant — use updateBoundSettings"
|
||
- admin.region.updateRegionConstants + products_version_num -> "... is a version counter owned by the
|
||
cache pipeline and cannot be set here" (was silently dropped)
|
||
- unknown key -> "... is not a known constant"
|
||
Legit writes still work on both the superadmin and staff endpoints:
|
||
bound + bound key -> {success:true,updatedCount:1,deletedCount:0}
|
||
region + region key -> {success:true,updatedCount:1,deletedCount:0}
|
||
Cleanup — stray row from the E2E run removed with value:null (allowed even for a wrong-scope key, so
|
||
mistakes can be deleted; scope is still enforced for writes):
|
||
admin.region.updateBoundSettings {boundId:1, settings:[{key:"isFlashDeliveryEnabled", value:null}]}
|
||
-> {success:true, updatedCount:0, deletedCount:1}; boundSettings no longer lists it; second call
|
||
-> deletedCount:0; essentialConsts unchanged (isFlashDeliveryEnabled false, deliveryCharge 20,
|
||
freeDeliveryThreshold 300, flashDeliveryCharge 69).
|
||
One bug found and fixed during verification: the delete branch used `.returning({ id })` but
|
||
region_consts/region_bound_consts have no id column (composite PK) -> "Cannot convert undefined or null
|
||
to object"; changed to `.returning({ key })`.
|
||
No migration. No tests run.
|
||
|
||
[2026-10-10 21:35:00 +0530] Add bound deletion (region deletion stays unsupported by design).
|
||
Context: A7 is not a defect (regions are not deletable), but bounds should be removable — and the RG-01
|
||
fixture bound 3 (region 2) is exactly what keeps a test region able to capture addresses.
|
||
Plan:
|
||
- packages/db_helper_sqlite/src/superadmin-apis/regions.ts: add deleteRegionBound(boundId) ->
|
||
{ found, deleted, regionId, addressCount, remainingBounds }. Refuses (deleted:false) when
|
||
addresses.boundId references it; otherwise removes its region_bound_consts rows and the bound row in one
|
||
transaction. (addresses.boundId is the only user-data FK to a bound, region_bound_consts.boundId the other.)
|
||
- apps/backend/src/lib/gen-store.ts: add deleteGenKvForBound(boundId) to drop the
|
||
essentialConsts_<boundId> KV blob of the removed bound.
|
||
- superadmin.regions.deleteBound {id}: 404 when missing, 409 naming the address count when in use,
|
||
else refreshGenKvForRegion + deleteGenKvForBound and return { success, deletedId, remainingBounds }.
|
||
- export deleteRegionBound via packages/db_helper_sqlite/index.ts and src/sqliteImporter.ts.
|
||
Verify with the region-2 fixture bound 3 (deletable) and the region-1 bound 2 (referenced by address 879 ->
|
||
409). No migration. No tests run.
|
||
|
||
[2026-10-10 21:55:00 +0530] Bound deletion, round 2: a region must always keep at least one bound.
|
||
Requirement (user): the UI must not let a bound be deleted when it is the region's only bound.
|
||
Plan:
|
||
- packages/db_helper_sqlite/src/superadmin-apis/regions.ts: deleteRegionBound now counts the region's
|
||
bounds first and refuses with `lastBound: true` when only one exists (no transaction run).
|
||
- superadmin.regions.deleteBound maps that to a 409: "Region <id>'s only bound cannot be deleted; a region
|
||
needs at least one bound so it can take orders."
|
||
- apps/superadmin-ui/src/lib/bound-rules.ts (NEW): MIN_BOUNDS_PER_REGION, canDeleteBound(boundCount) and
|
||
LAST_BOUND_HINT — the rule in one place so the UI and the test share it.
|
||
- apps/superadmin-ui/src/lib/bound-rules.test.ts (NEW): vitest cases — refuses the only bound (1), refuses
|
||
none (0), allows when another remains (2+). apps/superadmin-ui/package.json: add "test": "vitest run".
|
||
- apps/superadmin-ui/src/routes/regions.tsx: BoundSettingsEditor gains a "Delete bound" button, disabled
|
||
(with the hint as tooltip) when canDeleteBound(bounds.length) is false; on success it refetches the region
|
||
and surfaces server refusals (last bound / addresses in use) as an inline error.
|
||
No migration. No drizzle migrations run.
|
||
|
||
[2026-10-10 22:05:00 +0530] Add apps/superadmin-ui/vitest.config.ts (minimal) so `npm test` can run the bound-rule
|
||
test without loading the app's vite.config plugins (tanstack start / cloudflare / nitro are not needed for a
|
||
pure-logic test and are not resolvable from the hoisted node_modules here).
|
||
No other source files touched beyond the entries logged above.
|
||
|
||
[2026-10-10 22:15:00 +0530] Verified live:
|
||
- deleteBound {id:3} (region 2's only bound) -> 409 "Bound 3 is the only bound of region 2. A region needs
|
||
at least one bound so it can take orders."
|
||
- deleteBound {id:2} (region 1, referenced by address 879) -> 409 "Bound 2 is used by 1 address(es)."
|
||
- deleteBound {id:99999} -> 404.
|
||
- success path: created temp bound 4 in region 2 (priority 99) then deleted it ->
|
||
{"success":true,"deletedId":4,"remainingBounds":1}; region 2 is back to only bound 3 (temp row + its
|
||
bound consts gone); region 1 bounds 1/2 untouched; essentialConsts(bound 1) unchanged.
|
||
- UI test: `npx vitest run` in apps/superadmin-ui -> 1 file, 6 tests passed (ran by temporarily linking the
|
||
npx vitest cache into apps/superadmin-ui/node_modules because the app has no installed node_modules here —
|
||
link removed afterwards; with deps installed it is a plain `npm test`).
|
||
|
||
[2026-10-10 22:40:00 +0530] F9 fix 1: bound every catalogue/CDN request with an AbortController (90s) so a stalled
|
||
fetch can no longer pin the home pull-to-refresh spinner (or any query) forever.
|
||
Plan:
|
||
- apps/user-ui/src/lib/fetch-json.ts (NEW): JSON_FETCH_TIMEOUT_MS = 90_000, fetchJson<T>(url, timeoutMs?) that
|
||
runs axios.get(url, { signal }) under an AbortController armed for the timeout and cleared in `finally`,
|
||
plus isAbortError(error) for CanceledError/AbortError/ERR_CANCELED detection.
|
||
- apps/user-ui/src/hooks/prominent-api-hooks.ts: replace the five axios.get calls (products.json,
|
||
availability.json, stores.json, slots.json, store-with-products) with fetchJson; drop the axios import.
|
||
- apps/user-ui/utils/queryClient.ts: retry: (failureCount, error) => !isAbortError(error) && failureCount < 3
|
||
so a timed-out request surfaces instead of retrying 3 x 90s.
|
||
- apps/user-ui/src/trpc-client.ts: the custom fetch (used for every tRPC call, incl. the refetchConsts leg of
|
||
handleRefresh) gets the same 90s AbortController, forwarding any upstream signal.
|
||
No server changes. No migrations. No tests run.
|
||
|
||
[2026-10-10 22:50:00 +0530] F9 fix 1 implemented and verified.
|
||
Files: apps/user-ui/src/lib/fetch-json.ts (new), apps/user-ui/src/hooks/prominent-api-hooks.ts (5 call sites),
|
||
apps/user-ui/utils/queryClient.ts (retry skips aborts), apps/user-ui/src/trpc-client.ts (90s AbortController on
|
||
the shared fetch, forwarding the upstream signal).
|
||
Verification (the real helper bundled with esbuild, axios replaced by a faithful stub that turns an abort into
|
||
CanceledError/ERR_CANCELED; node http server with one instant route and one that never answers):
|
||
- JSON_FETCH_TIMEOUT_MS = 90000 (the requested cap)
|
||
- GET /fast -> resolves with the parsed JSON
|
||
- GET /stall with a 500 ms injected cap -> rejects after 504 ms, name CanceledError, isAbortError true
|
||
=> a hung request now fails at 90 s instead of hanging forever, so handleRefresh's `finally` runs and the
|
||
pull-to-refresh indicator clears
|
||
- isAbortError(new Error(...)) -> false (genuine failures are still retried 3x)
|
||
Not run here: the app's tsc/Metro build (apps/user-ui has no installed node_modules) and RN runtime behaviour.
|
||
AbortController is a platform global in RN 0.79 / Expo 53.
|
||
|
||
[2026-10-10 23:05:00 +0530] A11/F11 fix: per-variant out-of-stock, chosen from a BottomDialog in the admin app.
|
||
Plan:
|
||
- packages/db_helper_sqlite/src/admin-apis/product.ts: add
|
||
setProductSkusOutOfStock(regionId, productId, skuIds, isOutOfStock) ->
|
||
{ id, ignoredSkuIds, skus: [{id, name, isOutOfStock}], isOutOfStock } | null
|
||
(rejects skuIds that are not the product's; writes only those product_market_stats rows for the region;
|
||
leaves the existing all-variants toggleProductOutOfStock untouched).
|
||
- export it from packages/db_helper_sqlite/index.ts and apps/backend/src/sqliteImporter.ts.
|
||
- packages/shared/types/admin.ts: AdminToggleOutOfStockResult gains optional affectedSkuIds? and skus?.
|
||
- admin-apis/apis/product.ts toggleOutOfStock: input += skuIds? + isOutOfStock?; with skuIds it sets exactly
|
||
those variants (400 when a target state is missing or an id is not a variant), without skuIds it keeps the
|
||
current all-variants toggle. Availability cache is regenerated in both paths.
|
||
- NEW apps/admin-ui/src/components/VariantStockDialog.tsx: BottomDialog listing the variants with checkboxes
|
||
(select all / none) and two actions, "Mark out of stock" / "Mark in stock", calling the mutation with the
|
||
selected skuIds. Shows a partial-state note when variants disagree.
|
||
- apps/admin-ui/app/(drawer)/dashboard/products/index.tsx: the row's stock button now opens that dialog instead
|
||
of toggling blindly; the In/Out chip and the in-stock/out-of-stock filters/counters now use an aggregate over
|
||
all variants (In / Partial / Out) instead of only skus[0].
|
||
Verification: flip one variant of a real multi-SKU product out, assert the sibling stays in stock, then restore.
|
||
No migration. No drizzle migrations run.
|
||
|
||
[2026-10-10 23:20:00 +0530] A11/F11 implemented and verified (backend live; UI parse-checked only).
|
||
Verification (temp product 154 with SKUs 156/157, created for the test and soft-deleted afterwards):
|
||
- toggleOutOfStock {id, skuIds:[156], isOutOfStock:true} -> "Marked 1 variant(s) as out of stock (other
|
||
variants unchanged)", affectedSkuIds [156], aggregate isOutOfStock true, states (156:true, 157:false)
|
||
=> a single variant can be taken out while its sibling stays in stock (impossible before).
|
||
- toggleOutOfStock {id, skuIds:[157], isOutOfStock:false} -> both unchanged, targeting respected.
|
||
- toggleOutOfStock {id, skuIds:[999999], ...} -> 400 "These variants do not belong to product 154: 999999"
|
||
- toggleOutOfStock {id, skuIds:[156]} (no target) -> 400 "isOutOfStock is required when skuIds are given"
|
||
- toggleOutOfStock {id} (legacy) -> all variants out, pressing again -> all in (behaviour unchanged)
|
||
- admin.product.deleteProduct {154} -> "Product deleted successfully" (cleanup)
|
||
UI (apps/admin-ui): new VariantStockDialog (BottomDialog + Checkbox) opened from each row's Stock button; the
|
||
In/Out chip, the in-stock/out-of-stock filters and the counters now aggregate over all variants
|
||
(In / Partial / Out) instead of reading skus[0]. Both files parse with esbuild; the app itself was not built
|
||
or run here (apps/admin-ui has no installed node_modules in this environment).
|
||
|
||
[2026-10-10 21:05:00 +0530] Full-plan E2E run — FIX: business errors were flattened to HTTP 500 (ApiError -> tRPC).
|
||
Found while running section P/R (case P-01/P-02/P-03/P-04/T-04/R-01): every `throw new ApiError(msg, 4xx)` inside a
|
||
tRPC procedure reached clients as HTTP 500 / INTERNAL_SERVER_ERROR, because tRPC only understands TRPCError codes
|
||
and ApiError is a plain Error. Examples observed:
|
||
- createProduct with an unclaimed image -> 500 "These images were not uploaded through the app ..." (expected 400)
|
||
- updateProduct with an unclaimed new image -> 500 (expected 400)
|
||
- createProduct duplicate name (double-submit) -> 500 "A product with this name already exists" (expected 409/400)
|
||
- superadmin.regions.updateBoundSettings wrong-scope key -> 500 "…writes bound-scoped constants only" (expected 400)
|
||
- admin.store.getStoreById / slots.getSlotById / coupon.getById / order.getOrderDetails cross-region -> 500 (expected 404)
|
||
Change (one middleware, affects every procedure):
|
||
apps/backend/src/trpc/trpc-index.ts
|
||
+ import { ApiError } from '@/src/lib/api-error';
|
||
+ const API_ERROR_TRPC_CODES: Record<number, TRPCError['code']> = {
|
||
+ 400: 'BAD_REQUEST', 401: 'UNAUTHORIZED', 403: 'FORBIDDEN', 404: 'NOT_FOUND', 405: 'METHOD_NOT_SUPPORTED',
|
||
+ 409: 'CONFLICT', 412: 'PRECONDITION_FAILED', 413: 'PAYLOAD_TOO_LARGE', 422: 'UNPROCESSABLE_CONTENT',
|
||
+ 429: 'TOO_MANY_REQUESTS',
|
||
+ };
|
||
+ function toTRPCError(error: unknown): unknown {
|
||
+ if (!(error instanceof ApiError)) return error;
|
||
+ const status = error.statusCode ?? 500;
|
||
+ const code = API_ERROR_TRPC_CODES[status] ?? (status >= 500 ? 'INTERNAL_SERVER_ERROR' : 'BAD_REQUEST');
|
||
+ return new TRPCError({ code, message: error.message, cause: error });
|
||
+ }
|
||
} catch (error) {
|
||
... log ...
|
||
- throw error; // Re-throw to maintain error flow
|
||
+ throw toTRPCError(error); // keep 4xx a 4xx end-to-end
|
||
No migration. No drizzle migrations run.
|
||
|
||
[2026-10-10 21:12:00 +0530] Follow-up on the entry above: `error instanceof ApiError` never matched.
|
||
The backend bundle contains more than one copy of lib/api-error (packages carry their own node_modules),
|
||
so the thrown error's prototype differs from the imported class. Use structural detection instead:
|
||
- if (!(error instanceof ApiError)) return error;
|
||
+ function isApiErrorShape(error: unknown): error is { message: string; statusCode?: number } {
|
||
+ return !!error && typeof error === 'object' &&
|
||
+ ((error as any).name === 'ApiError' || typeof (error as any).statusCode === 'number')
|
||
+ }
|
||
+ if (!isApiErrorShape(error)) return error;
|
||
(and drop the now-unused ApiError import)
|
||
|
||
[2026-10-10 21:20:00 +0530] Note: the running `wrangler dev` watcher stopped re-bundling after ~20:31 IST
|
||
(reloadComplete events stop landing for new edits), so the ApiError->4xx fix above is in the source but could
|
||
not be verified against the live worker in this session. A dev-server restart applies it. Until then, live
|
||
requests still show business rejections as HTTP 500; every affected case below is marked PARTIAL/FAIL with that
|
||
note. No other code was changed for this entry.
|
||
|
||
[2026-10-10 23:27:44 +0530] Fix A22 — an expired reserved coupon could still be redeemed (and a secret could be claimed twice).
|
||
Policy (user decision): a reserved coupon's validTill is the single deadline for BOTH claiming the secret
|
||
and spending the issued coupon, so redemption must be rejected once it has passed.
|
||
|
||
1/3 apps/backend/src/trpc/apis/user-apis/apis/coupon.ts — guard the redeem route, handle a lost claim:
|
||
@@ redeemReservedCoupon
|
||
if (!reservedCoupon) {
|
||
throw new ApiError("Invalid or already redeemed coupon code", 400);
|
||
}
|
||
+
|
||
+ // A reserved coupon's validTill is the deadline for claiming the secret as well as for
|
||
+ // spending the coupon, so an expired code must not redeem: otherwise the code is burned
|
||
+ // and the customer is handed an already-expired coupon.
|
||
+ if (reservedCoupon.validTill && new Date(reservedCoupon.validTill) < new Date()) {
|
||
+ throw new ApiError("This coupon has expired", 400);
|
||
+ }
|
||
+
|
||
// Check if already redeemed by this user (in case of multiple attempts)
|
||
if (reservedCoupon.redeemedBy === userId) {
|
||
@@
|
||
const couponResult = await redeemUserReservedCouponInDb(userId, reservedCoupon)
|
||
+
|
||
+ if (!couponResult) {
|
||
+ // Lost the claim race: another request redeemed the same secret first.
|
||
+ throw new ApiError("Invalid or already redeemed coupon code", 400);
|
||
+ }
|
||
+
|
||
return { success: true, coupon: couponResult };
|
||
|
||
2/3 packages/db_helper_sqlite/src/user-apis/coupon.ts — claim the secret atomically before creating the coupon.
|
||
The return type becomes `UserCoupon | null` (null = the read-then-write race was lost):
|
||
-export async function redeemReservedCoupon(userId: number, reservedCoupon: ReservedCouponRow): Promise<UserCoupon> {
|
||
- const couponResult = await db.transaction(async (tx) => {
|
||
- const [coupon] = await tx.insert(coupons).values({ ...unchanged... }).returning()
|
||
-
|
||
- await tx.insert(couponApplicableUsers).values({
|
||
- couponId: coupon.id,
|
||
- userId,
|
||
- })
|
||
-
|
||
- await tx.update(reservedCoupons).set({
|
||
- isRedeemed: true,
|
||
- redeemedBy: userId,
|
||
- redeemedAt: new Date(),
|
||
- }).where(eq(reservedCoupons.id, reservedCoupon.id))
|
||
-
|
||
- return coupon
|
||
- })
|
||
-
|
||
- return mapCoupon(couponResult)
|
||
-}
|
||
+export async function redeemReservedCoupon(userId: number, reservedCoupon: ReservedCouponRow): Promise<UserCoupon | null> {
|
||
+ return db.transaction(async (tx) => {
|
||
+ // Claim first: this conditional update closes the gap between getReservedCouponByCode
|
||
+ // and the write, so two customers racing on one secret can never both get a coupon.
|
||
+ const claimed = await tx
|
||
+ .update(reservedCoupons)
|
||
+ .set({ isRedeemed: true, redeemedBy: userId, redeemedAt: new Date() })
|
||
+ .where(and(eq(reservedCoupons.id, reservedCoupon.id), eq(reservedCoupons.isRedeemed, false)))
|
||
+ .returning({ id: reservedCoupons.id })
|
||
+
|
||
+ if (claimed.length === 0) return null
|
||
+
|
||
+ const [coupon] = await tx.insert(coupons).values({ ...unchanged... }).returning()
|
||
+
|
||
+ await tx.insert(couponApplicableUsers).values({
|
||
+ couponId: coupon.id,
|
||
+ userId,
|
||
+ })
|
||
+
|
||
+ return mapCoupon(coupon)
|
||
+ })
|
||
+}
|
||
|
||
3/3 apps/backend/tests/api/coupon-ux.test.ts — the gap is no longer pinned; assert the fix instead:
|
||
- /**
|
||
- * KNOWN GAP: redemption does not check validTill (only the placeOrder
|
||
- * path does), so an already-expired reserved code still redeems.
|
||
- */
|
||
- it('pins: an expired reserved code still redeems', async () => {
|
||
+ it('rejects an expired reserved code', async () => {
|
||
const { secretCode } = await createReserved({
|
||
validTill: new Date(Date.now() - 3600_000).toISOString(),
|
||
})
|
||
- const res = await redeem(userA.token, secretCode)
|
||
- expect(res.success).toBe(true)
|
||
+ const error = await captureError(() => redeem(userA.token, secretCode))
|
||
+ expect(error.message).toMatch(/expired/i)
|
||
})
|
||
+
|
||
+ it('lets only one of two simultaneous claims win', async () => {
|
||
+ const { secretCode } = await createReserved()
|
||
+ const results = await Promise.allSettled([
|
||
+ redeem(userA.token, secretCode),
|
||
+ redeem(userB.token, secretCode),
|
||
+ ])
|
||
+ expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1)
|
||
+ })
|
||
|
||
Docs (.md only, no code): apps/backend/tests/BUGS.md #11 marked FIXED; #8 note updated to the product
|
||
policy that coupons are global (not region- or SKU-scoped).
|
||
Not changed: no admin-side create guard — a normal coupon can also be created with a past validTill and is
|
||
shown as "expired"; reserved coupons now behave identically.
|
||
No schema change, no migration, no drizzle migrations run.
|
||
|
||
[2026-10-10 23:41:54 +0530] Fix A24 — the delivery fee followed a client-supplied boundId, so an order could be undercharged.
|
||
Policy (user): prefer the delivery address's bound; only when the address has no bound, fall back to the
|
||
bound the client sends; then to the region's effective bound. This mirrors the customer app, which already
|
||
prices the selected address's bound (apps/user-ui/src/hooks/prominent-api-hooks.ts useGetEssentialConsts).
|
||
File: apps/backend/src/trpc/apis/user-apis/apis/order.ts (placeOrderUtil)
|
||
- // Bound-level constants (delivery charge/thresholds/min order) come from the
|
||
- // active bound the client is browsing in, falling back to the region's
|
||
- // effective bound. Region-level constants are shared across the region's bounds.
|
||
- const boundId = params.boundId ?? (await getEffectiveBoundId(params.regionId));
|
||
+ // Bound-level constants (delivery charge/thresholds/min order) come from the bound the
|
||
+ // delivery address belongs to, so pricing cannot be changed by a client-supplied id.
|
||
+ // Only when the address carries no bound do we fall back to the bound the client is
|
||
+ // browsing in, then to the region's effective bound. This mirrors the customer app, which
|
||
+ // already prices the selected address's bound (prominent-api-hooks useGetEssentialConsts).
|
||
+ // Region-level constants are shared across the region's bounds.
|
||
+ const boundId =
|
||
+ address.boundId ?? params.boundId ?? (await getEffectiveBoundId(params.regionId));
|
||
Effect: address 879 (bound 2 = Rs 200 fee / Rs 800 free-delivery threshold) + boundId 1 (Rs 20 / Rs 300)
|
||
now charges Rs 200 instead of Rs 20. An honest client is unaffected (it already sends the address's bound).
|
||
No schema change; the orders table still has no boundId column (auditability follow-up noted in the report).
|
||
No migration, no drizzle migrations run. No regression test added: the suite has no bound fixtures and no
|
||
superadmin session helper, so it cannot create a second bound to compare against; noted in tests/BUGS.md.
|
||
|
||
[2026-10-10 23:51:04 +0530] Fix A27 — rebalanceSlots wrote a total that excluded the delivery charge (and re-derived the coupon).
|
||
Policy (user): freeze the historic discount AND the delivery fee; rebalance only the product prices.
|
||
File: packages/db_helper_sqlite/src/admin-apis/order.ts (rebalanceSlots)
|
||
- with: { orderItems: {...}, couponUsages: { with: { coupon: true } } }
|
||
+ with: { orderItems: {...}, orderStatus: { columns: { isCancelled: true, isDelivered: true } } }
|
||
-
|
||
- const processedOrdersData = ordersList.map((order: any) => {
|
||
- let newTotal = order.orderItems.reduce((acc, item) => acc + latestPrice * qty, 0)
|
||
- order.orderItems.forEach((item) => { item.price = latest; item.discountedPrice = latest })
|
||
- const coupon = order.couponUsages[0]?.coupon
|
||
- let discount = 0
|
||
- if (coupon && !coupon.isInvalidated && (!coupon.validTill || coupon.validTill > now)) { ... }
|
||
- newTotal -= discount
|
||
- ... return { order: rest, updatedOrderItems, newTotal }
|
||
- })
|
||
+ const processedOrdersData = ordersList
|
||
+ .filter((order) => { const s = order.orderStatus?.[0]; return !s?.isCancelled && !s?.isDelivered })
|
||
+ .map((order) => {
|
||
+ const fee = Number(order.deliveryCharge || 0)
|
||
+ const oldItems = sum(item.price * item.quantity)
|
||
+ // Historic discount recovered from the stored row itself: items + fee - total.
|
||
+ // Immune to later coupon edits/invalidation and preserves a multi-slot sub-order's
|
||
+ // prorated share (that sub-order owns no coupon_usage row).
|
||
+ const frozenDiscount = Math.max(0, oldItems + fee - Number(order.totalAmount || 0))
|
||
+ const priceById = new Map<number, number>()
|
||
+ order.orderItems.forEach((item) => {
|
||
+ const latest = marketStatsForRegion(item.sku?.marketStats, regionId)?.ourPrice
|
||
+ // No price for this region -> keep the stored price (never drop to 0).
|
||
+ priceById.set(item.id, latest == null ? Number(item.price) : Number(latest))
|
||
+ })
|
||
+ const newItems = sum(priceById.get(item.id) * item.quantity)
|
||
+ const newTotal = Math.max(0, newItems - frozenDiscount + fee)
|
||
+ ...
|
||
+ return { order: rest, updatedOrderItems, newTotal, priceById }
|
||
+ })
|
||
-
|
||
- for (const { order, updatedOrderItems, newTotal } of processedOrdersData) {
|
||
+ for (const { order, updatedOrderItems, newTotal, priceById } of processedOrdersData) {
|
||
+ const price = priceById.get(item.id)
|
||
... .set({ price, discountedPrice: price })
|
||
Effect (verified live on an isolated slot): a no-op rebalance previously dropped the Rs 20 fee from the
|
||
payable (249 -> 249 where items+ fee = 269); now the fee and the charged discount are preserved and only the
|
||
item price is repriced. Delivered/cancelled orders are skipped. Coupon edits/invalidation no longer change a
|
||
historic order's total.
|
||
Unchanged / noted: money is still written unrounded (BUGS #7); db.transaction is the no-op stub, so the write
|
||
loop is still not atomic; orders rebalanced by the OLD code (e.g. 2541, 2554) now carry a phantom discount
|
||
equal to the dropped fee — a data-repair item, not auto-repaired here.
|
||
No schema change. No migration. No drizzle migrations run.
|
||
|
||
[2026-10-10 23:55:08 +0530] Fix A28 — updateProduct accepted never-uploaded (or another product's) image keys via skus[].images.
|
||
Root cause: createProduct validates every image (skus.flatMap(images) -> assertUploadUrlsClaimable -> claim),
|
||
but updateProduct validated only the declared newImageUrls, then wrote skus[].images straight through
|
||
(extractKeyFromPresignedUrl -> updateProductInDb) with no check and no claim. The edit form re-sends the
|
||
product's existing (already-claimed) images in skus[].images, which is why the whole set was not validated.
|
||
Policy (user): validate newImageUrls too, and treat an image the product already owns as owned (a removed
|
||
image re-added in the same submit is owned until the write).
|
||
1/4 packages/db_helper_sqlite/src/admin-apis/product.ts — new lightweight helper:
|
||
+export async function getProductImageKeys(regionId: number, productId: number): Promise<string[]> {
|
||
+ const product = await db.query.productInfo.findFirst({
|
||
+ where: and(eq(productInfo.id, productId), or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId))),
|
||
+ columns: { id: true },
|
||
+ with: { skus: { columns: { images: true } } },
|
||
+ })
|
||
+ return (product?.skus ?? []).flatMap((sku) => ((sku.images as string[] | null) ?? []).map(String))
|
||
+}
|
||
2/4 packages/db_helper_sqlite/index.ts + apps/backend/src/sqliteImporter.ts — export getProductImageKeys.
|
||
3/4 apps/backend/src/trpc/apis/admin-apis/apis/product.ts (updateProduct):
|
||
- // Before deleting any current image or writing the update: the new uploads must be real.
|
||
- await assertUploadUrlsClaimable(newImageUrls)
|
||
+ // The product's own images are re-sent on every edit, so only keys it does not already own are
|
||
+ // new references: those (plus the declared newImageUrls) must be real pending uploads.
|
||
+ const currentImageKeys = new Set(await getProductImageKeysInDb(ctx.staffUser!.regionId, id))
|
||
+ const incomingImageKeys = skus.flatMap((sku) => sku.images.map((url) => extractKeyFromPresignedUrl(url)))
|
||
+ const newlyReferenced = incomingImageKeys.filter((key) => !currentImageKeys.has(key))
|
||
+ const uploadsToValidate = [...new Set([
|
||
+ ...newImageUrls.map((url) => extractKeyFromPresignedUrl(url)),
|
||
+ ...newlyReferenced,
|
||
+ ])]
|
||
+ // Before deleting any current image or writing the update: the new uploads must be real.
|
||
+ await assertUploadUrlsClaimable(uploadsToValidate)
|
||
...
|
||
- if (newImageUrls.length > 0) { await claimUploadUrls(newImageUrls) }
|
||
+ if (uploadsToValidate.length > 0) { await claimUploadUrls(uploadsToValidate) }
|
||
4/4 imports: getProductImageKeys as getProductImageKeysInDb.
|
||
Verified live: fabricated key -> 400 with nothing written; another product's claimed key -> 400; the product's
|
||
own already-claimed image re-sent -> 200; a genuine pending upload -> 200 and claimed. createProduct guarded
|
||
as before. Probe product soft-deleted.
|
||
Not changed: banners/stores/global-stores convert URLs to keys unguarded, but the upload endpoint only issues
|
||
contexts review|product_info|notification|complaint|profile|tags, so those images are never registered in
|
||
upload_url_status and asserting there would reject legitimate images (out of scope).
|
||
No schema change. No migration. No drizzle migrations run.
|
||
|
||
[2026-10-10 23:57:48 +0530] Fix A29 — editing an address cleared its default flag (leaving the user with zero defaults).
|
||
Root cause: apps/backend/src/trpc/apis/user-apis/apis/address.ts (updateAddress) passed
|
||
isDefault: isDefault || false // "omitted" and "false" were treated identically
|
||
while the input schema declares isDefault optional, so a partial edit silently unset the default.
|
||
createAddress does not have the bug (it computes makeDefault = isDefault || no-other-addresses).
|
||
Fix:
|
||
- isDefault: isDefault || false,
|
||
+ // An omitted isDefault means "leave it as it is": only an explicit value may change it.
|
||
+ isDefault: isDefault ?? existingAddress.isDefault,
|
||
Behaviour: omitting isDefault keeps the current value; isDefault: true sets it and clears the other
|
||
addresses' defaults; isDefault: false still clears it explicitly (unchanged).
|
||
Verified live (U2 address 882): set default -> edit WITHOUT isDefault -> still default (previously it
|
||
became false and the user had zero defaults).
|
||
Not changed: the db helper still writes isDefault unconditionally (the route now always resolves a
|
||
boolean). The AddressForm/checkout selector already send the current value, so the UI was unaffected.
|
||
No schema change. No migration. No drizzle migrations run.
|
||
|
||
2026-10-10 23:59:14 Fix A30 — createAddress/updateAddress accepted any phone/pincode (only min(1) was enforced).
|
||
Rule (user): pincode = exactly 6 digits; phone = exactly 10 digits starting with 6, 7, 8 or 9.
|
||
1/3 apps/backend/src/trpc/apis/user-apis/apis/address.ts — shared patterns + both schemas:
|
||
+// Indian mobile numbers: exactly 10 digits starting 6-9. Pincode: exactly 6 digits.
|
||
+const PHONE_REGEX = /^[6-9]\d{9}$/
|
||
+const PINCODE_REGEX = /^\d{6}$/
|
||
- phone: z.string().min(1, 'Phone is required'),
|
||
- pincode: z.string().min(1, 'Pincode is required'),
|
||
+ phone: z.string().trim().min(1, 'Phone is required')
|
||
+ .regex(PHONE_REGEX, 'Phone must be a 10-digit number starting with 6, 7, 8 or 9'),
|
||
+ pincode: z.string().trim().min(1, 'Pincode is required')
|
||
+ .regex(PINCODE_REGEX, 'Pincode must be 6 digits'),
|
||
(applied to BOTH createAddress and updateAddress)
|
||
2/3 apps/user-ui/src/components/AddressForm.tsx — align the client rule with the server:
|
||
- phone: Yup.string().required('Phone is required').matches(/^\d{10}$/, 'Phone must be 10 digits'),
|
||
+ phone: Yup.string().required('Phone is required')
|
||
+ .matches(/^[6-9]\d{9}$/, 'Phone must be a 10-digit number starting with 6, 7, 8 or 9'),
|
||
(pincode already used /^\d{6}$/ — unchanged)
|
||
3/3 Cleanup of the probe fixtures that A30 created with invalid data (U2 886 phone "123", U2 887 pincode "12",
|
||
U3 892 phone "123", U3 893 pincode "12") — deleted.
|
||
Scope: only the user address router creates/updates addresses (admin.order.updateAddressCoords only writes
|
||
coordinates); the account mobile used by register/login is NOT validated by this change.
|
||
No schema change. No migration. No drizzle migrations run.
|
||
|
||
2026-10-11 00:01:20 Fix A31 / plan AD-08 — a user could end up with no address (and the protected-deletion errors
|
||
surfaced as HTTP 500). Rule (user): deleting the user's ONLY address must be refused and the reason shown to
|
||
the customer in a BottomDialog.
|
||
1/2 apps/backend/src/trpc/apis/user-apis/apis/address.ts (deleteAddress):
|
||
+ // A user must always keep at least one address: the app has nothing to deliver to otherwise.
|
||
+ const userAddresses = await getUserAddressesInDb(userId)
|
||
+ if (userAddresses.length <= 1) {
|
||
+ throw new ApiError('This is your only address. Add another address before deleting this one.', 409)
|
||
+ }
|
||
and the existing guards were converted so customers actually get a 4xx (they were plain Errors, which the
|
||
A19 mapping cannot translate):
|
||
- throw new Error('Address not found or does not belong to user')
|
||
+ throw new ApiError('Address not found or does not belong to user', 404)
|
||
- throw new Error('Address is attached to an ongoing order. Please cancel the order first.')
|
||
+ throw new ApiError('Address is attached to an ongoing order. Please cancel the order first.', 409)
|
||
- throw new Error('Cannot delete default address. Please set another address as default first.')
|
||
+ throw new ApiError('Cannot delete default address. Please set another address as default first.', 409)
|
||
+ import { ApiError } from '@/src/lib/api-error'
|
||
2/2 apps/user-ui/app/(drawer)/(tabs)/me/addresses/index.tsx — the refusal is shown in a BottomDialog
|
||
(the delete error used to be an Alert):
|
||
+ const [deleteError, setDeleteError] = useState<string | null>(null);
|
||
+ // check before the confirm step, so the customer is told why instead of "are you sure?" then an error
|
||
+ if (addresses.length <= 1) { setDeleteError('This is your only address. Add another address before deleting this one.'); return }
|
||
- onError: (error) => { Alert.alert('Error', error.message || 'Failed to delete address') }
|
||
+ onError: (error) => { setDeleteError(error.message || 'Failed to delete address') }
|
||
+ <BottomDialog open={deleteError !== null} onClose={() => setDeleteError(null)}> ... title/message/OK ...
|
||
Verified live (API): U3 has exactly one address -> delete refused; U2's default address -> refused (default
|
||
guard); a freshly created U2 address -> deleted successfully and gone from the list.
|
||
No schema change. No migration. No drizzle migrations run.
|
||
|
||
2026-10-11 00:16:33 Fix A37 — updateProductPrices took a SKU id under the name `productId`, and could silently reprice
|
||
the wrong product / report success without writing. No backward-compatibility alias kept (per user).
|
||
1/7 packages/db_helper_sqlite/src/admin-apis/product.ts (updateProductPrices):
|
||
updates: Array<{ productId: number; ... }> -> Array<{ skuId: number; ... }>
|
||
+ reject entries with no price field up front, so a "no-op" can never be reported as a success:
|
||
+ const emptyIds = updates.filter(u => u.price === undefined && u.marketPrice === undefined
|
||
+ && u.flashPrice === undefined && u.isFlashAvailable === undefined).map(u => u.skuId)
|
||
+ if (emptyIds.length > 0) return { updatedCount: 0, invalidIds: [], emptyIds }
|
||
+ return updatedCount = number of rows actually written (was: updates.length)
|
||
+ return shape: { updatedCount, invalidIds, emptyIds }
|
||
(validation + writes now key on `productSkus.id` / `productMarketStats.skuId` via `skuId`);
|
||
comments corrected from "SKU IDs" duplication, and the doc comment now says SKU explicitly.
|
||
2/7 apps/backend/src/trpc/apis/admin-apis/apis/product.ts:
|
||
updates: z.array(z.object({ productId: z.number(), ... })) -> { skuId: z.number().int().positive(), ... }
|
||
+ if (result.emptyIds.length > 0) throw new ApiError(`No price fields to update for SKU(s): ${result.emptyIds.join(', ')}`, 400)
|
||
"Invalid product IDs: ..." -> "Invalid SKU IDs: ..."
|
||
"Updated prices for N product(s)" -> "Updated prices for N SKU(s)"
|
||
3/7 apps/admin-ui/app/(drawer)/dashboard/prices-overview/index.tsx:
|
||
const update: any = { productId: sku?.id } -> const update: any = { skuId: sku?.id }
|
||
4/7 apps/admin-web/src/routes/dashboard.prices.tsx: same change.
|
||
5/7 apps/backend/tests/api/place-order-edge-cases.test.ts: two payloads productId -> skuId.
|
||
6/7 apps/backend/tests/api/cache-invalidation.test.ts: was passing `store.productId` — a product id, which only
|
||
worked when the product id happened to equal the SKU id; now passes `store.skuId`.
|
||
7/7 apps/admin-ui/tests/screens/prices-overview.test.tsx: expectations productId: 11 -> skuId: 11 (and the
|
||
"BUG:" comment removed).
|
||
Deliberately NOT done: resolving a product id to its SKUs — product ids and SKU ids overlap, and that ambiguity
|
||
is what produced the silent wrong-target write. The field is now unambiguously a SKU id.
|
||
No schema change. No migration. No drizzle migrations run.
|
||
|
||
2026-10-11 00:20:10 Fix A19 — business errors were flattened to HTTP 500: the error middleware could never see them.
|
||
Root cause (verified in the installed tRPC 11 source, ~/.bun/install/cache/@trpc/server@11.19.0/…/procedureBuilder.ts):
|
||
callRecursive does
|
||
try { … } catch (cause) { return { ok: false, error: getTRPCErrorFromUnknown(cause), marker } }
|
||
so a thrown resolver error NEVER propagates — the middleware receives it as a RESULT, not a throw.
|
||
getTRPCErrorFromUnknown (…/error/TRPCError.ts) wraps any non-TRPCError as
|
||
new TRPCError({ code: 'INTERNAL_SERVER_ERROR', cause }) // message inherited from the cause
|
||
which is exactly why the client saw HTTP 500 with the correct message. The previous fix wrapped
|
||
`next()` in try/catch and re-threw toTRPCError(error) in the catch — that catch is unreachable for
|
||
resolver errors, so the mapping never ran. (Not a duplicate-module problem: zod input errors already
|
||
returned 400, proving the transport was fine.)
|
||
File: apps/backend/src/trpc/trpc-index.ts
|
||
+/** tRPC hands resolver errors back as a result and wraps a non-TRPCError as INTERNAL_SERVER_ERROR,
|
||
+ * keeping the original in `cause`. Map our ApiError onto the matching TRPCError — and only that,
|
||
+ * so zod/BAD_REQUEST/UNAUTHORIZED and genuine 500s keep their code. */
|
||
+function translateResultError(error: unknown): unknown {
|
||
+ const original = (error as { cause?: unknown } | null)?.cause
|
||
+ return isApiErrorShape(original) ? toTRPCError(original) : error
|
||
+}
|
||
-const errorLoggerMiddleware = middleware(async ({ path, type, next, ctx }) => {
|
||
- const start = Date.now();
|
||
- try {
|
||
- const result = await next();
|
||
- const duration = Date.now() - start;
|
||
- if (process.env.NODE_ENV === 'development') { console.log(`✅ ${type} ${path} - ${duration}ms`); }
|
||
- return result;
|
||
- } catch (error) {
|
||
- …logging…
|
||
- throw toTRPCError(error);
|
||
- }
|
||
-});
|
||
+const errorLoggerMiddleware = middleware(async ({ path, type, next, ctx }) => {
|
||
+ const start = Date.now();
|
||
+ const result = await next();
|
||
+
|
||
+ // Resolver errors arrive as a result (tRPC catches them), so the only way to control the
|
||
+ // outgoing status is to re-throw the translated TRPCError from here.
|
||
+ if (!result.ok) {
|
||
+ logTrpcError({ path, type, start, ctx, error: result.error });
|
||
+ throw translateResultError(result.error);
|
||
+ }
|
||
+
|
||
+ if (process.env.NODE_ENV === 'development') { console.log(`✅ ${type} ${path} - ${Date.now() - start}ms`); }
|
||
+ return result;
|
||
+});
|
||
(the previous inline console.error block was extracted to `logTrpcError(...)`, unchanged in content)
|
||
Expected effect: ApiError(400/404/409) thrown in any resolver reaches clients as the real 4xx; the
|
||
`cause`-only mapping leaves zod 400s, UNAUTHORIZED 401s and genuine INTERNAL_SERVER_ERROR 500s alone.
|
||
No schema change. No migration. No drizzle migrations run.
|
||
|
||
2026-10-11 00:47:02 Fix A36 / SEC-04 — global products (regionId null) could be seen but never ordered or attached to a slot.
|
||
Rule (user): admins may add global products to slots; scheduled orders keep the slot-SKU verification; a SKU is
|
||
acceptable when its product's region is NULL (global) or equal to the target region.
|
||
1/4 apps/backend/src/trpc/apis/user-apis/apis/order.ts (placeOrderUtil, SEC-04):
|
||
- // SEC-04: the SKU must belong to the region being ordered into. A product
|
||
- // with no region is treated as not available anywhere.
|
||
- if ((product.product?.regionId ?? null) !== params.regionId) {
|
||
+ // SEC-04: the SKU must belong to the region being ordered into. A product with no region is
|
||
+ // GLOBAL: it is shared by every region (the catalogue reads use the same rule), so it is
|
||
+ // accepted anywhere; only another region's product is rejected.
|
||
+ const productRegionId = product.product?.regionId ?? null
|
||
+ if (productRegionId !== null && productRegionId !== params.regionId) {
|
||
throw new ApiError(`Product ${item.skuId} is not available in this region`, 409)
|
||
}
|
||
(the slot checks below are unchanged: slot region, active/freeze/delivery time, and that the slot
|
||
actually carries the ordered SKUs.)
|
||
2/4 packages/db_helper_sqlite/src/admin-apis/slots.ts (assertSkuIdsInRegion):
|
||
- const foreign = unique.filter((id) => regions.get(id) !== regionId)
|
||
+ // A global SKU (product regionId null) may be attached to any region's slot.
|
||
+ const foreign = unique.filter((id) => {
|
||
+ const skuRegionId = regions.get(id)
|
||
+ return skuRegionId != null && skuRegionId !== regionId
|
||
+ })
|
||
3/4 packages/db_helper_sqlite/src/admin-apis/banner.ts (assertSkuIdsInRegion, local copy): same predicate change
|
||
(r.product?.regionId ?? null) !== null && !== regionId.
|
||
4/4 packages/db_helper_sqlite/src/admin-apis/coupon.ts (assertApplicableSkusInRegion): same predicate change.
|
||
Not changed: packages/db_helper_sqlite/src/admin-apis/vendor-snippets.ts has the same copy but vendor snippets are
|
||
out of scope (deprecated) — left as-is and noted. admin-apis/product.ts already allowed global SKUs inside a
|
||
regional product, so products/tags/groups needed no change.
|
||
Effect: global SKUs can be attached to a slot/banner and ordered (scheduled delivery included); another region's
|
||
SKU is still rejected everywhere. No schema change. No migration. No drizzle migrations run.
|
||
|
||
2026-10-11 18:28:56 Test-harness fix (not app code): the API suites called user.slots.getSlots with no token and no
|
||
regionId, which the region-scoped implementation (the earlier A3 change) resolves to "no region" → empty list.
|
||
Every slot-dependent suite therefore failed in its fixture ("created slot ... was not returned").
|
||
The suites already assume region 1 everywhere (ensureUserAddress creates regionId 1, coupons/orders use region 1,
|
||
the staff in tests/.env is region 1), so the three call sites now pass the region explicitly.
|
||
1/3 apps/backend/tests/helpers/fixtures.ts (createFutureSlot):
|
||
- const listed = await apiClient().user.slots.getSlots.query()
|
||
+ // getSlots is region-scoped: ask for the region the slot was created in (the suites run against region 1).
|
||
+ const listed = await apiClient().user.slots.getSlots.query({ regionId: 1 })
|
||
2/3 apps/backend/tests/api/admin.test.ts (admin.slots.getAll includes the created slot):
|
||
- const publicSlots = await apiClient().user.slots.getSlots.query()
|
||
+ const publicSlots = await apiClient().user.slots.getSlots.query({ regionId: 1 })
|
||
3/3 apps/backend/tests/api/order-flow.test.ts ("lists the created slot via user.slots.getSlots"): same change.
|
||
No application code touched. No migration. No drizzle migrations run.
|