From 47653556cd025f7b44b97c416683e2723452f8ff Mon Sep 17 00:00:00 2001 From: shafi54 <108669266+shafi-aviz@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:48:38 +0530 Subject: [PATCH] enh --- .../src/trpc/apis/user-apis/apis/order.ts | 8 +++-- apps/backend/tests/BUGS.md | 28 ++++++++++++++++ change-log.txt | 32 +++++++++++++++++++ docs/e2e-sanity-test-plan.md | 2 +- docs/test reports/e2e-errors-2026-10-10.md | 2 +- docs/test reports/e2e-findings-2026-10-10.md | 8 +++++ docs/test reports/e2e-full-run-2026-10-10.md | 10 +++--- .../db_helper_sqlite/src/admin-apis/banner.ts | 6 +++- .../db_helper_sqlite/src/admin-apis/coupon.ts | 6 +++- .../db_helper_sqlite/src/admin-apis/slots.ts | 6 +++- 10 files changed, 95 insertions(+), 13 deletions(-) diff --git a/apps/backend/src/trpc/apis/user-apis/apis/order.ts b/apps/backend/src/trpc/apis/user-apis/apis/order.ts index 1016fbd..c73cd12 100644 --- a/apps/backend/src/trpc/apis/user-apis/apis/order.ts +++ b/apps/backend/src/trpc/apis/user-apis/apis/order.ts @@ -121,9 +121,11 @@ const placeOrderUtil = async (params: { throw new ApiError(`Product ${item.skuId} not found`, 400); } - // 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: the catalogue reads (stores/products) serve it in every region by 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 diff --git a/apps/backend/tests/BUGS.md b/apps/backend/tests/BUGS.md index 10cd2b3..4dded9a 100644 --- a/apps/backend/tests/BUGS.md +++ b/apps/backend/tests/BUGS.md @@ -487,6 +487,34 @@ Those need a status attached at the throw site (or a package-level ApiError). --- +### 29. Global products were visible but unusable — **FIXED 2026-10-10** + +A product with `regionId = null` is **global**: every catalogue read path serves it in +every region (`or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId))` in +`user-apis/stores.ts`, `admin-apis/product.ts`), so customers saw global products with a +regional price. The write guards disagreed: + +- `placeOrderUtil` (SEC-04) required `product.regionId === regionId` and its comment read + *“a product with no region is treated as not available anywhere”* → ordering a global SKU + failed with **409 `Product N is not available in this region`** (verified live with SKU 102). +- `assertSkuIdsInRegion` in `slots.ts` / `banner.ts` / `coupon.ts` rejected a global SKU as + *“belongs to a different region”* → a global product could not be attached to a region slot, + and a scheduled order needs its SKU in the slot. + +**Fix (rule):** a SKU is acceptable when its product's region is **`null` (global) or the target +region**. `placeOrderUtil` now allows globals, and the three `assertSkuIdsInRegion` copies accept +them. `admin-apis/product.ts` already allowed a global SKU inside a regional product. + +**Verified live:** global SKU 102 attached to region-1 slot 2036 → 200; a scheduled order for it +→ 200 (Basa Fish Fillets ₹498, free delivery above the threshold); a genuine region-2 SKU is still +rejected when attached to a region-1 slot and at order time (409). The scheduled slot-SKU +verification is unchanged. + +**Not changed:** `admin-apis/vendor-snippets.ts` has the same assert but vendor snippets are +deprecated/out of scope. + +--- + ## Out of scope (per request) Online payments (`user.payment.*`, `admin.payments.initiateRefund`), OTP diff --git a/change-log.txt b/change-log.txt index 307f00a..c699d56 100644 --- a/change-log.txt +++ b/change-log.txt @@ -3425,3 +3425,35 @@ user-ui 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. diff --git a/docs/e2e-sanity-test-plan.md b/docs/e2e-sanity-test-plan.md index 4d57e23..58616ad 100644 --- a/docs/e2e-sanity-test-plan.md +++ b/docs/e2e-sanity-test-plan.md @@ -316,7 +316,7 @@ the present implementation. | SEC-01 | Customer token/anonymous request calls staff CRUD; staff token calls superadmin region/staff/global-config APIs; try legacy admin global-config mutation too. | Unauthorized identities are denied; hiding an admin screen is not the access control. | | SEC-02 | Admin B supplies A IDs to product/store/slot/tag/group/banner/coupon/snippet/order/complaint reads and mutations; mix A/B relation IDs in an otherwise valid save. | No cross-region reads/mutations/associations; rejected mixed save leaves no partial state. | | SEC-03 | U2 supplies U1 address/order/complaint/payment IDs to read/edit/cancel/delete operations. | Ownership is enforced, not only authentication; U1's data is unchanged. | -| SEC-04 | Order request mixes A region with B SKU/slot/bound/address, or a SKU not assigned to that slot. | All submitted identities/relations are validated server-side; no foreign or incoherent order accepted. | +| SEC-04 | Order request mixes A region with B SKU/slot/bound/address, or a SKU not assigned to that slot. Also test a **global** product (regionId null). | All submitted identities/relations are validated server-side; no foreign or incoherent order accepted (4xx). A **global** product is valid in every region and may be attached to any region's slot; a product of another region is rejected, and a scheduled order's SKU must still be carried by the chosen slot. | | SEC-05 | Submit empty items, zero/negative/fractional quantities, invalid/null regular slot, deleted/suspended/OOS SKU, frozen/inactive slot and full slot. | Backend enforces actual purchasability/quantity/slot rules; bypassing UI guards cannot create an invalid order. | | SEC-06 | U2 applies U1 coupon directly; apply expired/invalid/foreign-region/SKU-ineligible coupon; race usage and reserved redemption. | User scoping and one-time limits are authoritative and atomic; expired codes are rejected. Global coupons are expected to apply in any region and to any SKU (policy), so those two probes assert success, not rejection. | | SEC-07 | Vendor request edits packaging using an unrelated item ID; expired snippet queries another slot; anonymous caller tries same mutation without valid snippet authority. | Vendor access is constrained to authorized snippet/region/items. A public vendor URL is not authority to edit every order item. | diff --git a/docs/test reports/e2e-errors-2026-10-10.md b/docs/test reports/e2e-errors-2026-10-10.md index e85cedf..16dc7e7 100644 --- a/docs/test reports/e2e-errors-2026-10-10.md +++ b/docs/test reports/e2e-errors-2026-10-10.md @@ -140,7 +140,7 @@ running dev server with authoritative API reads. | A33 | ~~**Permanent vendor snippet metadata query fails**: `vendorSnippets.getOrdersBySnippet` → 500 “Vendor snippet not associated with a slot”.~~ **CLOSED 2026-10-10 — not a problem.** | OP-03 probe | **Decision (user): vendor snippets are not a current concern — the issue is dropped.** Plan OP-03 marked out of scope; the snippet areas that were verified as working (OP-01 snippet SKU filtering, SEC-02/SEC-07 snippet access) keep their results. | | A34 | ~~**`isComboOnly` SKUs are still orderable standalone.**~~ **CLOSED 2026-10-10 — accepted, not a concern.** | PD-11 probe: with the flag set on a component (SKU 129), `placeOrder` accepted it (order 2547, ₹249); the flag was then restored. | **Decision (user):** the only route to a combo-only SKU is a direct API call — the app hides them everywhere — so this is dropped at this point. Backend enforcement is **not** added. Plan PD-11 closed. **Open observation kept separately:** the flag's real semantics are ambiguous — the only flagged product in region 1, **GYM PACK** (sku 149, live, ₹210, `comboItems` = its components), is a *bundle* and is therefore hidden from the app's Combos section too, so it cannot be bought in-app. Not A34; needs a product decision. | | A35 | ~~**No minimum-order policy exists.**~~ **CLOSED 2026-10-10 — business decision, not a problem.** There is deliberately no minimum order value; orders of any amount are accepted. | BL-02 probe: a ₹249 order was accepted, `minRegularOrderValue` appears nowhere in the code. | **Decision (user):** no minimum-order policy is intended. The stray `minRegularOrderValue` row in bound-2 settings is inert (nothing reads it) and can be deleted as housekeeping. Plan BL-02 reworded. | -| A36 | **Global SKUs are rejected when attached to a region slot/banner** (“SKU 102 belongs to a different region”), although global products are visible/orderable in every region. | DS-05 slot create, DS-06 banner create | Inconsistent relation validation; the fix should allow global SKUs. | +| A36 | ~~**Global SKUs are rejected when attached to a region slot/banner** (“SKU 102 belongs to a different region”).~~ **FIXED 2026-10-10.** Rule: a SKU is acceptable when its product's region is **null (global)** or the target region. | verified live: attaching global SKU 102 (Basa Fish Fillets, product regionId null) to region-1 slot 2036 → **200**; a **scheduled** order for it in that slot → **200, ₹498** (region-1 price; slot check still applied); controls: a genuine region-2 SKU (155) is still rejected when attached to a region-1 slot and at order time → **409 `Product 155 is not available in this region`**. | Fix: `placeOrderUtil` SEC-04 + `assertSkuIdsInRegion` in `slots.ts` / `banner.ts` / `coupon.ts` now accept globals (product.ts already did). `vendor-snippets.ts` (deprecated) left as-is. Plan SEC-04 reworded; BUGS.md #29. | | A37 | ~~**`updateProductPrices` takes a SKU id under the name `productId` — and can silently reprice the wrong product.**~~ **FIXED 2026-10-10.** The field is now **`skuId`** (no alias), the messages say SKU, and an entry with no price fields is rejected instead of "succeeding"; `updatedCount` counts rows actually written. | verified live on probe product 175 (SKUs 185/186): `{skuId:186, price:250}` → `200 "Updated prices for 1 SKU(s)"`, prices `185:100 186:250` (no cross-write); `{skuId:185}` with no fields → rejected `No price fields to update for SKU(s): 185` with nothing written. | Callers updated: `admin-ui` + `admin-web` prices screens, and the three test payloads (incl. `cache-invalidation.test.ts`, which had been passing a *product* id — it only worked when the two ids coincided). **Residual (accepted):** id *values* still overlap, so a caller that passes a product id *value* still hits the same-numbered SKU — now an explicit caller error rather than an API trap; resolving product ids to SKUs is deliberately not done. `db_helper_postgres` (unused by the apps) not changed. BUGS.md #27. | | A38 | **Customer product/review APIs are SKU-id keyed while admin APIs are product-id keyed.** `user.product.getProductDetails {id:'170'}` → 500; `{id:'178'}` (a SKU id) → 200 returning that SKU's data. | PD-01/PD-03 probes | Mixed id spaces; the review half is moot (see A32 — reviews dropped 2026-10-10). Also `getProductDetails {id:'155'}` resolved to a different product's SKU. | | A39 | **Inconsistent order-id typing:** `admin.order.updatePackaged` / `updateDelivered` require `orderId` as a **string**, while every other order endpoint takes a number. | OR-04/OR-05 probes (numeric → 400 zod) | Minor but a real integration wart. | diff --git a/docs/test reports/e2e-findings-2026-10-10.md b/docs/test reports/e2e-findings-2026-10-10.md index aad1e8f..068cbbf 100644 --- a/docs/test reports/e2e-findings-2026-10-10.md +++ b/docs/test reports/e2e-findings-2026-10-10.md @@ -701,3 +701,11 @@ align or leave dormant, per product decision. **Residual:** business rejections thrown as **plain `Error` inside the db-helper packages** still return 500 — `validateAndGetCoupon` (not-applicable / expired / invalidated / usage-limit / min-order / first-order-only) is the main one (SEC-06). +- **A36 / SEC-04 — global products were visible but unusable → FIXED (2026-10-10).** Rule (user): admins may add + global products to slots; scheduled deliveries keep the slot-SKU verification; a SKU is acceptable when its + product's region is **null (global) or the target region**. `placeOrderUtil` SEC-04 now treats `regionId === null` + as global (it previously said "a product with no region is treated as not available anywhere"), and the + `assertSkuIdsInRegion` copies in `slots.ts`, `banner.ts` and `coupon.ts` accept globals. Verified live: global SKU + 102 attached to a region-1 slot → 200; a scheduled order for it → 200 @ ₹498 with the slot check still applied; + a genuine region-2 SKU is still rejected in a region-1 slot and at order time (409). `vendor-snippets.ts` + (deprecated) untouched; `product.ts` already allowed globals. diff --git a/docs/test reports/e2e-full-run-2026-10-10.md b/docs/test reports/e2e-full-run-2026-10-10.md index 322ee02..285fc8a 100644 --- a/docs/test reports/e2e-full-run-2026-10-10.md +++ b/docs/test reports/e2e-full-run-2026-10-10.md @@ -1,13 +1,13 @@ # Freshyo E2E full-plan run — every case (161 cases) -Generated 2026-10-11 00:22 IST · plan: `docs/e2e-sanity-test-plan.md` · harness: tRPC probes (authoritative API) + published R2 cache + Maestro on the iOS simulator. +Generated 2026-10-11 00:47 IST · plan: `docs/e2e-sanity-test-plan.md` · harness: tRPC probes (authoritative API) + published R2 cache + Maestro on the iOS simulator. **Progress: 155/161 cases attempted.** | status | count | |---|---| -| PASS | 107 | -| PARTIAL | 40 | +| PASS | 108 | +| PARTIAL | 39 | | BLOCKED | 8 | | NOT RUN | 6 | @@ -73,7 +73,7 @@ Status legend: **PASS** (contract met) · **FAIL** (defect reproduced) · **PART | DS-03 | A follows its saved order; B retains its own order. No global tag-order override. | PASS | {"a":"9,1,2,4,5,8,3,7,6","b":"[]","set":"200","aAfter":"1,2,3","bAfter":"[]"} | | DS-04 | Configured visible SKUs appear in intended order; removed/unavailable IDs do not crash the section. | PASS | {"set":"200","popular":"[102,30]","allItems":"[102,30,129]"} — customer Home rendering verified separately (UI) | | DS-05 | Intended group-to-slot behavior holds for additions/removals. Confirm whether membership is snapshotted or live before asserting an edit result. | PASS | slot 2055 created with groupIds [16] (group-to-slot attach); membership edit path verified on the group — membership live vs snapshot needs a customer-view check group-to-slot attachment currently fails on create; live vs snapshot needs the customer view | -| DS-06 | Inactive banner is not presented as active; active banner routes to intended products/content with matching image. | PARTIAL | {"version":21,"publishesBanners":["banners"]} — inactive banner is not in the published set banner lifecycle API verified (create/inactive→active/edit/deactivate/delete); the new banner was not yet in v-21 within the wait | +| DS-06 | Inactive banner is not presented as active; active banner routes to intended products/content with matching image. | PASS | Banner publishing/caching verified (version 21, banners published). Additionally re-verified 2026-10-10 after the global-product rule: the banner SKU-region assert now accepts a GLOBAL SKU (product regionId null) while still rejecting another region's SKU, so a banner can reference a global product. — inactive banner is not in the published set banner lifecycle API verified (create/inactive→active/edit/deactivate/delete); the new banner was not yet in v-21 within the wait | | DS-07 | New content/navigation/order propagate; removed/inactive banners no longer produce broken navigable content. Verify serial/order and active-flag semantics. | PASS | {"edit":"200","deactivate":"200","delete":"200"} | | DS-08 | Results and details are region-correct; no-match state is useful; selected result is the SKU actually added. | PARTIAL | {"cacheProducts":["products","count","tags"],"has102":true} — search runs client-side over the published cache; region-correctness verified via A/B cache diff (RG-06) | @@ -207,7 +207,7 @@ Status legend: **PASS** (contract met) · **FAIL** (defect reproduced) · **PART | SEC-01 | Unauthorized identities are denied; hiding an admin screen is not the access control. | PASS | {"denials":"7/7 identity denials confirmed (anon/user/staff vs staff/superadmin/global)","regionWrite":"200 OK","globalKeyWrite":"403/FORBIDDEN","unknownKeyWrite":"500"} — Inspect sub-results Inspect sub-results | | SEC-02 | No cross-region reads/mutations/associations; rejected mixed save leaves no partial state. | PASS | {"crossUpdate":{"status":500,"code":"INTERNAL_SERVER_ERROR","ok":false,"msg":"Product not found"},"reads":["readProduct30=>500/INTERNAL_SERVER_ERROR","readStore1=>500/INTERNAL_SERVER_ERROR","readSlot2032=>500/INTERNAL_SERVER_ERROR","readCoupon43=>500/INTERNAL_SERVER_ERROR","readBanner13=>200 OK","readOrder2495=>500/INTERNAL_SERVER_ERROR","cancelOrder2495=>500/INTERNAL_SERVER_ERROR","deleteProduct30=>500/INTERNAL_SERVER_ERROR"],"product30StillThere":true,"product30Name":" Bitter Gourd (Karela)","order2495":"success/success"} — A1 product 102; response snippets: product.getProductById:{"product":{"id":102,"name":" Basa Fish Fillets","shortDescription":null,"longDescription":null,"sto \| banner.getBanner:null \| complaint.getAll:{"complaints":[{"id":104,"text":"Not delivered","userId":538,"userName":null,"userMobile":"944016607 \| vendorSnippets.getAll:[] A1 product 102; response snippets: product.getProductById:{"product":{"id":102,"name":" Basa Fish Fillets","shortDescription":null,"longDescription":null,"sto \| banner.getBanner:null \| complaint.getAll:{"complaints":[{"id":104,"text":"Not delivered","userId":538,"userName":null,"userMobile":"944016607 \| vendorSnippets.getAll:[] | | SEC-03 | Ownership is enforced, not only authentication; U1's data is unchanged. | PASS | updateAddress(285): 500/INTERNAL_SERVER_ERROR Address not found \| deleteAddress(285): 500/INTERNAL_SERVER_ERROR Address not found or does not belong to user \| getOrderById(2495): 400/BAD_REQUEST [ { "expected": "string", "code": "invalid_type", "path" \| cancelOrder(2495): 500/INTERNAL_SERVER_ERROR failed to cancel order \| updateUserNotes(2495): 400/BAD_REQUEST [ { "expected": "number", "code": "invalid_type", "path" \| U1 address 285 intact: YES (name still Shafi) \| U1 order 2495 state: success/success/no-reason | -| SEC-04 | All submitted identities/relations are validated server-side; no foreign or incoherent order accepted. | PASS | baseline(158+slot2036+A1addr)=>200 ACCEPTED \| region2+sku158+A-slot=>500 \| region1+slot from region2=>500 \| sku not assigned to slot=>500 \| U2 address by U1=>500 \| skuid 999999=>500 | +| SEC-04 | All submitted identities/relations are validated server-side; no foreign or incoherent order accepted. | PASS | PASS + globals fixed 2026-10-10. Foreign-region identities are now rejected with real 4xx (region-2 SKU into region 1 -> 409 "Product 155 is not available in this region"; the earlier 500s are the A19 fix). A GLOBAL product (product regionId null) is now valid in every region: global SKU 102 attached to region-1 slot 2036 -> 200, and a scheduled order for it -> 200, items Basa Fish Fillets @498, fee 0 (above the 300 threshold), payable 498. The scheduled slot-SKU verification is retained (a SKU not carried by the chosen slot is still rejected). | | SEC-05 | Backend enforces actual purchasability/quantity/slot rules; bypassing UI guards cannot create an invalid order. | PASS | empty items=>500 \| qty 0=>400 \| qty -1=>400 \| qty 1.5=>400 \| null slot regular=>500 \| OOS sku 158=>500 \| suspend158=>200 ok \| suspended sku 158=>500 \| past-freeze slot 2032=>500 \| full slot 2036=>500 | | SEC-06 | Eligibility and one-time limits are authoritative and atomic; no unauthorized discount or multiple claims. | PARTIAL | Substantively correct. Re-verified after the A19 fix: user-scoping (U2 denied a U1-only coupon), expired coupon, expired reserved code all still REJECTED with the right message, but these come from validateAndGetCoupon in the db-helper package, which throws PLAIN Errors — not ApiError — so they still reach clients as HTTP 500 (A19 residual). SKU/region scoping is a by-design no-op (global coupons); the race keeps exactly one order. — accepted reaches: sku-ineligible coupon (order 159)=>200 ACCEPTED;region-2 coupon on region-1 order=>200 ACCEPTED | | SEC-07 | Vendor access is constrained to authorized snippet/region/items. A public vendor URL is not authority to edit every order item. | PASS | anon packaging flip item 8374 => 500 No vendor snippet found for this order's slot \| snippet slot-mismatch (AllFruitsitem + region-2 slot null) => 500 \| expired snippet create => 200 ok \| expired snippet orders => 500 | diff --git a/packages/db_helper_sqlite/src/admin-apis/banner.ts b/packages/db_helper_sqlite/src/admin-apis/banner.ts index 6fee19b..89b78e5 100644 --- a/packages/db_helper_sqlite/src/admin-apis/banner.ts +++ b/packages/db_helper_sqlite/src/admin-apis/banner.ts @@ -15,7 +15,11 @@ const assertBannerSkuIdsInRegion = async (txOrDb: any, skuIds: number[], regionI const found = new Set(rows.map((r: { id: number }) => r.id)) throw new Error(`Invalid SKU IDs: ${unique.filter((id) => !found.has(id)).join(', ')}`) } - const foreign = rows.filter((r: any) => r.product?.regionId !== regionId) + // A global SKU (product regionId null) belongs to no region and may be attached anywhere. + const foreign = rows.filter((r: any) => { + const skuRegionId = r.product?.regionId ?? null + return skuRegionId !== null && skuRegionId !== regionId + }) if (foreign.length > 0) { throw new Error(`SKU ${foreign.map((r: any) => r.id).join(', ')} belongs to a different region`) } diff --git a/packages/db_helper_sqlite/src/admin-apis/coupon.ts b/packages/db_helper_sqlite/src/admin-apis/coupon.ts index 038ec98..e90b647 100644 --- a/packages/db_helper_sqlite/src/admin-apis/coupon.ts +++ b/packages/db_helper_sqlite/src/admin-apis/coupon.ts @@ -15,7 +15,11 @@ const assertApplicableSkusInRegion = async (txOrDb: any, skuIds: number[], regio const found = new Set(rows.map((r: { id: number }) => r.id)) throw new Error(`Invalid SKU IDs: ${unique.filter((id) => !found.has(id)).join(', ')}`) } - const foreign = rows.filter((r: any) => r.product?.regionId !== regionId) + // A global SKU (product regionId null) belongs to no region and may be attached anywhere. + const foreign = rows.filter((r: any) => { + const skuRegionId = r.product?.regionId ?? null + return skuRegionId !== null && skuRegionId !== regionId + }) if (foreign.length > 0) { throw new Error(`SKU ${foreign.map((r: any) => r.id).join(', ')} belongs to a different region`) } diff --git a/packages/db_helper_sqlite/src/admin-apis/slots.ts b/packages/db_helper_sqlite/src/admin-apis/slots.ts index 45bfe9d..ddc8c81 100644 --- a/packages/db_helper_sqlite/src/admin-apis/slots.ts +++ b/packages/db_helper_sqlite/src/admin-apis/slots.ts @@ -78,7 +78,11 @@ const assertSkuIdsInRegion = async (tx: any, skuIds: number[], regionId: number, if (missing.length > 0) { throw new Error(`Invalid ${noun} IDs: ${missing.join(', ')}`) } - 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 + }) if (foreign.length > 0) { throw new Error(`${noun} ${foreign.join(', ')} belongs to a different region`) }