Compare commits
No commits in common. "577536f9c1a2d20bf1b3b681e78b33e7671a6bb6" and "1b7b3b97e992d113679ce71dc361f31272085c1f" have entirely different histories.
577536f9c1
...
1b7b3b97e9
14 changed files with 21528 additions and 14527 deletions
|
|
@ -1,312 +0,0 @@
|
||||||
# Freshyo Monorepo — Full Code Review
|
|
||||||
|
|
||||||
- **Date:** 2026-11-02
|
|
||||||
- **Branch:** `main`, at commit `0ca0a95`
|
|
||||||
- **Method:** read-only review. No files under review were edited, and no tests or migrations were run.
|
|
||||||
- **Scope:** all apps and packages except `packages/db_helper_postgres`, which is abandoned.
|
|
||||||
- **Known issues:** anything already listed in `unfixed-issues-MULTI_REGION_I2.md` is left out.
|
|
||||||
- **Deployment model:** the git remote is private and self-hosted, so repository contents are not treated as an exposure vector. Findings that only matter if the repo leaks (committed credentials, database dumps, tracked `.env` files) are excluded.
|
|
||||||
|
|
||||||
Severity runs from Critical to High, Medium and Low. **✓** means the finding was checked directly in the source. Unmarked findings come from the area reviewers, with the confidence they reported.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Round 1
|
|
||||||
|
|
||||||
### Critical
|
|
||||||
|
|
||||||
#### C1. The production superadmin is seeded with a test password and cannot be changed
|
|
||||||
- **Where:** `packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql:96-98` seeds the `superadmin` user with a fixed bcrypt hash that matches `TEST_SUPERADMIN_PASSWORD` in `apps/backend/tests/.env`. There is no endpoint for changing the superadmin password.
|
|
||||||
- **Why this still matters with a private repo:** the exposure is not "someone reads the repo". It is that the production credential is a *test* credential:
|
|
||||||
- anyone who has ever had a clone, a backup, a laptop, a CI log or a screenshare retains it;
|
|
||||||
- it cannot be rotated through the product, only by hand-editing the database;
|
|
||||||
- superadmin login (`superadmin-apis/apis/auth.ts:10`) has no throttling, so a weak or common test password is remotely brute-forceable.
|
|
||||||
- **Check:** confirm what the live production hash actually resolves to. If it is still the seeded value, log in and change it, or add a password-change endpoint.
|
|
||||||
|
|
||||||
#### C2. Admin endpoints can be called with a customer token ✓
|
|
||||||
- **Cause:** `adminRouter` (`admin-apis/apis/admin-trpc-index.ts`) has no staff-only gate, and `protectedProcedure` (`trpc-index.ts:121-128`) accepts customer tokens.
|
|
||||||
- **Confirmed reachable by a customer:**
|
|
||||||
- `admin.user.updateUserSuspension` (`admin-apis/apis/user.ts:143-157`) can suspend or unsuspend any user, with no region check either.
|
|
||||||
- `admin.user.sendNotification` (`user.ts:183-252`) sends any title, text and image to every device when `userIds: []`.
|
|
||||||
- `admin.staffUser.getStaff` and `getRoles` (`staff-user.ts:66,121`) list every staff member, role and permission.
|
|
||||||
- **Partly protected:** admin handlers that read `ctx.staffUser!.regionId` fail with a TypeError (a 500) when a customer calls them, so they are protected by accident.
|
|
||||||
- **Fix:** add a `staffProcedure` and use it for the whole admin router.
|
|
||||||
|
|
||||||
#### C3. The dev worker uses the production database ✓
|
|
||||||
- **Where:** `wrangler.dev.toml:14` and `wrangler.prod.toml:12` have the same D1 `database_id`, and the same JWT secret.
|
|
||||||
- **Impact:** a `deploy:dev` build reads and writes live orders, and a dev-issued token is accepted by production (it is the same signing key, so environment separation does not exist at the auth layer).
|
|
||||||
- **Also affected:** dev image uploads go to the `meatfarmer-dev` bucket while their database rows land in prod, so those images break in prod.
|
|
||||||
- **Related ✓:** `apps/backend/reset-remote-db.sh:24-25` runs `wrangler d1 delete` and then `create` on that database. Prod goes down, and the new database id no longer matches `wrangler.prod.toml`.
|
|
||||||
|
|
||||||
### High
|
|
||||||
|
|
||||||
#### H1. Database transactions do nothing ✓
|
|
||||||
- **Cause:** `packages/db_helper_sqlite/src/db/db_index.ts:29-33` replaces `transaction` with `handler(base)`, so the 36 call sites get no atomicity.
|
|
||||||
- **Order placement:** `placeOrderTransaction` (`user-apis/order.ts:339-368`) inserts the orders, then the items five at a time, then the statuses. Cart deletion and `recordUserCouponUsage` are separate writes.
|
|
||||||
- **Effect of a partial failure:** an order with no items or no `order_status` row. It can't be cancelled ("Order status not found"), or the discount is applied but the coupon usage is never recorded.
|
|
||||||
- **Other writers affected:** `createSlotWithRelations`, `rebalanceSlots`, product create/update, and user and admin cancel.
|
|
||||||
- **Fix:** use `db.batch`, as `redeemReservedCoupon` already does.
|
|
||||||
|
|
||||||
#### H2. Coupon limits can be beaten by placing two orders at once
|
|
||||||
- **Where:** `validateAndGetCoupons` (`user-apis/order.ts:150,168`) checks usage, and the usage row is only written after the orders are inserted.
|
|
||||||
- **Gap:** no unique constraint, conditional write or idempotency key prevents a second use.
|
|
||||||
- **Scenario:** two parallel `placeOrder` calls with a `maxLimitForUser=1` or first-order-only coupon both get the discount.
|
|
||||||
- **Related:** `orderGroupId = \`${Date.now()}-${userId}\`` (`order.ts:69`) can collide when one user sends two requests in the same millisecond.
|
|
||||||
|
|
||||||
#### H3. Suspended users keep full tRPC access ✓
|
|
||||||
- **Where:** `apps/backend/src/app.ts:80-94`.
|
|
||||||
- **Cause:** `user = decoded` is set before the suspension check, and the thrown `TRPCError` is swallowed by `catch {}`. Suspension is only enforced on the Hono `/api/v1` path.
|
|
||||||
|
|
||||||
#### H4. `vendorSnippets.updateOrderItemPackaging` needs no login ✓
|
|
||||||
- **Where:** `admin-apis/apis/vendor-snippets.ts:366-387`. It is a `publicProcedure`, and its auth check is commented out.
|
|
||||||
- **Impact:** anyone can flip `is_packaged` on any order item by trying sequential IDs.
|
|
||||||
- **Related:** `getOrdersBySnippetAndSlot` (`:278-298`) ignores snippet `validTill` and never checks that the slot belongs to the snippet or its region. One valid code returns another region's customer orders.
|
|
||||||
|
|
||||||
#### H5. An address outside every delivery area takes the region the client sends ✓
|
|
||||||
- **Where:** `user-apis/apis/order.ts:80-90`.
|
|
||||||
- **Cause:** when the address has coordinates but `resolveRegionAndBound` returns null, the `else if` skips `address.regionId`.
|
|
||||||
- **Impact:** the client's `regionId`/`boundId` then decides pricing, the delivery charge, the free-delivery threshold and whether flash is allowed.
|
|
||||||
|
|
||||||
#### H6. A customer can change their mobile number without OTP
|
|
||||||
- **Where:** `user-apis/apis/auth.ts:303-333`.
|
|
||||||
- **Scenario:** an attacker sets their account's mobile to a victim's unregistered number. When the victim later logs in by OTP, they land in the attacker's account.
|
|
||||||
|
|
||||||
#### H7. The profile image path can read other buckets
|
|
||||||
- **Where:** `user-apis/apis/auth.ts:129,173,180,282,335` → `s3-client.ts:160-179`.
|
|
||||||
- **Cause:** `profileImageUrl` accepts any string, and `new URL` collapses `../`. A value like `../meatfarmer-dev/<key>` returns a signed GET URL for another bucket's object.
|
|
||||||
- **Confidence:** medium. It depends on the R2 key having access to more than one bucket.
|
|
||||||
|
|
||||||
#### H8. The cart picks delivery slots that have already closed (user-ui and server) ✓
|
|
||||||
- **Where:** `apps/user-ui/components/cart-page.tsx:806-824` and `:450`, `hooks/useProductSlotIdentifier.ts:21-23`, `components/floating-cart-bar.tsx:144-152`, and the server's `getAllSlotsWithProductsForCache` (`packages/db_helper_sqlite/src/stores/store-helpers.ts:371-376`).
|
|
||||||
- **Cause:** all of these filter only `deliveryTime > now` and ignore `freezeTime`.
|
|
||||||
- **Scenario:** after a slot's freeze time, the cart still auto-selects it as the earliest slot, then shows "slot has closed" and blocks checkout.
|
|
||||||
|
|
||||||
#### H9. A slot picked in the user-ui cart reverts on any cart refetch
|
|
||||||
- **Where:** `cart-page.tsx:788-831`.
|
|
||||||
- **Cause:** the effect depends on `cartItems` and rewrites each slot from the saved `item.slotId`. The choices made in `setSelectedSlots` and "Deliver all at…" are never saved.
|
|
||||||
- **Scenario:** change a slot, then tap +/- or let the app regain focus. The slot jumps back.
|
|
||||||
|
|
||||||
#### H10. web-ui: lowering quantity to 0 never removes the item ✓
|
|
||||||
- **Where:** `apps/web-ui/src/components/ProductCard.tsx:68`, `routes/home.product.$id.tsx:77`, `routes/flash.tsx:433`.
|
|
||||||
- **Cause:** these pass the cart line's `id` (a `Date.now()` value), but `useRemoveFromCart` (`hooks/cart-query-hooks.ts:128-142`) filters by `skuId`.
|
|
||||||
|
|
||||||
#### H11. web-ui ignores the per-area "flash delivery enabled" setting
|
|
||||||
- **Where:** `apps/web-ui/src/components/AddToCartDialog.tsx:34` hardcodes `isFlashDeliveryEnabled = true`, and `/flash` has no gate. user-ui blocks the flash section in `flash-delivery/_layout.tsx:14`.
|
|
||||||
- **Impact:** production crons switch flash off every day, and web users can still check out. Their orders then fail with a 403.
|
|
||||||
|
|
||||||
#### H12. web-ui never repairs expired cart slots and can pick a past slot
|
|
||||||
- **Where:** `apps/web-ui/src/hooks/useProductSlotIdentifier.ts:16-21` returns `slots[0]` unsorted, with no time filter, and there is no `useReconcileCartSlots` equivalent. `PaymentAndOrderComponent.tsx:104` sends the stored `slotId` as is.
|
|
||||||
- **Impact:** checkout fails with "Selected delivery slot is closed for orders", and `/cart` gives no way to change the slot.
|
|
||||||
|
|
||||||
#### H13. web-ui checkout sends out-of-stock and non-flash items, so the whole order is rejected
|
|
||||||
- **Where:** `components/PaymentAndOrderComponent.tsx:101-111`, `routes/flash.checkout.tsx:93`, `routes/home.checkout.tsx:93`. user-ui filters these out (`PaymentAndOrderComponent.tsx:121-131`).
|
|
||||||
- **Impact:** one out-of-stock line blocks checkout on web, and `/cart` shows no out-of-stock indicator.
|
|
||||||
|
|
||||||
#### H14. Admin product edit puts every out-of-stock variant back in stock ✓
|
|
||||||
- **Where:** admin-ui `products/edit.tsx:163-183` and admin-web `dashboard.products.edit.tsx` leave `isOutOfStock` out of the variant payload.
|
|
||||||
- **Cause:** the server defaults the missing value to `false` (`admin-apis/apis/product.ts:62`) and writes it.
|
|
||||||
- **Scenario:** fix a typo in a product name, and every out-of-stock variant goes back on sale.
|
|
||||||
|
|
||||||
#### H15. Saving a product twice deletes all its images, from storage too
|
|
||||||
- **Where:** `products/edit.tsx:202` calls `clearImages()` after a successful save while the screen stays open. admin-web does the same (`dashboard.products.edit.tsx:195`).
|
|
||||||
- **Cause:** on the next save, `ProductForm.tsx:253-261` marks every existing key as deleted, and the server removes the R2 objects (`apis/product.ts:431-436`).
|
|
||||||
|
|
||||||
#### H16. Editing a slot that has vendor snippets fails or duplicates them
|
|
||||||
- **Where:** `SlotForm.tsx:65-70` reads `snippet.name`, but the server only returns `snippetCode` (`db_helper_sqlite/.../slots.ts:110-118`).
|
|
||||||
- **Effect:** the update fails validation. If the admin types a name, `updateSlotWithRelations` (`slots.ts:382-402`) creates a duplicate snippet with a new code.
|
|
||||||
|
|
||||||
#### H17. Admin delivery sequence saves the wrong driver's list
|
|
||||||
- **Where:** admin-ui `delivery-sequences/index.tsx:432-437, 485-491, 714`, admin-web `dashboard.orders.sequence.tsx:438-457`.
|
|
||||||
- **Cause:** the "unsaved changes" flag isn't reset when the selected driver changes.
|
|
||||||
- **Scenario A:** reorder driver A's list, switch to driver B, and save. B's unchanged list is saved, A's reorder is lost, and a success message is shown.
|
|
||||||
- **Scenario B:** saving while "All Users" (-2) is selected stores a corrupt `"-2"` key. After that, the Unassigned view is always empty and the assignment labels are wrong.
|
|
||||||
|
|
||||||
### Medium
|
|
||||||
|
|
||||||
#### Backend
|
|
||||||
- **Cancelled orders can be marked delivered.** `updateOrderDelivered` (`admin-apis/order.ts:134-155`) has no `isCancelled` check, and it sends a "delivered" notification. `updateOrderPackaged(false)` resets `isDelivered=false`, which reopens a delivered order. Neither path rejects archived orders.
|
|
||||||
- **Complaints can be filed against another user's order.** `user-apis/apis/complaint.ts:34-48` never checks `orderId` against the user.
|
|
||||||
- **Cache versions can collide.** `region-cache-versions.ts:40-60` reads the version and then writes +1. Concurrent slot, stock or price mutations can get the same version, and the client never refetches. Fix: `UPDATE … SET value = value + 1 RETURNING value`.
|
|
||||||
- **Fractional quantities can never be ordered.** `placeOrder` requires `quantity: z.number().int()` (`order.ts:375`), while `increment_step` is a `real` column.
|
|
||||||
- **Combo-only SKUs can be bought on their own.** `order.ts:164-171` doesn't check `isComboOnly`.
|
|
||||||
- **Staff roles are never enforced.** Any staff member, even a `marketer`, can call `createStaffUser` with a `super_admin` role.
|
|
||||||
- **OTP and login have no rate limits.** OTP inputs are also put into the provider URL without escaping (`otp-utils.ts:35,57`). User login and register also reveal whether an account exists.
|
|
||||||
- **Missing indexes.** The hot foreign keys have none: `orders.user_id`, `order_items.order_id`, `order_status.order_id`, `coupon_usage(user_id, coupon_id)`, `addresses.user_id`, `notifications.user_id`, `notif_creds.user_id`, `product_skus.product_id`. D1 bills per row read.
|
|
||||||
- **Schema and migration drift.** Snapshots stop at 0002 while the journal goes to 0006, so the next `drizzle-kit generate` will produce a wrong migration. `schema.ts` doesn't declare the `idx_*_region` indexes, so they would be dropped. Its `region_id` nullability also doesn't match the database, and `reserved_coupons.region_id` has no foreign key.
|
|
||||||
- **Migration 0006 reuses an old filename.** Databases that applied the old 0006–0009 files may never run the squashed content. Confidence: low–medium.
|
|
||||||
|
|
||||||
#### user-ui
|
|
||||||
- **Stale selected address.** `useAddressStore` isn't reset on logout (`AuthContext.tsx:50-64`) or on address delete. Checkout shows the default address but submits the stale id, and the order fails with "Invalid address".
|
|
||||||
- **The Add-to-Cart dialog allows quantity 0** (`AddToCartDialog.tsx:261-266`). The server then rejects the whole order.
|
|
||||||
- **The flash cart bill includes items that can't be delivered by flash** (`cart-page.tsx:357-373, 491-510`). The coupon and free-delivery thresholds pass in the cart but fail at checkout.
|
|
||||||
- **A successful order clears the whole local cart**, including items that weren't ordered (`PaymentAndOrderComponent.tsx:59-62,94`).
|
|
||||||
- **`useAuthenticatedRoute` can push the login screen several times** because its focus callback is an inline function (`hooks/useAuthenticatedRoute.ts:16`).
|
|
||||||
|
|
||||||
#### web-ui
|
|
||||||
- **Login shows no errors at all** (`routes/login.tsx`).
|
|
||||||
- **The address list doesn't refresh.** The invalidation calls use the wrong key format, `['user.address.getUserAddresses']`, so they do nothing (`CheckoutAddressSelector.tsx:35`, `checkout-hooks.ts:71`, `checkout.tsx:130`).
|
|
||||||
- **Flash cart, checkout and success screens show the wrong price.** They use `price` instead of `flashPrice`, and the flash delivery charge is left out.
|
|
||||||
- **Logout leaves the previous user's data.** It doesn't call `queryClient.clear()` (`lib/auth-context.tsx:101-112`). The next user sees the previous user's cached data, and `RegionGate` writes it into the new user's snapshot.
|
|
||||||
- **The success page shows a locally computed total** instead of the server's `totalAmount`.
|
|
||||||
|
|
||||||
#### admin-ui and admin-web
|
|
||||||
- **A price-dialog save with no real change fails the whole batch** ("No price fields to update"). It also drops an earlier Flash toggle.
|
|
||||||
- **Coupon edit can't switch discount type or clear optional fields**, because `undefined` means "keep the current value".
|
|
||||||
- **Every coupon edit cuts `validTill` down to midnight.**
|
|
||||||
- **Coupon edit doesn't load `exclusiveApply` or `applicableUsers`.** Picking users then replaces the existing list.
|
|
||||||
- **admin-web toggles stock for the whole product instead of per variant** (`dashboard.products.tsx:85-87`).
|
|
||||||
- **The admin-ui orders list may crash.** `orders/index.tsx:186` uses `{score && score > 0 && …}`, which renders a bare `0` outside `<Text>`. Not reproduced on a device.
|
|
||||||
- **Rebalance has no confirmation and no double-submit guard**, and it shows "Rebalance Complete" from `onSettled`, so it also appears on errors.
|
|
||||||
|
|
||||||
### Low
|
|
||||||
- **Unchecked env values.** `env-exporter.ts:104-106`: if `MIN_ORDER_VALUE` or `DELIVERY_CHARGE` is missing they become `NaN`, and the delivery charge is silently never applied.
|
|
||||||
- **Unused setting.** `minOrderAmountForCoupon` is editable but never enforced.
|
|
||||||
- **Blind SSRF.** Possible through `googleMapsUrl` (`license-util.ts:3`).
|
|
||||||
- **Loose upload URLs.** They don't sign Content-Type, customers can write to admin asset folders, and keys collide when several MIME types are requested at once.
|
|
||||||
- **Large build artifacts tracked.** `apps/admin-ui/mfa_20_mar_dev.apk` (92 MB), `apps/user-ui/user-ui-shafi-dev-arm.apk` (35 MB), a 17 MB binary in `.opencode/`, `.expo` caches and `web-ui/.output`. Not a secret risk, but every clone and CI checkout pays for it.
|
|
||||||
- **Stale Docker setup.** It targets the old Postgres/Node backend, so it no longer describes how the app actually runs.
|
|
||||||
- **ProductCard re-renders every 5 s.** user-ui `ProductCard.tsx:62-67` bumps an unused `updater` state.
|
|
||||||
- **Delivery notes carry over.** `useCheckoutStore.userNotes` survives a successful order and logout.
|
|
||||||
- **Malformed checkout links crash.** A `slots` deep link without `:` crashes the checkout screen (`checkout-page.tsx:83-90`).
|
|
||||||
- **Cancelling "Remove item" resets the displayed quantity to 1** instead of the stored quantity.
|
|
||||||
- **Cart writes have no locking.** Read-modify-write on AsyncStorage can lose updates.
|
|
||||||
- **web quantity buttons ignore min/max.** The web `Quantifier` doesn't enforce them for steps that don't divide evenly, and fractional steps build up float error.
|
|
||||||
- **superadmin-ui and fallback-ui don't check token expiry.** The superadmin profile is also not restored after a reload.
|
|
||||||
- **Suspending a user fails silently** in the admin UI.
|
|
||||||
- **Two admin delivery-sequence problems.** The order menu shows stale status after an update, and selected order ids carry over when switching slots.
|
|
||||||
- **Large reads.** Slot and cache reads load the whole `productSkus` table, and the `!item.isDeleted` filter is a no-op because the column isn't selected.
|
|
||||||
- **web flash memoisation doesn't hold.** web `flash.tsx`'s `handleAddToCart` depends on the `useMutation` result object, which is new on every render, so the memo is ineffective.
|
|
||||||
- **Home ordering goes stale.** user-ui `getQuickestSlot` is memoised but depends on time, so the home catalogue ordering goes stale as slots expire.
|
|
||||||
|
|
||||||
### Checked and fine
|
|
||||||
- Address queries filter by `userId`, so there is no address IDOR.
|
|
||||||
- `/api/test` routes are gated by `ENABLE_TEST_ROUTES`.
|
|
||||||
- JWTs use HS256 and carry an expiry.
|
|
||||||
- The raw `sql` usage that was checked is parameterised.
|
|
||||||
- Prices are computed on the server, and discounts are capped at the subtotal.
|
|
||||||
- Scheduled orders enforce freeze time on the server.
|
|
||||||
- Catalogue image cache-busting only touches public asset URLs.
|
|
||||||
- web-ui has no `dangerouslySetInnerHTML`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Round 2 — deeper review
|
|
||||||
|
|
||||||
Round 2 was done by reading the code directly, since the scheduled reviewers were unavailable. Items marked ✓ were read and confirmed in the source.
|
|
||||||
|
|
||||||
### High
|
|
||||||
|
|
||||||
#### R2-1. The test suite asserts the auth holes as "current" behaviour ✓
|
|
||||||
- **Where:** `apps/backend/tests/api/auth-matrix.test.ts`.
|
|
||||||
- **What it does:**
|
|
||||||
- `AUTH-03` asserts that a customer token succeeds on `admin.vendorSnippets.getAll` and `admin.staffUser.getStaff`, and gets 500s from the other admin reads.
|
|
||||||
- `AUTH-04` asserts that a customer token passes the admin write guard, then *actually suspends a throwaway user* with a customer token and asserts `isOk === true`.
|
|
||||||
- `HARNESS-13` and `AUTH-11` assert that a suspended user still passes tRPC.
|
|
||||||
- **Why it matters:** these tests pass today, so a green suite does not mean the authorization is correct. Fixing C2 and H3 requires rewriting these cases; until then the suite actively protects the vulnerability.
|
|
||||||
|
|
||||||
#### R2-2. `web-ui` and `admin-web` have no tests at all ✓
|
|
||||||
- **Counts:** user-ui 56 test files, admin-ui 65, backend 72, web-ui 0, admin-web 0.
|
|
||||||
- **Impact:** every web-only bug found in round 1 (cart removal, flash gate, address invalidation keys, logout cache, wrong flash prices) is uncovered. The project rule that admin-ui and user-ui changes must be mirrored on web makes this the highest-risk blind spot, because the web copies drift without any test to catch it.
|
|
||||||
|
|
||||||
### Medium
|
|
||||||
|
|
||||||
#### R2-3. Cancelling an order always returns a 500 with a generic message ✓
|
|
||||||
- **Where:** `apps/backend/src/trpc/apis/user-apis/apis/order.ts:633-690`.
|
|
||||||
- **Cause:** the handler `catch`es every error and rethrows `new ApiError("failed to cancel order")`. `ApiError` defaults to status 500.
|
|
||||||
- **Effect:** "Order not found" (404), "already cancelled" (400) and "Cannot cancel delivered order" (400) all reach the client as a 500 "failed to cancel order". The specific messages only reach the logs.
|
|
||||||
- **Second effect:** `publishCancellation` is awaited *after* the cancel transaction. If the queue publish fails, the user is told the cancellation failed even though it succeeded. Retrying then hits "already cancelled", which also surfaces as the same generic 500.
|
|
||||||
- **Fix:** rethrow `ApiError` unchanged, and only wrap unknown errors.
|
|
||||||
|
|
||||||
#### R2-4. A coupon can increase the amount the customer pays ✓
|
|
||||||
- **Where:** `packages/shared/cart-pricing.ts:493-494`.
|
|
||||||
- **Cause:** `finalTotal = goodsSubtotal - discountTotal`, then `deliveryTotal = finalTotal < threshold ? charge : 0`. The free-delivery threshold is tested **after** discounts.
|
|
||||||
- **Example:** goods ₹500, threshold ₹500, delivery charge ₹60, coupon ₹50. Without the coupon the total is ₹500 (free delivery). With it, ₹450 is below the threshold, so the total becomes ₹510. Applying the coupon costs ₹10 more.
|
|
||||||
- **Note:** the user-ui cart (`cart-page.tsx:620-638`) and the server agree, because both apply the same rule, so the bill is consistent but wrong from the customer's point of view.
|
|
||||||
- **Fix:** compare the threshold against the pre-discount goods subtotal, or never charge more than the no-coupon total.
|
|
||||||
|
|
||||||
#### R2-5. Queue consumers are not idempotent and have no per-message handling ✓
|
|
||||||
- **Where:** `apps/backend/src/lib/queue-consumer.ts`.
|
|
||||||
- **Cause:** `handleNotifQueue`, `handleOrderPlacedQueue` and `handleOrderCancelledQueue` loop over `batch.messages`, await each, and never call `ack()` or `retry()`.
|
|
||||||
- **Effect:** any throw inside the loop fails the whole batch, so Cloudflare retries all messages, including the ones already processed. That means duplicate pushes and repeated order-placed side effects. A single poison message retries the entire batch until the retry limit.
|
|
||||||
- **Fix:** catch per message, `message.ack()` on success and `message.retry()` on failure, or make the handlers idempotent (for example, keyed on order id).
|
|
||||||
|
|
||||||
#### R2-6. `runBatched` promises a rollback that cannot happen ✓
|
|
||||||
- **Where:** `packages/db_helper_sqlite/src/lib/run-batched.ts`.
|
|
||||||
- **Cause:** its doc comment says "All chunks commit together, or the whole thing rolls back", but it runs inside `db.transaction`, which is the no-op from H1.
|
|
||||||
- **Effect:** callers relying on the documented atomicity (archive and order-item chunking) get partial writes on failure.
|
|
||||||
|
|
||||||
#### R2-7. Checkout delivery notes leak between orders and between users ✓
|
|
||||||
- **Where:** `apps/user-ui/src/store/checkoutStore.ts`, used at `cart-page.tsx:287` and `PaymentAndOrderComponent.tsx:56`.
|
|
||||||
- **Cause:** `userNotes` is never reset after a successful order or on logout (`AuthContext.clearSession` clears the token and the query cache only).
|
|
||||||
- **Effect on a shared device:** the next user's first order is pre-filled with the previous user's delivery instructions, and is submitted with them unless the field is edited. On the same account, every order carries the previous order's note.
|
|
||||||
|
|
||||||
#### R2-8. Cart quantity 0 is displayed as the stored quantity ✓
|
|
||||||
- **Where:** `apps/user-ui/components/cart-page.tsx:488-499, 357-372`.
|
|
||||||
- **Cause:** `quantities[item.id] || item.quantity` treats a pending 0 as "not set".
|
|
||||||
- **Effect:** when a decrement to 0 is pending or was cancelled, the cart bill and coupon maths use the stored quantity while the row shows 0. This compounds the round-1 Low item "Cancelling 'Remove item' resets the displayed quantity to 1 instead of the stored quantity".
|
|
||||||
|
|
||||||
### Low
|
|
||||||
|
|
||||||
#### R2-9. Production CORS allows local and LAN origins with credentials ✓
|
|
||||||
- **Where:** `apps/backend/src/app.ts:17-22`.
|
|
||||||
- **What's allowed:** `http://localhost:5174/4174/4175/4176` and `http://192.168.100.126:4175`, with `credentials: true`, in the production worker.
|
|
||||||
- **Impact:** a process listening on the victim's machine at one of those ports can read authenticated cross-origin responses using the web session cookie. Unlikely, but it should be gated on `NODE_ENV`.
|
|
||||||
|
|
||||||
#### R2-10. `user.savePushToken` is a public procedure ✓
|
|
||||||
- **Where:** `apps/backend/src/trpc/apis/user-apis/apis/user.ts:73`.
|
|
||||||
- **Intent:** deliberately public so that signed-out devices can register a token, and the region comes from the address.
|
|
||||||
- **Risk:** an anonymous caller can register or reassign arbitrary Expo tokens and region ids. Worth rate-limiting, or requiring a signed-out device id.
|
|
||||||
|
|
||||||
#### R2-11. The flash cron comment is wrong (the logic is not) ✓
|
|
||||||
- **Where:** `apps/backend/src/lib/flash-delivery-cron.ts:8-9`.
|
|
||||||
- **Details:** `0 16 * * *` is 21:30 IST, which matches its "9:30 PM IST" comment. `0 1 * * *` is 06:30 IST, but the comment says "6:30 PM IST". That is a sign error in a comment only: flash turns on at 06:30 and off at 21:30.
|
|
||||||
- **Also:** the toggle calls `computeConstants()` and `refreshGenKv()`, so clients do receive the new bound setting.
|
|
||||||
|
|
||||||
#### R2-12. Customer-reachable admin reads confirmed ✓
|
|
||||||
- `admin.vendorSnippets.getAll` and `admin.staffUser.getStaff` fully succeed for a customer token, since they never touch `ctx.staffUser`. The other admin reads fail with a 500 (TypeError) rather than a 401, as documented in `AUTH-03`.
|
|
||||||
- **Fix:** route all of them through `staffProcedure`.
|
|
||||||
|
|
||||||
### Verified as correct (so these are not re-reported later)
|
|
||||||
- **Region scoping is sound.** A script check over every exported helper in `packages/db_helper_sqlite/src/{admin,user,superadmin}-apis`, `stores` and `lib` found that every function that accepts `regionId` uses it in its query.
|
|
||||||
- **User ownership is sound.** Every helper that accepts `userId` uses it. Address, order and complaint reads are properly scoped (the complaint *write* gap is listed separately).
|
|
||||||
- **Order money maths is server-authoritative.** Prices come from the database. The free-delivery threshold, coupon stacking, sub-order splitting and the single delivery charge on the primary sub-order all behave consistently, and the shared helper uses the same ordering on client and server.
|
|
||||||
- **Slot rules are enforced on the server.** Existence, region, active flag, freeze time, delivery time and SKU membership are all checked in `placeOrder` for scheduled orders. Flash is re-checked against the bound setting.
|
|
||||||
- **Cron wiring covers all three schedules.** Archive at `30 20`, flash off at `0 16`, flash on at `0 1`.
|
|
||||||
- **API tests target `localhost:8787` by default**, so they do not point at production.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Suggested order of work
|
|
||||||
|
|
||||||
1. **Containment (do first, regardless of code fixes)**
|
|
||||||
- Verify and change the production superadmin password, and add a way to rotate it.
|
|
||||||
- Stop tracking the build artifacts (APKs, `.wrangler` state, `.expo`, `web-ui/.output`); they are repo bloat rather than a secret risk.
|
|
||||||
- Give dev its own D1 database, and fix or delete `reset-remote-db.sh`.
|
|
||||||
2. **Authorization**
|
|
||||||
- Add a `staffProcedure` gate to the whole admin router (C2).
|
|
||||||
- Fix the suspension check in `app.ts` (H3).
|
|
||||||
- Make `updateOrderItemPackaging` authenticated (H4).
|
|
||||||
- Then rewrite `AUTH-03/04`, `HARNESS-13` and `AUTH-11` so they assert the fixed behaviour (R2-1).
|
|
||||||
3. **Data integrity**
|
|
||||||
- Replace `db.transaction` with `db.batch` where atomicity is claimed (H1, R2-6).
|
|
||||||
- Add an atomic guard for coupon usage (H2).
|
|
||||||
4. **Slot correctness**
|
|
||||||
- Filter on `freezeTime` in the cart, `useProductSlotIdentifier`, `floating-cart-bar` and `getAllSlotsWithProductsForCache` (H8).
|
|
||||||
- Persist the user's slot choice in the cart (H9, H12).
|
|
||||||
5. **Admin data-loss bugs**
|
|
||||||
- Out-of-stock flags and images on product edit (H14, H15).
|
|
||||||
- Slot snippet editing (H16).
|
|
||||||
- Delivery sequence save-after-switch (H17).
|
|
||||||
6. **web-ui parity**
|
|
||||||
- Cart removal (H10).
|
|
||||||
- Flash gate (H11).
|
|
||||||
- Checkout filtering (H13).
|
|
||||||
- Logout cache and address invalidation.
|
|
||||||
- Add the missing web test coverage (R2-2).
|
|
||||||
|
|
||||||
## Coverage notes
|
|
||||||
|
|
||||||
- Every app and package was read in round 1: backend (auth, business logic, jobs), `user-ui`, `web-ui`, `admin-ui`, `admin-web`, `superadmin-ui`, `fallback-ui`, `shared`, `ui`, `web-components`, schema and migrations, and infra.
|
|
||||||
- Round 2 added a full authorization sweep, the order/coupon/slot code paths, jobs and queues, and the cart pricing helper.
|
|
||||||
- **Less deeply reviewed:** `superadmin-ui` beyond the auth-context issue, `fallback-ui`, `packages/migrator`, and the individual `packages/ui` components. These had a first-pass read only, so treat their sections as non-exhaustive.
|
|
||||||
- The abandoned `packages/db_helper_postgres` was excluded by project rule.
|
|
||||||
|
|
@ -336,7 +336,6 @@ availability ${assetsDomain}regions/${regionId}/av-${availability_version_n
|
||||||
| CACHE-23 | edge | missing assets domain/cache key env | payload null/empty; cache tests should fail with actionable message |
|
| CACHE-23 | edge | missing assets domain/cache key env | payload null/empty; cache tests should fail with actionable message |
|
||||||
| CACHE-24 | edge | bound deleted and recreated | old KV key removed; new bound does not serve stale payload |
|
| CACHE-24 | edge | bound deleted and recreated | old KV key removed; new bound does not serve stale payload |
|
||||||
| CACHE-115 | happy | `essentialUrls` in API + KV | products/stores/banners/essential-consts under the cache key; availability/slots outside it; store template substitutes |
|
| CACHE-115 | happy | `essentialUrls` in API + KV | products/stores/banners/essential-consts under the cache key; availability/slots outside it; store template substitutes |
|
||||||
| CACHE-117 | edge | `updatePrompt` switches | object `{isEnabled, isClosable}`, computed per request (not in the cached payload); `isEnabled:false` suppresses the user-ui update dialog, `isClosable` adds a "Later" dismiss |
|
|
||||||
|
|
||||||
### 4.2 products.json
|
### 4.2 products.json
|
||||||
|
|
||||||
|
|
|
||||||
File diff suppressed because one or more lines are too long
|
|
@ -3,11 +3,6 @@ set -euo pipefail
|
||||||
|
|
||||||
ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
|
ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
DUMP_FILE="$ROOT_DIR/dumps/latest.sql"
|
DUMP_FILE="$ROOT_DIR/dumps/latest.sql"
|
||||||
# Split files live under .wrangler (gitignored) so a pull never adds untracked
|
|
||||||
# artefacts next to the tracked dumps.
|
|
||||||
SPLIT_DIR="$ROOT_DIR/.wrangler/pull"
|
|
||||||
SCHEMA_FILE="$SPLIT_DIR/schema.sql"
|
|
||||||
DATA_FILE="$SPLIT_DIR/data.sql"
|
|
||||||
|
|
||||||
if [ "${1:-}" = "--dev" ]; then
|
if [ "${1:-}" = "--dev" ]; then
|
||||||
WRANGLER_CONFIG="$ROOT_DIR/wrangler.dev.toml"
|
WRANGLER_CONFIG="$ROOT_DIR/wrangler.dev.toml"
|
||||||
|
|
@ -27,40 +22,6 @@ if [ ! -f "$WRANGLER_CONFIG" ]; then
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
mkdir -p "$SPLIT_DIR"
|
wrangler d1 execute "$DB_NAME" --local --file "$DUMP_FILE" --config "$WRANGLER_CONFIG"
|
||||||
|
|
||||||
# `wrangler d1 export` emits tables in sqlite_master rowid order (the order they
|
|
||||||
# were historically created), so a table can be created and filled before the
|
|
||||||
# parent it references exists — e.g. `notif_creds`/`unlogged_user_tokens` ->
|
|
||||||
# `regions`, or `product_skus` -> `product_info` after the SKU-split rebuild.
|
|
||||||
#
|
|
||||||
# Local D1 pins `foreign_keys=ON` and runs the whole file as one transaction, so
|
|
||||||
# neither `PRAGMA foreign_keys=OFF` (a no-op) nor the dump's own
|
|
||||||
# `defer_foreign_keys` avoids `no such table: main.<parent>`.
|
|
||||||
#
|
|
||||||
# `CREATE TABLE` is allowed to reference a table that does not exist yet (FKs are
|
|
||||||
# resolved at DML time), so replaying every CREATE first and every INSERT second
|
|
||||||
# removes the "no such table" failure. See wrangler-commands.md.
|
|
||||||
#
|
|
||||||
# The dump's row order is not FK-safe either — child rows can precede their
|
|
||||||
# parent rows (e.g. `product_skus` before `product_info`). D1 enforces FKs per
|
|
||||||
# statement, so the data pass runs with deferred enforcement: every row is
|
|
||||||
# checked once at COMMIT, by which point the whole dump is loaded. (Verified:
|
|
||||||
# `PRAGMA foreign_key_check` on the imported DB reports no violations.)
|
|
||||||
awk -v schema="$SCHEMA_FILE" -v data="$DATA_FILE" '
|
|
||||||
BEGIN { print "PRAGMA defer_foreign_keys=TRUE;" > data }
|
|
||||||
/^CREATE/ { in_create = 1 }
|
|
||||||
in_create {
|
|
||||||
print > schema
|
|
||||||
# Multi-line CREATE TABLE blocks end with a line that is just `);`.
|
|
||||||
if ($0 ~ /\);[[:space:]]*$/) in_create = 0
|
|
||||||
next
|
|
||||||
}
|
|
||||||
/^PRAGMA/ { print > schema; next }
|
|
||||||
{ print > data }
|
|
||||||
' "$DUMP_FILE"
|
|
||||||
|
|
||||||
wrangler d1 execute "$DB_NAME" --local --file "$SCHEMA_FILE" --config "$WRANGLER_CONFIG"
|
|
||||||
wrangler d1 execute "$DB_NAME" --local --file "$DATA_FILE" --config "$WRANGLER_CONFIG"
|
|
||||||
|
|
||||||
echo "Local D1 database populated from $DUMP_FILE"
|
echo "Local D1 database populated from $DUMP_FILE"
|
||||||
|
|
|
||||||
|
|
@ -269,6 +269,7 @@ export const commonApiRouter = router({
|
||||||
.input(z.object({ boundId: z.number().int().positive().optional() }).optional())
|
.input(z.object({ boundId: z.number().int().positive().optional() }).optional())
|
||||||
.query(async ({ ctx, input }) => {
|
.query(async ({ ctx, input }) => {
|
||||||
const boundId = input?.boundId ?? 1
|
const boundId = input?.boundId ?? 1
|
||||||
|
console.log({ boundId })
|
||||||
const requestUrl = ctx.req.url
|
const requestUrl = ctx.req.url
|
||||||
const host = new URL(requestUrl).host
|
const host = new URL(requestUrl).host
|
||||||
const updateNotice = `<div style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%;">
|
const updateNotice = `<div style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%;">
|
||||||
|
|
@ -277,24 +278,13 @@ export const commonApiRouter = router({
|
||||||
</div>`
|
</div>`
|
||||||
|
|
||||||
const response = await readEssentialConstsFromKv(boundId);
|
const response = await readEssentialConstsFromKv(boundId);
|
||||||
// One switch drives every update surface: the BottomDialog in UpdateChecker,
|
const shouldShowNotice = host.includes('raw') || host.includes('mf')
|
||||||
// the store-version dialog in HealthTestWrapper, and the legacy host-gated
|
|
||||||
// WebView notice in WebViewWrapper. `isEnabled: false` means no surface
|
|
||||||
// ever asks the user to restart, even when the build is behind.
|
|
||||||
// `isClosable: true` adds a "Later" escape hatch where the surface offers
|
|
||||||
// one (backdrop/back for the bottom sheets, the close button for the WebView).
|
|
||||||
const updatePrompt = {
|
|
||||||
isEnabled: true,
|
|
||||||
isClosable: false,
|
|
||||||
}
|
|
||||||
const shouldShowNotice =
|
|
||||||
updatePrompt.isEnabled && (host.includes('raw') || host.includes('mf'))
|
|
||||||
|
|
||||||
|
console.log('essentialConsts request', { host, url: requestUrl, ...response })
|
||||||
return {
|
return {
|
||||||
...response,
|
...response,
|
||||||
webviewHtml: shouldShowNotice ? updateNotice : null,
|
webviewHtml: shouldShowNotice ? updateNotice : null,
|
||||||
isWebviewClosable: shouldShowNotice ? updatePrompt.isClosable : true,
|
isWebviewClosable: shouldShowNotice ? false : true
|
||||||
updatePrompt,
|
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -153,16 +153,6 @@ describe('common.essentialConsts shape (CACHE-01..05)', () => {
|
||||||
const consts = await getEssentialConsts(TEST_BOUND_ID)
|
const consts = await getEssentialConsts(TEST_BOUND_ID)
|
||||||
expect(typeof consts.isFlashDeliveryEnabled).toBe('boolean')
|
expect(typeof consts.isFlashDeliveryEnabled).toBe('boolean')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('CACHE-117: updatePrompt carries the enabled/closable switches', async () => {
|
|
||||||
// Computed per request in the router (not part of the cached payload), so a
|
|
||||||
// flip is a one-line change plus deploy. Assert the shape, not the values, so
|
|
||||||
// toggling the switches does not churn this test.
|
|
||||||
const consts = await getEssentialConsts(TEST_BOUND_ID)
|
|
||||||
expect(typeof consts.updatePrompt).toBe('object')
|
|
||||||
expect(typeof consts.updatePrompt?.isEnabled).toBe('boolean')
|
|
||||||
expect(typeof consts.updatePrompt?.isClosable).toBe('boolean')
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('common.essentialConsts published URLs (CACHE-115)', () => {
|
describe('common.essentialConsts published URLs (CACHE-115)', () => {
|
||||||
|
|
|
||||||
|
|
@ -38,7 +38,6 @@ export interface EssentialConsts {
|
||||||
essentialUrls?: Record<string, string>
|
essentialUrls?: Record<string, string>
|
||||||
webviewHtml?: string | null
|
webviewHtml?: string | null
|
||||||
isWebviewClosable?: boolean
|
isWebviewClosable?: boolean
|
||||||
updatePrompt?: { isEnabled: boolean; isClosable: boolean }
|
|
||||||
[key: string]: unknown
|
[key: string]: unknown
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -42,24 +42,15 @@ The only real fix is **ordering** the tables.
|
||||||
For every `REFERENCES x(...)`, confirm the `CREATE TABLE "x"` line appears
|
For every `REFERENCES x(...)`, confirm the `CREATE TABLE "x"` line appears
|
||||||
BEFORE the referencing table's `CREATE TABLE`.
|
BEFORE the referencing table's `CREATE TABLE`.
|
||||||
|
|
||||||
## How it is fixed now (automated)
|
## How to hand-fix
|
||||||
|
|
||||||
`scripts/populate_localdb.sh` no longer replays the dump as one file. It splits
|
Cut the parent table's block (`CREATE TABLE ...` + all its `INSERT ...` lines)
|
||||||
it into `.wrangler/pull/schema.sql` (every `CREATE` / `PRAGMA`) and
|
and paste it ABOVE the child table's block. Then verify it loads cleanly:
|
||||||
`.wrangler/pull/data.sql` (the `INSERT`s), then applies schema first and data
|
|
||||||
second. `CREATE TABLE` may reference a table that does not exist yet, so the
|
|
||||||
schema pass is order-independent and the data pass then has every parent.
|
|
||||||
|
|
||||||
`bun run pull_db` and `bun run pull_dev_db` stay single commands; the split files
|
|
||||||
are gitignored under `.wrangler/`.
|
|
||||||
|
|
||||||
## Hand verification
|
|
||||||
|
|
||||||
To check a dump yourself:
|
|
||||||
|
|
||||||
sqlite3 :memory: "PRAGMA foreign_keys=ON; BEGIN; .read dumps/<dump>.sql; COMMIT;"
|
sqlite3 :memory: "PRAGMA foreign_keys=ON; BEGIN; .read dumps/<dump>.sql; COMMIT;"
|
||||||
|
|
||||||
This should exit 0 with no error.
|
This should exit 0 with no error. (Example already applied to `latest_1.sql` and
|
||||||
|
`local_8_aug.sql`: `product_info` was moved above `product_skus`.)
|
||||||
|
|
||||||
## When to re-check
|
## When to re-check
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -28,7 +28,7 @@ Use these names in the cases below so the expected values stay consistent.
|
||||||
|
|
||||||
| Fixture | Value | Used by |
|
| Fixture | Value | Used by |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `CONSTS` | `freeDeliveryThreshold: 249`, `deliveryCharge: 15`, `flashFreeDeliveryThreshold: 199`, `flashDeliveryCharge: 25`, `isFlashDeliveryEnabled: true`, `boundId: 7`, `supportMobile: '8688182552'`, `supportEmail: 'support@freshyo.in'`, `versionNum: '1.2.0'`, `internalAppVersion: 2`, `updatePrompt: { isEnabled: true, isClosable: false }` | home, cart, checkout, wrappers |
|
| `CONSTS` | `freeDeliveryThreshold: 249`, `deliveryCharge: 15`, `flashFreeDeliveryThreshold: 199`, `flashDeliveryCharge: 25`, `isFlashDeliveryEnabled: true`, `boundId: 7`, `supportMobile: '8688182552'`, `supportEmail: 'support@freshyo.in'`, `versionNum: '1.2.0'`, `internalAppVersion: 2` | home, cart, checkout, wrappers |
|
||||||
| `CONSTS_FLASH_OFF` | `CONSTS` with `isFlashDeliveryEnabled: false` | flash gate, product detail |
|
| `CONSTS_FLASH_OFF` | `CONSTS` with `isFlashDeliveryEnabled: false` | flash gate, product detail |
|
||||||
| `P_CHICKEN` | id `2`, name `Chicken Breast`, price `215`, marketPrice `220`, unitNotation `500g`, incrementStep `1`, storeId `1`, images `['chicken.jpg']` | home, cart, store, search |
|
| `P_CHICKEN` | id `2`, name `Chicken Breast`, price `215`, marketPrice `220`, unitNotation `500g`, incrementStep `1`, storeId `1`, images `['chicken.jpg']` | home, cart, store, search |
|
||||||
| `P_CUCUMBER` | id `5`, name `Cucumber`, price `15`, marketPrice `20`, unitNotation `500g`, storeId `1` | home, cart, store |
|
| `P_CUCUMBER` | id `5`, name `Cucumber`, price `15`, marketPrice `20`, unitNotation `500g`, storeId `1` | home, cart, store |
|
||||||
|
|
@ -120,7 +120,7 @@ Use these names in the cases below so the expected values stay consistent.
|
||||||
| ROOT-02 | happy | `useFonts` returns `[true]` | `app-root`, QueryClient, tRPC provider and `Stack` are mounted |
|
| ROOT-02 | happy | `useFonts` returns `[true]` | `app-root`, QueryClient, tRPC provider and `Stack` are mounted |
|
||||||
| ROOT-03 | edge | health check is pending | children still render; no error screen |
|
| ROOT-03 | edge | health check is pending | children still render; no error screen |
|
||||||
| ROOT-04 | error | `common.healthCheck` rejects | shows “Service Unavailable”; retry calls `healthCheck` again |
|
| ROOT-04 | error | `common.healthCheck` rejects | shows “Service Unavailable”; retry calls `healthCheck` again |
|
||||||
| ROOT-05 | edge | `HealthTestWrapper` backend version `1.3.0`, local `1.2.0`, iOS URL set | “Update Available” dialog (requires `updatePrompt.isEnabled`); tapping opens the App Store URL |
|
| ROOT-05 | edge | `HealthTestWrapper` backend version `1.3.0`, local `1.2.0`, iOS URL set | “Update Available” dialog; tapping opens the App Store URL |
|
||||||
| ROOT-06 | edge | Android and `playStoreUrl` set | update dialog opens the Play Store URL |
|
| ROOT-06 | edge | Android and `playStoreUrl` set | update dialog opens the Play Store URL |
|
||||||
| ROOT-07 | edge | versions equal or local newer | no update dialog |
|
| ROOT-07 | edge | versions equal or local newer | no update dialog |
|
||||||
| ROOT-08 | error | app version malformed or backend version malformed | no dialog, no crash |
|
| ROOT-08 | error | app version malformed or backend version malformed | no dialog, no crash |
|
||||||
|
|
@ -130,13 +130,8 @@ Use these names in the cases below so the expected values stay consistent.
|
||||||
| ROOT-12 | happy | `webviewHtml` absent | children render |
|
| ROOT-12 | happy | `webviewHtml` absent | children render |
|
||||||
| ROOT-13 | edge | `webviewHtml` present, not closable | WebView renders and children are hidden |
|
| ROOT-13 | edge | `webviewHtml` present, not closable | WebView renders and children are hidden |
|
||||||
| ROOT-14 | edge | closable WebView | close button hides WebView and shows children |
|
| ROOT-14 | edge | closable WebView | close button hides WebView and shows children |
|
||||||
| ROOT-16 | edge | remote internal version ahead | bottom dialog shown once (no Later); Update & Restart calls `fetchUpdateAsync` then `reloadAsync` |
|
| ROOT-16 | edge | remote internal version ahead | alert shown once; Update & Restart calls `fetchUpdateAsync` then `reloadAsync` |
|
||||||
| ROOT-17 | error | update fetch/reload rejects | dialog stays up/does not crash |
|
| ROOT-17 | error | update fetch/reload rejects | alert stays/does not crash |
|
||||||
| ROOT-30 | edge | backend `updatePrompt.isEnabled:false` with version ahead | no alert; no update fetch |
|
|
||||||
| ROOT-31 | edge | `isEnabled:true, isClosable:true` | dialog with Later + Update & Restart; Later dismisses and never fetches |
|
|
||||||
| ROOT-32 | edge | stale persisted snapshot with `isEnabled:true`, query pending | no dialog (placeholder data is ignored) |
|
|
||||||
| ROOT-33 | edge | `versionNum` ahead + `updatePrompt.isEnabled:false` | no store-version dialog |
|
|
||||||
| ROOT-34 | edge | `versionNum` ahead + `isClosable:true` | Later dismisses the dialog; store not opened |
|
|
||||||
| ROOT-18 | happy | back press on home with empty stack | `Exit App` alert; Exit calls `BackHandler.exitApp`; returns `true` |
|
| ROOT-18 | happy | back press on home with empty stack | `Exit App` alert; Exit calls `BackHandler.exitApp`; returns `true` |
|
||||||
| ROOT-19 | edge | back press on non-home route | returns `false`; no alert |
|
| ROOT-19 | edge | back press on non-home route | returns `false`; no alert |
|
||||||
| ROOT-20 | edge | back press while stack can go back | returns `false` |
|
| ROOT-20 | edge | back press while stack can go back | returns `false` |
|
||||||
|
|
|
||||||
|
|
@ -9,12 +9,9 @@ import type { ReactParentComponent } from '@packages/shared';
|
||||||
|
|
||||||
const HealthTestWrapper: React.FC<ReactParentComponent> = ({ children }) => {
|
const HealthTestWrapper: React.FC<ReactParentComponent> = ({ children }) => {
|
||||||
const { data, isLoading, error, refetch } = trpc.common.healthCheck.useQuery();
|
const { data, isLoading, error, refetch } = trpc.common.healthCheck.useQuery();
|
||||||
const { data: backendConsts, isPlaceholderData } = useGetEssentialConsts();
|
const { data: backendConsts } = useGetEssentialConsts();
|
||||||
|
|
||||||
const versionFromBackend = backendConsts?.versionNum;
|
const versionFromBackend = backendConsts?.versionNum;
|
||||||
const updatePrompt = backendConsts?.updatePrompt;
|
|
||||||
const isUpdatePromptEnabled = updatePrompt?.isEnabled === true;
|
|
||||||
const isUpdatePromptClosable = updatePrompt?.isClosable === true;
|
|
||||||
|
|
||||||
const appUrl = Platform.OS === 'ios'
|
const appUrl = Platform.OS === 'ios'
|
||||||
? backendConsts?.appStoreUrl
|
? backendConsts?.appStoreUrl
|
||||||
|
|
@ -24,12 +21,6 @@ const HealthTestWrapper: React.FC<ReactParentComponent> = ({ children }) => {
|
||||||
|
|
||||||
// Version comparison logic
|
// Version comparison logic
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Same backend switch as UpdateChecker: with the prompt disabled — or with
|
|
||||||
// only the persisted snapshot in hand — this store-version gate must stay
|
|
||||||
// silent. Otherwise it raises a second, non-dismissable update dialog.
|
|
||||||
if (isPlaceholderData) return;
|
|
||||||
if (!isUpdatePromptEnabled) return;
|
|
||||||
|
|
||||||
const version = Constants.expoConfig?.version;
|
const version = Constants.expoConfig?.version;
|
||||||
if (!version || !versionFromBackend) return;
|
if (!version || !versionFromBackend) return;
|
||||||
|
|
||||||
|
|
@ -56,7 +47,7 @@ const HealthTestWrapper: React.FC<ReactParentComponent> = ({ children }) => {
|
||||||
if (needsUpdate) {
|
if (needsUpdate) {
|
||||||
setShowUpdateDialog(true);
|
setShowUpdateDialog(true);
|
||||||
}
|
}
|
||||||
}, [versionFromBackend, isPlaceholderData, isUpdatePromptEnabled]);
|
}, [versionFromBackend]);
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
return (
|
return (
|
||||||
|
|
@ -83,11 +74,7 @@ const HealthTestWrapper: React.FC<ReactParentComponent> = ({ children }) => {
|
||||||
<>
|
<>
|
||||||
{children}
|
{children}
|
||||||
{showUpdateDialog && appUrl && (
|
{showUpdateDialog && appUrl && (
|
||||||
<BottomDialog
|
<BottomDialog open={showUpdateDialog} onClose={() => setShowUpdateDialog(false)} enableDismiss={false}>
|
||||||
open={showUpdateDialog}
|
|
||||||
onClose={() => setShowUpdateDialog(false)}
|
|
||||||
enableDismiss={isUpdatePromptClosable}
|
|
||||||
>
|
|
||||||
<View style={{ padding: 20 }}>
|
<View style={{ padding: 20 }}>
|
||||||
<MyText style={{ fontSize: 18, fontWeight: 'bold', marginBottom: 16 }}>
|
<MyText style={{ fontSize: 18, fontWeight: 'bold', marginBottom: 16 }}>
|
||||||
Update Available
|
Update Available
|
||||||
|
|
@ -95,15 +82,6 @@ const HealthTestWrapper: React.FC<ReactParentComponent> = ({ children }) => {
|
||||||
<MyText style={{ marginBottom: 24 }}>
|
<MyText style={{ marginBottom: 24 }}>
|
||||||
A new version ({versionFromBackend}) is available. Your current version is {Constants.expoConfig?.version}. Please update to continue using the app.
|
A new version ({versionFromBackend}) is available. Your current version is {Constants.expoConfig?.version}. Please update to continue using the app.
|
||||||
</MyText>
|
</MyText>
|
||||||
{isUpdatePromptClosable && (
|
|
||||||
<MyTouchableOpacity
|
|
||||||
testID="health-update-later"
|
|
||||||
onPress={() => setShowUpdateDialog(false)}
|
|
||||||
style={tw`py-3 items-center mb-2`}
|
|
||||||
>
|
|
||||||
<MyText style={tw`text-gray-600 font-bold`}>Later</MyText>
|
|
||||||
</MyTouchableOpacity>
|
|
||||||
)}
|
|
||||||
<MyTouchableOpacity
|
<MyTouchableOpacity
|
||||||
onPress={() => {
|
onPress={() => {
|
||||||
if (appUrl) {
|
if (appUrl) {
|
||||||
|
|
|
||||||
|
|
@ -1,120 +1,52 @@
|
||||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
import React, { useEffect, useRef } from 'react';
|
||||||
import * as Updates from 'expo-updates';
|
import * as Updates from 'expo-updates';
|
||||||
import { useWindowDimensions, View } from 'react-native';
|
import { Alert } from 'react-native';
|
||||||
import { BottomDialog, MyButton, MyText, tw } from 'common-ui';
|
|
||||||
import type { ReactParentComponent } from '@packages/shared';
|
import type { ReactParentComponent } from '@packages/shared';
|
||||||
import { useGetEssentialConsts } from '@/src/hooks/prominent-api-hooks';
|
import { useGetEssentialConsts } from '@/src/hooks/prominent-api-hooks';
|
||||||
import constants from '@/src/constants';
|
import constants from '@/src/constants';
|
||||||
|
|
||||||
/** Share of the window height the prompt occupies. */
|
|
||||||
const DIALOG_HEIGHT_RATIO = 0.4;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Version gate for the user app.
|
* Version gate for the user app.
|
||||||
*
|
*
|
||||||
* Instead of expo-updates' own check, we compare the number shipped in this
|
* Instead of expo-updates' own check, we compare the number shipped in this
|
||||||
* build (`constants.INTERNAL_APP_VERSION`) with the backend's
|
* build (`constants.INTERNAL_APP_VERSION`) with the backend's
|
||||||
* `internalAppVersion` constant. When the backend is ahead, the update is
|
* `internalAppVersion` constant. When the backend is ahead, the update is
|
||||||
* fetched and the app reloads. Both the gate and its close behaviour come from
|
* fetched and the app reloads (blocking dialog, no "later").
|
||||||
* the backend's `updatePrompt` object (`isEnabled` / `isClosable`), so the
|
|
||||||
* prompt can be switched off — or made dismissable — without shipping a build.
|
|
||||||
*
|
|
||||||
* Rendered as the app's BottomDialog (not a native Alert) so it looks like the
|
|
||||||
* rest of the dialogs and can show an in-progress state while updating.
|
|
||||||
*/
|
*/
|
||||||
const UpdateChecker: React.FC<ReactParentComponent> = ({ children }) => {
|
const UpdateChecker: React.FC<ReactParentComponent> = ({ children }) => {
|
||||||
const { data, isPlaceholderData } = useGetEssentialConsts();
|
const { data } = useGetEssentialConsts();
|
||||||
const { height } = useWindowDimensions();
|
|
||||||
const [prompt, setPrompt] = useState<{ isClosable: boolean } | null>(null);
|
|
||||||
const [isUpdating, setIsUpdating] = useState(false);
|
|
||||||
const prompted = useRef(false);
|
const prompted = useRef(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (prompted.current) return;
|
if (prompted.current) return;
|
||||||
// The hook rehydrates the last persisted payload as placeholder data before
|
|
||||||
// the network call resolves. That snapshot can predate an `isEnabled: false`
|
|
||||||
// flip, so never decide from it.
|
|
||||||
if (isPlaceholderData) return;
|
|
||||||
|
|
||||||
const remoteVersion = data?.internalAppVersion;
|
const remoteVersion = data?.internalAppVersion;
|
||||||
if (typeof remoteVersion !== 'number') return;
|
if (typeof remoteVersion !== 'number') return;
|
||||||
const updatePrompt = data?.updatePrompt;
|
|
||||||
if (updatePrompt?.isEnabled !== true) return;
|
|
||||||
if (constants.INTERNAL_APP_VERSION >= remoteVersion) return;
|
if (constants.INTERNAL_APP_VERSION >= remoteVersion) return;
|
||||||
|
|
||||||
prompted.current = true;
|
prompted.current = true;
|
||||||
setPrompt({ isClosable: updatePrompt.isClosable === true });
|
|
||||||
}, [data, isPlaceholderData]);
|
|
||||||
|
|
||||||
const isClosable = prompt?.isClosable === true;
|
Alert.alert(
|
||||||
|
'Update available',
|
||||||
// Backdrop tap / Android back. A non-closable prompt is the hard gate, so it
|
'A new version of the app is available. Please restart to continue.',
|
||||||
// ignores both (`BottomDialog` also drops its dismiss handlers then).
|
[
|
||||||
const handleClose = useCallback(() => {
|
{
|
||||||
setPrompt((current) => (current?.isClosable ? null : current));
|
text: 'Update & Restart',
|
||||||
}, []);
|
onPress: async () => {
|
||||||
|
|
||||||
const applyUpdate = useCallback(async () => {
|
|
||||||
setIsUpdating(true);
|
|
||||||
try {
|
try {
|
||||||
await Updates.fetchUpdateAsync();
|
await Updates.fetchUpdateAsync();
|
||||||
await Updates.reloadAsync();
|
await Updates.reloadAsync();
|
||||||
} catch {
|
} catch {
|
||||||
// If the update cannot be applied, leave the app as-is.
|
// If the update cannot be applied, leave the app as-is.
|
||||||
} finally {
|
|
||||||
setIsUpdating(false);
|
|
||||||
}
|
}
|
||||||
}, []);
|
},
|
||||||
|
},
|
||||||
return (
|
],
|
||||||
<>
|
{ cancelable: false }
|
||||||
{children}
|
|
||||||
<BottomDialog
|
|
||||||
open={prompt !== null}
|
|
||||||
onClose={handleClose}
|
|
||||||
enableDismiss={isClosable}
|
|
||||||
>
|
|
||||||
<View
|
|
||||||
testID="update-dialog"
|
|
||||||
style={[tw`px-6`, { height: Math.round(height * DIALOG_HEIGHT_RATIO) }]}
|
|
||||||
>
|
|
||||||
<View style={tw`flex-1 justify-between pb-6`}>
|
|
||||||
<View>
|
|
||||||
<MyText style={tw`text-xl font-bold text-gray-900`}>
|
|
||||||
Update available
|
|
||||||
</MyText>
|
|
||||||
<MyText style={tw`text-sm text-gray-600 mt-2`}>
|
|
||||||
{isClosable
|
|
||||||
? 'A new version of the app is available. Update now, or continue and restart later.'
|
|
||||||
: 'A new version of the app is available. Please restart to continue.'}
|
|
||||||
</MyText>
|
|
||||||
</View>
|
|
||||||
|
|
||||||
<View>
|
|
||||||
{isClosable ? (
|
|
||||||
<MyButton
|
|
||||||
testID="update-later"
|
|
||||||
textContent="Later"
|
|
||||||
fillColor="gray3"
|
|
||||||
textColor="black2"
|
|
||||||
fullWidth
|
|
||||||
onPress={handleClose}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
<MyButton
|
|
||||||
testID="update-restart"
|
|
||||||
textContent={isUpdating ? 'Updating…' : 'Update & Restart'}
|
|
||||||
fullWidth
|
|
||||||
disabled={isUpdating}
|
|
||||||
onPress={applyUpdate}
|
|
||||||
style={isClosable ? tw`mt-2` : undefined}
|
|
||||||
/>
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
</BottomDialog>
|
|
||||||
</>
|
|
||||||
);
|
);
|
||||||
|
}, [data]);
|
||||||
|
|
||||||
|
return <>{children}</>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default UpdateChecker;
|
export default UpdateChecker;
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
/**
|
/**
|
||||||
* ROOT-01..ROOT-34 — the app shell (`app/_layout.tsx`) and the wrappers it
|
* ROOT-01..ROOT-29 — the app shell (`app/_layout.tsx`) and the wrappers it
|
||||||
* composes.
|
* composes.
|
||||||
*
|
*
|
||||||
* Rows that need the *whole* provider tree (fonts gate, health gate) mount
|
* Rows that need the *whole* provider tree (fonts gate, health gate) mount
|
||||||
|
|
@ -188,31 +188,6 @@ describe('app shell (ROOT-01..ROOT-29)', () => {
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
it('ROOT-33: a disabled update prompt silences the store-version dialog', async () => {
|
|
||||||
const view = renderHealth({
|
|
||||||
versionNum: '1.3.0',
|
|
||||||
updatePrompt: { isEnabled: false, isClosable: true },
|
|
||||||
})
|
|
||||||
|
|
||||||
await flush(3)
|
|
||||||
expect(view.queryByText('Update Available')).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('ROOT-34: a closable store-version dialog dismisses with Later', async () => {
|
|
||||||
const view = renderHealth({
|
|
||||||
versionNum: '1.3.0',
|
|
||||||
updatePrompt: { isEnabled: true, isClosable: true },
|
|
||||||
})
|
|
||||||
|
|
||||||
await waitFor(() => expect(view.getByText('Update Available')).toBeTruthy())
|
|
||||||
|
|
||||||
fireEvent.press(view.getByTestId('health-update-later'))
|
|
||||||
|
|
||||||
await flush()
|
|
||||||
expect(view.queryByText('Update Available')).toBeNull()
|
|
||||||
expect(Linking.openURL).not.toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('ROOT-09: a first-time user sees the welcome screen and Next stores the flag', async () => {
|
it('ROOT-09: a first-time user sees the welcome screen and Next stores the flag', async () => {
|
||||||
const view = render(
|
const view = render(
|
||||||
<FirstUserWrapper>
|
<FirstUserWrapper>
|
||||||
|
|
@ -306,18 +281,20 @@ describe('app shell (ROOT-01..ROOT-29)', () => {
|
||||||
expect(view.queryByTestId('webview')).toBeNull()
|
expect(view.queryByTestId('webview')).toBeNull()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('ROOT-16: a newer backend internal version shows the hard-gate dialog and updates', async () => {
|
it('ROOT-16: a newer backend internal version alerts once and updates', async () => {
|
||||||
|
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||||
|
renderUpdateChecker()
|
||||||
setProcedure('common.essentialConsts', {
|
setProcedure('common.essentialConsts', {
|
||||||
data: { ...CONSTS, internalAppVersion: 5 },
|
data: { ...CONSTS, internalAppVersion: 5 },
|
||||||
})
|
})
|
||||||
const view = renderUpdateChecker()
|
|
||||||
|
|
||||||
await waitFor(() => expect(view.getByTestId('update-dialog')).toBeTruthy())
|
await waitFor(() => expect(alertSpy).toHaveBeenCalledTimes(1))
|
||||||
// The fixture's prompt is the non-closable hard gate.
|
expect(alertSpy.mock.calls[0][0]).toBe('Update available')
|
||||||
expect(view.queryByTestId('update-later')).toBeNull()
|
|
||||||
|
|
||||||
|
const buttons = alertSpy.mock.calls[0][2] as any[]
|
||||||
|
const update = buttons.find((button) => button.text === 'Update & Restart')
|
||||||
await act(async () => {
|
await act(async () => {
|
||||||
fireEvent.press(view.getByTestId('update-restart'))
|
await update.onPress()
|
||||||
})
|
})
|
||||||
|
|
||||||
expect(Updates.fetchUpdateAsync).toHaveBeenCalledTimes(1)
|
expect(Updates.fetchUpdateAsync).toHaveBeenCalledTimes(1)
|
||||||
|
|
@ -328,74 +305,23 @@ describe('app shell (ROOT-01..ROOT-29)', () => {
|
||||||
})
|
})
|
||||||
|
|
||||||
it('ROOT-17: an update fetch failure does not crash or reload', async () => {
|
it('ROOT-17: an update fetch failure does not crash or reload', async () => {
|
||||||
|
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||||
;(Updates.fetchUpdateAsync as jest.Mock).mockRejectedValueOnce(new Error('no update'))
|
;(Updates.fetchUpdateAsync as jest.Mock).mockRejectedValueOnce(new Error('no update'))
|
||||||
|
renderUpdateChecker()
|
||||||
setProcedure('common.essentialConsts', {
|
setProcedure('common.essentialConsts', {
|
||||||
data: { ...CONSTS, internalAppVersion: 5 },
|
data: { ...CONSTS, internalAppVersion: 5 },
|
||||||
})
|
})
|
||||||
const view = renderUpdateChecker()
|
|
||||||
|
|
||||||
await waitFor(() => expect(view.getByTestId('update-dialog')).toBeTruthy())
|
await waitFor(() => expect(alertSpy).toHaveBeenCalledTimes(1))
|
||||||
|
const update = (alertSpy.mock.calls[0][2] as any[]).find(
|
||||||
await act(async () => {
|
(button) => button.text === 'Update & Restart'
|
||||||
fireEvent.press(view.getByTestId('update-restart'))
|
|
||||||
})
|
|
||||||
|
|
||||||
expect(Updates.reloadAsync).not.toHaveBeenCalled()
|
|
||||||
// The gate stays up so the user can retry.
|
|
||||||
expect(view.getByTestId('update-dialog')).toBeTruthy()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('ROOT-30: a disabled backend flag suppresses the update prompt', async () => {
|
|
||||||
setProcedure('common.essentialConsts', {
|
|
||||||
data: { ...CONSTS, internalAppVersion: 5, updatePrompt: { isEnabled: false, isClosable: true } },
|
|
||||||
})
|
|
||||||
const view = renderUpdateChecker()
|
|
||||||
|
|
||||||
// Let the query resolve; the dialog must stay absent either way.
|
|
||||||
await flush(3)
|
|
||||||
expect(view.queryByTestId('update-dialog')).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('ROOT-31: a closable prompt offers "Later" and does not update', async () => {
|
|
||||||
setProcedure('common.essentialConsts', {
|
|
||||||
data: {
|
|
||||||
...CONSTS,
|
|
||||||
internalAppVersion: 5,
|
|
||||||
updatePrompt: { isEnabled: true, isClosable: true },
|
|
||||||
},
|
|
||||||
})
|
|
||||||
const view = renderUpdateChecker()
|
|
||||||
|
|
||||||
await waitFor(() => expect(view.getByTestId('update-dialog')).toBeTruthy())
|
|
||||||
expect(view.getByTestId('update-later')).toBeTruthy()
|
|
||||||
expect(view.getByText('Update & Restart')).toBeTruthy()
|
|
||||||
|
|
||||||
await act(async () => {
|
|
||||||
fireEvent.press(view.getByTestId('update-later'))
|
|
||||||
})
|
|
||||||
|
|
||||||
expect(view.queryByTestId('update-dialog')).toBeNull()
|
|
||||||
expect(Updates.fetchUpdateAsync).not.toHaveBeenCalled()
|
|
||||||
expect(Updates.reloadAsync).not.toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('ROOT-32: a stale persisted snapshot cannot trigger the prompt', async () => {
|
|
||||||
// The hook rehydrates this as placeholder data while the query is pending —
|
|
||||||
// it carries isEnabled:true from before the backend flipped it to false.
|
|
||||||
__set(
|
|
||||||
'essential_consts_b7',
|
|
||||||
JSON.stringify({
|
|
||||||
...CONSTS,
|
|
||||||
internalAppVersion: 5,
|
|
||||||
updatePrompt: { isEnabled: true, isClosable: false },
|
|
||||||
})
|
|
||||||
)
|
)
|
||||||
setProcedure('common.essentialConsts', { mode: 'pending' })
|
|
||||||
const view = renderUpdateChecker()
|
|
||||||
|
|
||||||
// Let the query resolve; the dialog must stay absent either way.
|
await act(async () => {
|
||||||
await flush(3)
|
await update.onPress()
|
||||||
expect(view.queryByTestId('update-dialog')).toBeNull()
|
})
|
||||||
|
|
||||||
|
expect(Updates.reloadAsync).not.toHaveBeenCalled()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('ROOT-18: back on home with an empty stack asks to exit and exits', () => {
|
it('ROOT-18: back on home with an empty stack asks to exit and exits', () => {
|
||||||
|
|
|
||||||
1
apps/user-ui/tests/fixtures/index.ts
vendored
1
apps/user-ui/tests/fixtures/index.ts
vendored
|
|
@ -66,7 +66,6 @@ export const CONSTS = {
|
||||||
welcomeMessage: 'Welcome to Freshyo',
|
welcomeMessage: 'Welcome to Freshyo',
|
||||||
versionNum: '1.2.0',
|
versionNum: '1.2.0',
|
||||||
internalAppVersion: 2,
|
internalAppVersion: 2,
|
||||||
updatePrompt: { isEnabled: true, isClosable: false },
|
|
||||||
appStoreUrl: 'https://apps.apple.com/app/freshyo/id123456',
|
appStoreUrl: 'https://apps.apple.com/app/freshyo/id123456',
|
||||||
playStoreUrl: 'https://play.google.com/store/apps/details?id=com.freshyotrial.app',
|
playStoreUrl: 'https://play.google.com/store/apps/details?id=com.freshyotrial.app',
|
||||||
webviewHtml: null,
|
webviewHtml: null,
|
||||||
|
|
|
||||||
231
change-log.txt
231
change-log.txt
|
|
@ -636,234 +636,3 @@ job itself.
|
||||||
--- apps/backend/wrangler.prod.toml
|
--- apps/backend/wrangler.prod.toml
|
||||||
-crons = ["0 16 * * *", "0 1 * * *", "30 20 * * *"]
|
-crons = ["0 16 * * *", "0 1 * * *", "30 20 * * *"]
|
||||||
+crons = ["0 15 * * *", "0 1 * * *", "30 20 * * *"]
|
+crons = ["0 15 * * *", "0 1 * * *", "30 20 * * *"]
|
||||||
|
|
||||||
[2026-11-05 22:40:37 IST] add a backend kill switch for the in-app update dialog.
|
|
||||||
|
|
||||||
The force-update dialog (apps/user-ui/components/UpdateChecker.tsx) is now gated
|
|
||||||
by `isUpdatePromptEnabled`, returned per request by `common.essentialConsts`.
|
|
||||||
It is a hardcoded literal in the router, deliberately NOT in the constants
|
|
||||||
tables or the per-bound KV cache, so flipping it is a one-line change plus a
|
|
||||||
deploy. Currently `false`: no prompt even when the build is behind
|
|
||||||
`internalAppVersion`. The client only prompts when the flag is explicitly
|
|
||||||
`true`, so an older payload or a persisted snapshot cannot flash the dialog.
|
|
||||||
|
|
||||||
--- apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
|
|
||||||
return {
|
|
||||||
...response,
|
|
||||||
webviewHtml: shouldShowNotice ? updateNotice : null,
|
|
||||||
isWebviewClosable: shouldShowNotice ? false : true,
|
|
||||||
+ // Kill switch for the in-app "Update available" dialog (UpdateChecker in
|
|
||||||
+ // apps/user-ui). Hardcoded on purpose and computed per request, so it can
|
|
||||||
+ // be flipped and deployed without touching the constants tables or waiting
|
|
||||||
+ // for the per-bound KV cache to rebuild: `false` means users are never
|
|
||||||
+ // asked to restart, even when their build is behind `internalAppVersion`.
|
|
||||||
+ isUpdatePromptEnabled: false,
|
|
||||||
};
|
|
||||||
--- apps/user-ui/components/UpdateChecker.tsx
|
|
||||||
const remoteVersion = data?.internalAppVersion;
|
|
||||||
if (typeof remoteVersion !== 'number') return;
|
|
||||||
+ // Backend kill switch: only prompt when the backend explicitly enables it.
|
|
||||||
+ // A missing field (older payload, or a persisted snapshot from before the
|
|
||||||
+ // flag existed) also suppresses the prompt, so a stale cache cannot flash
|
|
||||||
+ // the dialog before the fresh payload arrives.
|
|
||||||
+ if (data?.isUpdatePromptEnabled !== true) return;
|
|
||||||
if (constants.INTERNAL_APP_VERSION >= remoteVersion) return;
|
|
||||||
--- apps/user-ui/tests/fixtures/index.ts
|
|
||||||
internalAppVersion: 2,
|
|
||||||
+ isUpdatePromptEnabled: true,
|
|
||||||
--- apps/user-ui/tests/app/root-layout.test.tsx
|
|
||||||
+ it('ROOT-30: a disabled backend flag suppresses the update prompt', ...)
|
|
||||||
--- apps/backend/tests/helpers/cache.ts
|
|
||||||
webviewHtml?: string | null
|
|
||||||
isWebviewClosable?: boolean
|
|
||||||
+ isUpdatePromptEnabled?: boolean
|
|
||||||
--- apps/backend/tests/api/cache-consts.test.ts
|
|
||||||
+ it('CACHE-117: isUpdatePromptEnabled is a boolean', ...)
|
|
||||||
--- apps/user-ui/JEST-TEST-CASES.md, apps/backend/API-TEST-CASES.md
|
|
||||||
- CONSTS fixture row + ROOT-30 row; CACHE-117 row.
|
|
||||||
|
|
||||||
[2026-11-05 22:45:31 IST] the update-dialog flag becomes an object: enabled + closable.
|
|
||||||
|
|
||||||
`common.essentialConsts` now returns `updatePrompt: { isEnabled, isClosable }`
|
|
||||||
instead of the scalar `isUpdatePromptEnabled`. `isEnabled: false` still means the
|
|
||||||
dialog is never shown (the current state). When it is enabled, `isClosable: true`
|
|
||||||
renders a "Later" button and lets Android back/outside-tap dismiss the alert;
|
|
||||||
`isClosable: false` keeps the single-button hard gate. Still a hardcoded literal
|
|
||||||
computed per request (not in the per-bound KV cache), so flipping it is one line
|
|
||||||
plus a deploy.
|
|
||||||
|
|
||||||
--- apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
|
|
||||||
- // Kill switch for the in-app "Update available" dialog (UpdateChecker in
|
|
||||||
- // apps/user-ui). Hardcoded on purpose and computed per request, so it can
|
|
||||||
- // be flipped and deployed without touching the constants tables or waiting
|
|
||||||
- // for the per-bound KV cache to rebuild: `false` means users are never
|
|
||||||
- // asked to restart, even when their build is behind `internalAppVersion`.
|
|
||||||
- isUpdatePromptEnabled: false,
|
|
||||||
+ // Kill switch + close behaviour for the in-app "Update available" dialog
|
|
||||||
+ // (UpdateChecker in apps/user-ui). Hardcoded on purpose and computed per
|
|
||||||
+ // request, so it can be flipped and deployed without touching the
|
|
||||||
+ // constants tables or waiting for the per-bound KV cache to rebuild.
|
|
||||||
+ updatePrompt: {
|
|
||||||
+ isEnabled: false,
|
|
||||||
+ isClosable: true,
|
|
||||||
+ },
|
|
||||||
--- apps/user-ui/components/UpdateChecker.tsx
|
|
||||||
- if (data?.isUpdatePromptEnabled !== true) return;
|
|
||||||
+ const prompt = data?.updatePrompt;
|
|
||||||
+ if (prompt?.isEnabled !== true) return;
|
|
||||||
...
|
|
||||||
- Alert.alert('Update available', '...Please restart to continue.', [one button], { cancelable: false })
|
|
||||||
+ const isClosable = prompt?.isClosable === true;
|
|
||||||
+ Alert.alert(
|
|
||||||
+ 'Update available',
|
|
||||||
+ isClosable ? '... Update now, or continue and restart later.' : '... Please restart to continue.',
|
|
||||||
+ isClosable
|
|
||||||
+ ? [{ text: 'Later', style: 'cancel' }, { text: 'Update & Restart', onPress: applyUpdate }]
|
|
||||||
+ : [{ text: 'Update & Restart', onPress: applyUpdate }],
|
|
||||||
+ { cancelable: isClosable }
|
|
||||||
+ );
|
|
||||||
--- apps/user-ui/tests/fixtures/index.ts
|
|
||||||
- isUpdatePromptEnabled: true,
|
|
||||||
+ updatePrompt: { isEnabled: true, isClosable: false },
|
|
||||||
--- apps/user-ui/tests/app/root-layout.test.tsx
|
|
||||||
- ROOT-30 uses updatePrompt: { isEnabled: false, isClosable: false }
|
|
||||||
+ ROOT-31 (new): isClosable:true shows "Later", cancelable alert, no fetch on Later
|
|
||||||
--- apps/backend/tests/helpers/cache.ts
|
|
||||||
- isUpdatePromptEnabled?: boolean
|
|
||||||
+ updatePrompt?: { isEnabled: boolean; isClosable: boolean }
|
|
||||||
--- apps/backend/tests/api/cache-consts.test.ts
|
|
||||||
- CACHE-117 asserts typeof === 'boolean'
|
|
||||||
+ CACHE-117 asserts the updatePrompt object shape
|
|
||||||
--- apps/user-ui/JEST-TEST-CASES.md, apps/backend/API-TEST-CASES.md
|
|
||||||
- CONSTS fixture row, ROOT-30/ROOT-31 rows, CACHE-117 row.
|
|
||||||
|
|
||||||
[2026-11-05 23:14:54 IST] fix `bun run pull_db`: split the dump into schema + data before replaying.
|
|
||||||
|
|
||||||
`wrangler d1 export` writes tables in sqlite_master rowid (historical creation)
|
|
||||||
order, so a child table is created and populated before its parent exists
|
|
||||||
(`notif_creds`/`unlogged_user_tokens` -> `regions`, `product_skus` ->
|
|
||||||
`product_info`). Local D1 pins foreign_keys=ON and runs the file as one
|
|
||||||
transaction, so neither `PRAGMA foreign_keys=OFF` (a no-op, verified: the pragma
|
|
||||||
still reads 1) nor the dump's own `defer_foreign_keys` prevents
|
|
||||||
`no such table: main.regions`. `CREATE TABLE` may reference a missing parent, so
|
|
||||||
replaying every CREATE first and every INSERT second makes the import
|
|
||||||
order-independent.
|
|
||||||
|
|
||||||
`populate_localdb.sh` now splits dumps/latest.sql into .wrangler/pull/schema.sql
|
|
||||||
and .wrangler/pull/data.sql (gitignored by the existing `**/.wrangler/*` rule)
|
|
||||||
and executes them in that order. `package.json` is unchanged, so `bun run pull_db`
|
|
||||||
is still the one command (and `pull_dev_db` benefits from the same fix).
|
|
||||||
|
|
||||||
--- apps/backend/scripts/populate_localdb.sh
|
|
||||||
-wrangler d1 execute "$DB_NAME" --local --file "$DUMP_FILE" --config "$WRANGLER_CONFIG"
|
|
||||||
+mkdir -p "$SPLIT_DIR"
|
|
||||||
+# ... awk splitter: CREATE/PRAGMA -> schema.sql, everything else -> data.sql
|
|
||||||
+wrangler d1 execute "$DB_NAME" --local --file "$SCHEMA_FILE" --config "$WRANGLER_CONFIG"
|
|
||||||
+wrangler d1 execute "$DB_NAME" --local --file "$DATA_FILE" --config "$WRANGLER_CONFIG"
|
|
||||||
--- apps/backend/wrangler-commands.md
|
|
||||||
- "How to hand-fix" (cut/paste the parent block above the child) is now automated
|
|
||||||
+ by populate_localdb.sh; kept the way to verify a dump by hand.
|
|
||||||
|
|
||||||
Follow-up on the same change: the data pass also needs deferred FK checks.
|
|
||||||
The dump's row order is not FK-safe (child rows can precede their parent rows),
|
|
||||||
and D1 enforces FKs per statement, which surfaced as
|
|
||||||
`FOREIGN KEY constraint failed: SQLITE_CONSTRAINT` only after the schema split
|
|
||||||
was in place. populate_localdb.sh now writes `PRAGMA defer_foreign_keys=TRUE;`
|
|
||||||
at the top of .wrangler/pull/data.sql as well; enforcement then happens once at
|
|
||||||
COMMIT and `PRAGMA foreign_key_check` is clean on the imported DB.
|
|
||||||
|
|
||||||
[2026-11-05 23:22:25 IST] never fire the update prompt from the persisted snapshot.
|
|
||||||
|
|
||||||
useGetEssentialConsts rehydrates the last cached payload as React Query
|
|
||||||
`placeholderData` before the network call resolves, so on launch the effect can
|
|
||||||
see an older `updatePrompt.isEnabled: true` while the fresh (correct) `false`
|
|
||||||
arrives a moment later. The alert had already been raised by then and cannot be
|
|
||||||
dismissed programmatically. UpdateChecker now ignores placeholder data entirely
|
|
||||||
and only decides from the resolved response. Also removed a leftover debug
|
|
||||||
`console.log({ consts: data })`.
|
|
||||||
|
|
||||||
--- apps/user-ui/components/UpdateChecker.tsx
|
|
||||||
- const { data } = useGetEssentialConsts();
|
|
||||||
+ const { data, isPlaceholderData } = useGetEssentialConsts();
|
|
||||||
- console.log({consts: data})
|
|
||||||
useEffect(() => {
|
|
||||||
if (prompted.current) return;
|
|
||||||
+ // The hook rehydrates the last persisted payload as placeholder data before
|
|
||||||
+ // the network call resolves; that snapshot can predate an `isEnabled: false`
|
|
||||||
+ // flip, so never decide from it.
|
|
||||||
+ if (isPlaceholderData) return;
|
|
||||||
const remoteVersion = data?.internalAppVersion;
|
|
||||||
- }, [data]);
|
|
||||||
+ }, [data, isPlaceholderData]);
|
|
||||||
--- apps/user-ui/tests/app/root-layout.test.tsx
|
|
||||||
+ ROOT-32: a seeded stale snapshot (isEnabled:true) with a pending query shows no alert.
|
|
||||||
--- apps/user-ui/JEST-TEST-CASES.md
|
|
||||||
+ ROOT-32 row.
|
|
||||||
|
|
||||||
[2026-11-05 23:25:16 IST] the update prompt uses the app's BottomDialog at 40% height.
|
|
||||||
|
|
||||||
Replaced the native `Alert.alert` with `BottomDialog` (common-ui) sized to 40%
|
|
||||||
of the window height, so it matches the rest of the app (handle, slide-up,
|
|
||||||
scrollable body) and can carry real buttons. `enableDismiss` follows
|
|
||||||
`updatePrompt.isClosable` (backdrop tap + Android back only when closable);
|
|
||||||
the closable variant renders a "Later" button, the hard gate renders only
|
|
||||||
"Update & Restart". "Updating…" disables the button while fetch/reload runs.
|
|
||||||
|
|
||||||
--- apps/user-ui/components/UpdateChecker.tsx
|
|
||||||
-import { Alert } from 'react-native';
|
|
||||||
+import { useWindowDimensions, View } from 'react-native';
|
|
||||||
+import { BottomDialog, MyButton, MyText, tw } from 'common-ui';
|
|
||||||
- const prompted = useRef(false);
|
|
||||||
+ const [prompt, setPrompt] = useState<{ isClosable: boolean } | null>(null);
|
|
||||||
+ const [isUpdating, setIsUpdating] = useState(false);
|
|
||||||
- Alert.alert('Update available', message, [buttons], { cancelable: isClosable });
|
|
||||||
+ setPrompt({ isClosable: updatePrompt.isClosable === true });
|
|
||||||
+ ...
|
|
||||||
+ <BottomDialog open={prompt !== null} onClose={handleClose} enableDismiss={isClosable}>
|
|
||||||
+ <View testID="update-dialog" style={{ height: Math.round(height * 0.4) }}> ... </View>
|
|
||||||
+ </BottomDialog>
|
|
||||||
--- apps/user-ui/tests/app/root-layout.test.tsx
|
|
||||||
- ROOT-16/17/30/31/32 now assert the rendered dialog (testIDs update-dialog,
|
|
||||||
update-later, update-restart) instead of spying on Alert.alert.
|
|
||||||
--- apps/user-ui/JEST-TEST-CASES.md
|
|
||||||
- ROOT-16/17/31 wording updated from "alert" to "bottom dialog".
|
|
||||||
|
|
||||||
[2026-11-05 23:30:12 IST] every update prompt now honours `updatePrompt.isEnabled`.
|
|
||||||
|
|
||||||
The dialog still shown with `isEnabled: false` was not UpdateChecker: it was
|
|
||||||
HealthTestWrapper's store-version gate (`versionNum` vs `Constants.expoConfig
|
|
||||||
.version`, rendered `enableDismiss={false}` so it cannot be closed). That gate
|
|
||||||
never read the new switch. WebViewWrapper was a third surface (host-gated
|
|
||||||
`webviewHtml`) that also ignored it.
|
|
||||||
|
|
||||||
--- apps/user-ui/components/HealthTestWrapper.tsx
|
|
||||||
- const { data: backendConsts } = useGetEssentialConsts();
|
|
||||||
+ const { data: backendConsts, isPlaceholderData } = useGetEssentialConsts();
|
|
||||||
+ const updatePrompt = backendConsts?.updatePrompt;
|
|
||||||
+ const isUpdatePromptEnabled = updatePrompt?.isEnabled === true;
|
|
||||||
+ const isUpdatePromptClosable = updatePrompt?.isClosable === true;
|
|
||||||
useEffect(() => {
|
|
||||||
+ // Same switch as UpdateChecker, and never from the persisted placeholder.
|
|
||||||
+ if (isPlaceholderData) return;
|
|
||||||
+ if (!isUpdatePromptEnabled) return;
|
|
||||||
...
|
|
||||||
- }, [versionFromBackend]);
|
|
||||||
+ }, [versionFromBackend, isPlaceholderData, isUpdatePromptEnabled]);
|
|
||||||
- <BottomDialog open={showUpdateDialog} onClose={...} enableDismiss={false}>
|
|
||||||
+ <BottomDialog open={showUpdateDialog} onClose={...} enableDismiss={isUpdatePromptClosable}>
|
|
||||||
+ {isUpdatePromptClosable && <Later button that closes the dialog>}
|
|
||||||
--- apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
|
|
||||||
const updatePrompt = { isEnabled: false, isClosable: true }
|
|
||||||
- const shouldShowNotice = host.includes('raw') || host.includes('mf')
|
|
||||||
+ const shouldShowNotice = updatePrompt.isEnabled && (host.includes('raw') || host.includes('mf'))
|
|
||||||
return {
|
|
||||||
webviewHtml: shouldShowNotice ? updateNotice : null,
|
|
||||||
- isWebviewClosable: shouldShowNotice ? false : true,
|
|
||||||
+ isWebviewClosable: shouldShowNotice ? updatePrompt.isClosable : true,
|
|
||||||
updatePrompt,
|
|
||||||
}
|
|
||||||
--- apps/user-ui/tests/app/root-layout.test.tsx
|
|
||||||
+ ROOT-33: versionNum ahead but updatePrompt.isEnabled:false -> no store dialog.
|
|
||||||
+ ROOT-34: closable store dialog renders Later and dismisses.
|
|
||||||
--- apps/user-ui/JEST-TEST-CASES.md
|
|
||||||
+ ROOT-33/ROOT-34 rows; ROOT-05/06 note the switch.
|
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue