freshyo/apps/backend/tests/BUGS.md
2026-10-15 20:31:20 +05:30

25 KiB
Raw Blame History

Known bugs — apps/backend

Found while writing the API integration suites under tests/api/. Each entry gives the source location, the actual behaviour, the expected behaviour and the test that pins it. Severity is my judgement of impact.


High — security / data integrity

1. A user token can perform admin writes (missing staff guard)

src/trpc/trpc-index.ts — protectedProcedure only requires some identity (ctx.user OR ctx.staffUser). Many admin.* procedures never re-check ctx.staffUser, so a plain user token can call them.

Confirmed reachable with a user token:

  • admin.order.cancelOrder — cancel any order
  • admin.user.updateUserSuspension — suspend any user
  • admin.user.sendNotification — broadcast notifications
  • admin.product.toggleOutOfStock (and the other admin.product.* writes)
  • admin.staffUser.createStaffUser — create a usable staff account (privilege escalation); the new account can log in

Procedures that do guard correctly: admin.slots.*, admin.coupon.create, admin.coupon.createReservedCoupon (they check ctx.staffUser?.id).

Fix: add a staffProcedure (or a ctx.staffUser check) to every admin.* write.

Pinned by: tests/api/authorization-matrix.test.ts.

Partially fixed (FC-01/SEC-01): admin.const.* is no longer reachable with a user token. The router now uses staffProcedure; updateConstants also rejects global-scope keys (globals are superadmin-only), and the redundant getGlobalConstants/updateGlobalConstants/getLegacyConstants/ updateLegacyConstants procedures were removed (they had no production UI caller — the admin apps use admin.region.*, the superadmin UI uses superadmin.const.*). The remaining entries above are still open.

2. Public admin.vendorSnippets endpoints

src/trpc/apis/admin-apis/apis/vendor-snippets.ts

  • getUpcomingSlots:176? / 259 — publicProcedure
  • getOrdersBySnippet:176 — publicProcedure, returns order/customer data for a snippet code
  • getOrdersBySnippetAndSlot:275 — publicProcedure
  • updateOrderItemPackaging:362 — publicProcedure with the staff check commented out (lines 355-360), so anyone can flip packaging state

Fix: require staff on all four.

Pinned by: tests/api/authorization-matrix.test.ts.

3. user.auth.updateProfile always throws

src/trpc/apis/user-apis/apis/auth.ts:342

const authHeader = ctx.req.header('authorization');

ctx.req is a fetch Request (see src/app.ts context: { req, c, ... }), which has .headers.get(...), not .header(...). The call throws TypeError: ctx.req.header is not a function.

Worse, the profile update (updateUserProfileInDb) and the profile image URL resolving both run before line 342, so the write is committed and the client still receives an error — a silent partial success.

Fix: ctx.req.headers.get('authorization') (or use ctx.c).

Pinned by: tests/api/misc-procedures.test.ts — "pins: updateProfile crashes after writing the change".

Fixed (FC-15/AU-07): Context.req is now typed as the fetch Request the adapter actually passes, and updateProfile reads ctx.req.headers.get('authorization'). The optional email was also relaxed: an empty email means "no change" (the client only requires it when registering).

4. user.auth.updatePassword silently does nothing

packages/db_helper_sqlite/src/user-apis/auth.ts:177 (upsertUserPassword)

try {
  await db.insert(userCreds).values({ userId, userPassword: hashedPassword })
  return
} catch (error) {
  if (error.code === '23505') { /* postgres unique violation -> UPDATE */ }
  throw error
}

user_creds has no UNIQUE constraint on user_id (schema: id, user_id, user_password, created_at), and 23505 is the Postgres unique-violation code — on D1 the insert simply succeeds. Result: a second credentials row is created, getUserAuthCreds keeps returning the original row, and the account's password never changes.

Verified: after "updating" the password, the old password still logs in and the new one is rejected; the user now has duplicate rows in user_creds.

Fix: add a UNIQUE index on user_creds.user_id and handle the SQLite constraint code, or do an explicit select-then-insert/update.

Pinned by: tests/api/misc-procedures.test.ts — "pins: updatePassword reports success but the old password still works".

Fixed (FC-16/AU-08): upsertUserPassword now does an explicit select-then-update-or-insert (updating every row for the user, which also repairs existing duplicates), and a uniqueIndex on user_creds.user_id was added to the schema. Existing duplicate rows must be deduped before the index migration can be applied (the local DB has duplicates for users 379, 908, 1311).


High — money

5. A ≥100% coupon produces a negative order total

packages/db_helper_sqlite/src/user-apis/order.ts (applyDiscountToOrder)

The percentage branch caps the discount at maxValue * proportion or Infinity and never at orderTotal (the flat branch does cap at the order total). A coupon with discountPercent >= 100 and no maxValue therefore drives orders.totalAmount to zero or negative. admin.coupon.create accepts any discountPercent (no upper bound).

Pinned by: tests/api/coupon-math.test.ts — "pins: a 150% coupon produces a negative total".

6. The discount is applied to the delivery-inclusive base

src/trpc/apis/user-apis/apis/order.ts:156

const orderTotalAmount = isFirstOrder ? subOrderTotalWithDelivery : subOrderTotal;

isFirstOrder is true for the first sub-order of every placeOrder call, so that sub-order's discount is computed on goods + deliveryCharge. A percentage coupon therefore discounts the delivery fee as well.

Pinned by: tests/api/coupon-math.test.ts — "pins: a percentage coupon discounts the delivery fee too".

Fixed (FC-08): placeOrderUtil now computes the coupon discount on the whole cart subtotal and decides delivery on the post-discount total (finalTotal < freeDeliveryThreshold), mirroring the customer app. A percentage coupon no longer touches the delivery fee. (FC-07 is fixed too: the threshold key is now freeDeliveryThreshold, not minRegularOrderValue.)

7. Money is never rounded

Nothing rounds totalAmount; it is written with .toString() on a raw float, so percentage discounts leave float noise (e.g. 999 - 15%).

Pinned by: tests/api/coupon-math.test.ts — "pins: amounts are stored unrounded".

Fixed (coupon stacking): coupon discounts are now rounded to the nearest rupee in the shared computeCartPricing / computeCouponStack (packages/shared/cart-pricing.ts) and multiple coupons stack sequentially in the order the customer applied them. orders.totalAmount no longer carries float noise.


Medium — coupon rules

8. Coupon scoping is not enforced at placeOrder

validateAndGetCoupon checks invalidated / expiry / per-user limit / minOrder / first-order-only, but not isUserBased, applicableUsers, skuIds or exclusiveApply. Only the display endpoints (getEligible / getMyCoupons) filter by applicability, so user B can spend a coupon issued to user A by passing its id to placeOrder.

Pinned by: tests/api/coupon-ux.test.ts — "rejects user B applying a coupon issued to user A".

FIXED 2026-10-11: validateAndGetCoupons now enforces, per coupon: user-based applicability, skuIds/coupon_applicable_products product targeting (the coupon must match at least one cart line, and minOrder compares against the targeted subtotal), region (coupons.regionId null = global, else the order's region), and exclusiveApply (an exclusive coupon cannot be combined with any other). The customer coupon list (getEligible/getMyCoupons) is region-filtered too.

9. Cancelling an order does not release its coupon usage

recordUserCouponUsage runs at placement; cancelOrderTransaction never touches coupon_usage. A cancelled order permanently consumes a maxLimitForUser slot.

Pinned by: tests/api/order-lifecycle-gaps.test.ts — "pins: cancelling an order does not release its coupon usage".

FIXED 2026-10-11: both cancel paths now delete the group's coupon_usage row(s) once every sibling order sharing the orderGroupId is cancelled (releaseCouponUsageIfGroupFullyCancelled, called from cancelOrderTransaction and admin cancelOrder). A lone order counts as "all" and releases on cancel. The lifecycle tests now assert the release.

10. A cancelled first order poisons an isFirstOrderOnly coupon

getOrderCount counts every order including cancelled ones, and isUserBased/first-order checks run off it — so placing and cancelling a first order permanently blocks a first-order-only coupon for that user.

Pinned by: tests/api/order-lifecycle-gaps.test.ts — "pins: a cancelled first order poisons an isFirstOrderOnly coupon".

FIXED 2026-10-11: first-order eligibility now uses countEffectiveOrders — distinct, non-cancelled order groups (a split placement counts once, a cancelled order not at all). getOrderCount keeps its row-count meaning for pagination. The lifecycle test now asserts the coupon still applies.

11. Reserved-coupon expiry is not checked at redemption — FIXED 2026-10-10

redeemReservedCoupon checked "already redeemed" and first-order-only, but not validTill, so an expired reserved code still redeemed (it only failed later at placeOrder) and the secret was burned for a dead coupon.

Fix: the redeem route now rejects validTill < now with "This coupon has expired" (policy: one deadline for both claiming the secret and spending the coupon), and redeemReservedCoupon claims the secret with a conditional update (WHERE is_redeemed = 0) before creating the coupon, so two customers racing the same code can no longer both receive one.

Covered by: tests/api/coupon-ux.test.ts — "rejects an expired reserved code" and "lets only one of two simultaneous claims win".

12. exclusiveApply is stored but never enforced

Coupons carry exclusiveApply, and placeOrder accepts a single couponId, so the flag has no effect anywhere. (Observation from reading the code; no runtime test.)

FIXED 2026-10-11: orders now accept couponIds: number[] and validateAndGetCoupons rejects any combination where one coupon is exclusive (it must be the only coupon on the order).


Medium — placeOrder guards

13. Out-of-stock products are still orderable

placeOrderUtil checks isFlashAvailable for flash orders but never isOutOfStock.

Pinned by: tests/api/place-order-edge-cases.test.ts.

Fixed (FC-03/SEC-05): placeOrderUtil now rejects a product that is isDeleted, isOutOfStock or isSuspended (400 "… is unavailable"). The cross-region-SKU case (FC-02/SEC-04) is rejected too: the SKU's product regionId must equal the order region (409).

14. An empty selectedItems list fails with a raw DB error

There is no .min(1) on selectedItems, so an empty list reaches Drizzle, which throws values() must be called with at least one value instead of returning a 400.

Pinned by: tests/api/place-order-edge-cases.test.ts.

15. No quantity cap

quantity is z.number().int().positive() with no upper bound; 1_000_000 units are accepted.

Pinned by: tests/api/place-order-edge-cases.test.ts.

16. No slot validity checks

placeOrder only checks slot capacity. An inactive slot, a slot whose delivery time has already passed, and a slot that does not carry the ordered SKU are all accepted.

Pinned by: tests/api/place-order-edge-cases.test.ts.

Fixed (FC-03/SEC-05, FC-13/SL-04): placeOrderUtil now requires a non-null slotId for scheduled orders and validates the slot: it must exist, belong to the order region (409), be isActive, have freezeTime > now and deliveryTime > now, and carry every ordered skuId in slot.skuIds (400 otherwise).

17. No idempotency

Two identical placeOrder calls create two orders (orderGroupId is Date.now()-userId, with no uniqueness check).

Pinned by: tests/api/place-order-edge-cases.test.ts.

Mitigated client-side (FC-17/OR-12): the Place Order button is disabled while a submit is in flight and handlePlaceOrder early-returns via a synchronous useRef guard, so an accidental double-tap cannot submit twice. Server-side idempotency is still absent — a direct API replay or network retry can create duplicates. A client-generated idempotency key remains the proper fix if/when wanted.


Low — error handling / lifecycle

18. cancelOrder swallows every error into one generic message

src/trpc/apis/user-apis/apis/order.ts:554-599 wraps the whole handler in a try/catch that rethrows new ApiError("failed to cancel order"), discarding the specific 404/400 messages it constructs ("Order not found", "Order is already cancelled", "Cannot cancel delivered order"). updateUserNotes, by contrast, has no catch and propagates its real messages.

Pinned by: tests/api/order-lifecycle-gaps.test.ts and tests/api/authorization-matrix.test.ts.

19. No order status transition guards

admin.order.updateDelivered / updatePackaged accept any state: a cancelled order can be marked delivered, and delivered is reversible.

Pinned by: tests/api/order-lifecycle-gaps.test.ts.

20. getUserDetails breaks past ~110 orders

admin.user.getUserDetails builds an unchunked IN (...) over the user's order ids and fails once the history is large. Documented in tests/api/admin-users.test.ts (that suite uses a throwaway user to avoid it).


21. Bound pricing followed a client-supplied boundId — FIXED 2026-10-10

placeOrderUtil resolved the delivery charge and free-delivery threshold from params.boundId ?? getEffectiveBoundId(regionId). boundId is a plain optional mutation input, and getRegionSettingsForBound only checked that the bound belongs to the region — never to the order's address. So an order against an address in bound 2 (₹200 / free above ₹800) could be placed with boundId: 1 (₹20 / free above ₹300) and be charged ₹20. The address's own boundId was never read on this path.

Fix (policy): the delivery address's bound is authoritative — address.boundId ?? params.boundId ?? getEffectiveBoundId(regionId). This mirrors the customer app, which already prices the selected address's bound (apps/user-ui/src/hooks/prominent-api-hooks.ts → useGetEssentialConsts), and keeps the bound-less-address fallback intact. Verified live: address 879 (bound 2)

  • boundId: 1 now charges ₹200 (was ₹20); a bound-less address still honours the client bound (₹20 for bound 1, ₹200 for bound 2).

No regression test yet: the suite has no bound fixtures and no superadmin session helper, so it cannot create a second bound to compare against.


22. Explicit rebalance dropped the delivery charge — FIXED 2026-10-10

rebalanceSlots repriced an order as total = items(latest prices) − discount, never adding deliveryCharge back — so every rebalanced order lost its fee from the payable (while the delivery_charge column kept the old value). It also re-derived the discount from the coupon's current state and looked it up per order, so invalidating/expiring a coupon silently raised a historical total, and multi-slot sub-orders (which own no coupon_usage row) lost their prorated discount entirely. Delivered and cancelled orders were repriced too.

Fix (policy): freeze the historic discount and delivery fee; rebalance only product prices. The charged discount is recovered from the stored row itself (items + fee − total), which is immune to later coupon changes and preserves a sub-order's prorated share; the fee is added back; delivered/cancelled orders are skipped; a SKU with no price for the region keeps its stored price instead of dropping to 0. Verified live: a no-op rebalance now leaves the payable untouched, an invalidated coupon no longer changes it, and repricing keeps items − frozen discount + fee.

Known residue: the customer/admin order detail display still recomputes the discount from the coupon, so after a reprice it can show a discount that differs from the frozen one (the payable is correct). Same family as the A23 display decision; db.transaction is still the no-op stub, so the write loop is not atomic; money is still written unrounded (see #7). Orders rebalanced by the old code carry a phantom discount equal to the dropped fee and were not auto-repaired.


23. updateProduct stored unvalidated image keys — FIXED 2026-10-10

createProduct validated every referenced image (skus.flatMap((s) => s.images) → assertUploadUrlsClaimable → claimUploadUrls), but updateProduct validated only the declared newImageUrls and then wrote skus[].images straight through (extractKeyFromPresignedUrl → updateProductInDb) with no check and no claim. A fabricated key therefore produced a permanently broken image, and another product's already-claimed key could be silently reused (createProduct rejects that as "already used").

Fix: validate the delta — the keys the product does not already own (via a new getProductImageKeys(regionId, productId) helper) plus newImageUrls — before the write, and claim them after it. The product's own images may be re-sent by the edit form untouched. Verified live: fabricated key → rejected with nothing written; another product's claimed image → rejected; own image re-sent → 200; genuine pending upload → 200 and claimed.

Banners, stores and global stores also convert URLs to keys without this guard, but the upload endpoint only issues the contexts review | product_info | notification | complaint | profile | tags, so those images are never registered in upload_url_status — guarding them would reject legitimate images.


24. Editing an address cleared its default flag — FIXED 2026-10-10

user.address.updateAddress forwarded isDefault: isDefault || false while the input schema declares isDefault optional. An edit that omitted the field — the natural partial update — therefore unset the address's default and left the user with zero default addresses. (createAddress computes makeDefault = isDefault || no-other-addresses, so it never had the bug; the AddressForm and checkout selector already send the current value, so the UI did not expose it.)

Fix: isDefault: isDefault ?? existingAddress.isDefault — omitted keeps the current value, explicit true sets it and clears the other addresses' defaults, explicit false still clears it.

Related, still open: explicitly sending isDefault: false (or deleting the only default address, see AD-08) can still leave a user with no default.


25. Address phone/pincode were unvalidated — FIXED 2026-10-10

user.address.createAddress / updateAddress accepted any non-empty string for phone and pincode (only min(1)), so phone: "123" and pincode: "12" were persisted. The app's form validated both client-side, so only a non-app client could store garbage — which is what the run did.

Fix (rule): phone = exactly 10 digits starting 6/7/8/9; pincode = exactly 6 digits, enforced in both procedures, with the UI's phone regex aligned. Verified live: 123 / 1234567890 / 5678901234 / 9-digit / 11-digit phones and 5-digit / 7-digit / non-numeric pincodes all return 400; a valid pair is accepted; the update path rejects too.

Note: zod-level input validation already surfaces as HTTP 400 — only ApiError throws are flattened to 500 (see #… / A19).


26. A user could delete their only address — FIXED 2026-10-10

user.address.deleteAddress guarded against an address attached to an ongoing order and against the default address, but nothing stopped the user deleting their only address — leaving an account with nowhere to deliver to (the same zero-address state that editing could reach, see #24). The refusals were also plain Errors, so they surfaced as HTTP 500.

Fix (rule): deleting the user's only address is refused with “This is your only address. Add another address before deleting this one.”, and the app shows it in a BottomDialog (checked before the “are you sure?” step and again from the mutation's onError). The other refusals now throw ApiError (409 / 404) so they reach the customer as 4xx.

Still open: explicitly sending isDefault: false for the last default can still leave an account with no default address.


27. updateProductPrices addressed SKUs as productId — FIXED 2026-10-10

admin.product.updateProductPrices took updates[].productId, but the helper validated it against productSkus.id and wrote product_market_stats.skuId. A product id therefore landed on whatever SKU carried the same number (product ids and SKU ids are separate, overlapping sequences), and the response still said “Updated prices for N product(s)”. An entry with no price field wrote nothing yet was counted as updated and reported as a success.

Fix: the input field is skuId (no alias), the messages say SKU, an entry with no price field is rejected up front (No price fields to update for SKU(s): …), and updatedCount counts rows actually written. The admin-ui and admin-web price screens were updated, along with three test payloads — cache-invalidation.test.ts had been passing a product id and only passed while the two ids happened to coincide.

Residual (accepted): id values still overlap, so a caller that passes a product id for skuId still hits the same-numbered SKU. That is now an explicit caller error rather than an API trap; mapping a product id to its SKUs is deliberately not done because that ambiguity is what caused the bug.


28. Business errors left tRPC as HTTP 500 — FIXED 2026-10-10

errorLoggerMiddleware translated our ApiError to a TRPCError inside a try/catch around next(). In tRPC 11 that catch is unreachable for resolver errors: callRecursive catches them and returns the middleware a { ok: false, error } result, and getTRPCErrorFromUnknown has already wrapped a non-TRPCError as INTERNAL_SERVER_ERROR (keeping the original on cause) — which is why every business rejection arrived as HTTP 500 with the correct message.

Fix: the middleware now inspects the result and re-throws translateResultError(result.error), which maps result.error.cause only when it is an ApiError, so zod BAD_REQUESTs, UNAUTHORIZEDs and genuine 500s keep the code tRPC gave them. Verified live: 400 (expired reserved coupon, duplicate product name, bogus upload URL on product + tag, wrong-scope const writes on both admin and superadmin), 403 (capacity-full slot), 409 (only address, default address, address on an open order); controls unchanged (400 zod, 404 unknown procedure, 401 no token).

Residual: business rejections thrown as plain Error inside the db-helper packages still return 500 — validateAndGetCoupon (not applicable, Coupon has expired, invalidated, usage-limit, min-order, first-order-only) is the main one. 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 (sendOtp/verifyOtp) and deleteAccount are deliberately untested and not listed here.