Merge branch 'MULTI_REGION_I2'

This commit is contained in:
shafi54 2026-10-25 19:40:13 +05:30
commit 9d1ba3d0f9
949 changed files with 147553 additions and 466588 deletions

View file

@ -98,7 +98,11 @@
"Shell(NODE_ENV=test bunx jest --config tests/jest.config.js tests/home-page/navigation.test.tsx 2 >& 1)",
"Shell(NODE_ENV=test bunx jest --config tests/jest.config.js tests/home-page/navigation.test.tsx -t routes to the slot view 2 >& 1)",
"Shell(node inspect.cjs)",
"Shell(node -e \" const s=require('/Users/mohammedshafiuddin/WebDev/freshyo/apps/user-ui/tests/mocks/mock-slots-response.json'); for (const id of [2,40,23]) { const idx = s.slots.findIndex(sl=>sl.products.some(p=>p.id===id)); const sl = s.slots[idx]; console.log('product', id, '-> slot index', idx, 'slotId', sl && sl.id, 'delivery', sl && sl.deliveryTime); } console.log('slot order:', s.slots.map(sl=>sl.id).join(',')); \")"
"Shell(node -e \" const s=require('/Users/mohammedshafiuddin/WebDev/freshyo/apps/user-ui/tests/mocks/mock-slots-response.json'); for (const id of [2,40,23]) { const idx = s.slots.findIndex(sl=>sl.products.some(p=>p.id===id)); const sl = s.slots[idx]; console.log('product', id, '-> slot index', idx, 'slotId', sl && sl.id, 'delivery', sl && sl.deliveryTime); } console.log('slot order:', s.slots.map(sl=>sl.id).join(',')); \")",
"Shell(cmd:*)",
"Shell(which maestro || ls -la ~/.maestro 2>/dev/null | head -20; echo \"---\"; ls ~/.commandcode/mcp.json 2>/dev/null; echo \"--- project mcp\"; cat .mcp.json 2>/dev/null; echo \"--- other agent configs\"; grep -ril \"maestro\" ~/.claude.json ~/.cursor/mcp.json ~/.config/opencode/opencode.json ~/Library/Application\\ Support/Claude/claude_desktop_config.json 2>/dev/null)",
"Shell(~/.maestro/bin/maestro:*)",
"Shell(xcrun:*)"
],
"deny": [],
"defaultMode": "default"

View file

@ -7,7 +7,7 @@
- Prefers detailed analysis and explicit error/mistake checking before executing destructive operations, rather than just performing the action — e.g., before a git merge, or before deleting a row directly from the DB (asked "Can I simply delete the row from db. Will it cause any problems" about an unclaimed reserved coupon, expecting the agent to trace all referencing tables/FKs — couponUsages, couponApplicableUsers/Products — before answering). Confidence: 0.7
- Do not run `git stash` or other destructive git operations that would discard or modify working-tree changes without explicit permission. Confidence: 0.9
- When removing unused code (e.g., an unused tRPC procedure), prefers a complete cleanup: also remove internal helper methods used only by it, associated types, re-exports, orphaned hook/API files and their shared types, and even commented-out imports, leaving zero remaining references. Confidence: 0.9
- Before removing or deciding on code, likes to first verify where it is actually used across the codebase (asks questions like "where is X used"), rather than removing based on assumption. Confidence: 0.4
- Before removing or deciding on code, likes to first verify where it is actually used across the codebase (asks questions like "where is X used"), rather than removing based on assumption. Confidence: 0.5
- Prefers light/pastel colors for randomized or accent UI elements (e.g., tabs, chips). Confidence: 0.7
- Prefers minimal, flat tab/navigation UI: active state shown with a thick underline, no pill/chip backgrounds or rounded fills; communicates desired visual styles by sharing reference images/screenshots. Confidence: 0.8
- Wants the agent to come up with a plan first before implementing code changes. Confidence: 0.9
@ -134,6 +134,7 @@ er-ui/app/(drawer)/(tabs)/home/index.tsx, I want similar here") and expects the
- Dislikes long lists of CLI flags for supplying run-time/test values and asks for a "better way" ("isn't there a better way to supply the values"). Expects values supplied declaratively: non-secret defaults committed in a config file (e.g. Maestro `config.yaml` `env:` block), secrets in a gitignored `.env`-style file, and a thin wrapper/runner script wired to a single package-manager entry point (`bun run e2e`) so one short command runs everything — with extra flags still passable through. Secrets should never be passed inline on the command line or committed. Confidence: 0.7
- When he doubts the current approach ("isn't there a better way"), expects the agent to actually research the tool's documented capabilities (check `--help`, official docs) before proposing alternatives, rather than answering from memory. Confidence: 0.6
- For mobile app E2E testing, wants Android ONLY and never iOS — stated explicitly: "I want to test only on android. Never on ios." The test runner/harness should be wired so it can never target an iOS simulator (e.g., pin the Android package id and always pass `--platform android`), rather than auto-detecting the platform from booted devices. Confidence: 0.9
- The Android-only rule applies to the automated E2E suite, not to ad-hoc/interactive driving of a running app: when he just wants the app operated and inspected, he is happy to use whatever device is already booted, iOS included — "I have maestro mcp installed. I want you to use maestro to control my ios simulator." Expects the agent to check what tooling/MCP servers are actually available in the session, use the installed Maestro setup (MCP or CLI) rather than declaring it unavailable, and tell him how to register the MCP server so it loads in future sessions. Confidence: 0.45
- For React Native / Expo mobile E2E automation, prefers **Maestro** (not Detox/Appium), with its flow configs in a folder at the repo ROOT named `e2e/` — "I want test end to end test automation with maestro. have a folder at the root named e2e" — mirroring his `tests/`-at-root convention for Playwright. Expects the tool's own YAML workspace layout inside it (`config.yaml`, `flows/`, reusable `subflows/`), not per-app test dirs. Confidence: 0.85
- Wants E2E flows to take the shortest realistic user path and skip unnecessary intermediate screens — e.g., add to the cart directly from the home product card's cart icon instead of opening the product-detail screen first ("don't open any product detail. Just click on the cart icon of any product, then go to the cart page and then place order"). Confidence: 0.5
- When he pastes a runtime error/log (e.g., a tRPC/D1 `Failed query: select ... from "key_val_store"` 500), he asks for an explanation first — "what does this error mean. Why am I seeing it" — expecting the agent to investigate and explain the root cause (local D1 state, migrations/config) before changing any code, not to jump straight to a fix. Confidence: 0.5
@ -150,6 +151,11 @@ er-ui/app/(drawer)/(tabs)/home/index.tsx, I want similar here") and expects the
- When he asks where/why some behavior lives ("where are we creating the product. show me the test code of it"), expects the answer to show the ACTUAL code — the exact file path, the function that performs the action, and the relevant snippet — not just a prose description of the flow or a high-level summary. Confidence: 0.55
- For feature coverage, expects the test to span roles end-to-end: exercise the admin/staff CRUD (create → read-back → update → delete) and THEN drive the same entity from the user's end to prove it actually takes effect — e.g. create a coupon as staff, then pass its id to the user's `placeOrder` and assert the order reflects the discount, and that deleting it drops it from eligibility and gets rejected on apply. Stated as "I want to test coupon crud, I then want to test it too. Apply it from user's end for an order." Prefers this combined admin-CRUD-plus-user-application flow in a single suite over an admin-only CRUD test. Confidence: 0.72
- Excludes flows that depend on real third-party services from automated test scope — payment-gateway flows (Razorpay-signed payloads) and OTP/SMS login are deliberately left out, while everything else must be covered. Repeats the exclusion across requests ("don't test payments, OTP Login do the rest"; "except the OTP, payments test rest all of the thingss"), treating untestable external-service paths as an accepted gap rather than investing in mocks/bypasses. Confidence: 0.6
- When asking a narrow, targeted factual question (e.g. "tell me which table has that data"), wants the answer scoped to exactly what was asked — the direct fact (the table name) — not another expansive multi-section explanation; corrects over-answering explicitly ("I meant tell me which table has that data"). The broad end-to-end breakdowns he requests elsewhere are for when he asks for them, not a default response length. Confidence: 0.5
- Prefers API payloads that are FLAT and fully resolved server-side: when a value can come from stacked scopes (bound → region → global), the backend must merge them into one flat JSON object so the client reads the final value directly, with no nested blocks and no client-side merge/precedence logic — "every bound should have all it's bound data, it's region's data and global data. It should be a flat json". Confidence: 0.7
- When redesigning a data model, prefers a clean slate over patching the existing shape — instructs the agent to ignore the current implementation ("forget the current pattern") and re-specify storage from scratch, splitting what was one catch-all table into tables by natural scope instead of preserving legacy structure. Confidence: 0.6
- When he changes a shared backend contract (response shape / query input), expects every consumer to be updated to the new shape in the same change and names the affected apps explicitly ("@apps/user-ui should be accomodated to expect this flat json and use this flat json") — a contract change is not done while any client still reads the old shape. Confidence: 0.65
- Wants MCP servers configured at PROJECT scope (repo-root `.mcp.json`) rather than user/global scope — on being told a server would have to be added globally, he corrected with "I want mcp server in this project." So when registering MCP tooling (e.g. maestro), prefer `--scope project` so the config is scoped to and shareable with the repo. Confidence: 0.6
e changes. Confidence: 0.95
er-ui/app/(drawer)/(tabs)/home/index.tsx, I want similar here") and expects the agent to mirror that pattern exactly, including details like item counts and container styling. Confidence: 0.9
als) rather than introducing new brand palettes; approval of a redesign's layout/composition does not imply approval of color or theme changes. Confidence: 0.95

11
.gitignore vendored
View file

@ -138,6 +138,15 @@ type-clusters/*
apps/user-ui/android/
apps/admin-ui/android/
apps/user-ui/ios/
apps/admin-ui/ios/
.maestro-output/*
apps/admin-ui/.expo/cache/*
apps/admin-ui/.expo/cache/*
.playwright-mcp
/apps/admin-ui/.expo/prebuild
# Local wrangler dev vars (may hold local-only secrets)
.dev.vars
apps/*/.dev.vars

12
.mcp.json Normal file
View file

@ -0,0 +1,12 @@
{
"mcpServers": {
"maestro": {
"transport": "stdio",
"enabled": true,
"command": "/Users/mohammedshafiuddin/.maestro/bin/maestro",
"args": [
"mcp"
]
}
}
}

29
.pi/mcp.json Normal file
View file

@ -0,0 +1,29 @@
{
"mcpServers": {
"maestro": {
"command": "maestro",
"args": [
"mcp"
],
"description": "Maestro mobile/web UI automation: list devices, drive and inspect the screen, run YAML flows locally or on Maestro Cloud."
}
},
"_notes": {
"added": "2026-10-18 (FR-2026-10-18-01 regression run)",
"known_issues": [
"MCP can wedge with 'Device became unreachable during deviceInfo'. Later calls then fail instantly because the failure state is cached, so retrying does not help.",
"Observed cause: a stale/duplicate 'maestro.cli.AppKt mcp' java process and/or stale '~/.maestro/deps/simulator-server ios --id <udid>' children. Killing the simulator-server children alone did not recover it.",
"Recovery that worked: kill the java process running 'maestro.cli.AppKt mcp' (pgrep -f 'maestro.cli.AppKt mcp'). pi respawns it on the next tool call; list_devices and run then work again.",
"After a respawn the Maestro Viewer URL changes (seen at http://127.0.0.1:10000/ and http://127.0.0.1:9999/). Surface the URL from the tool output instead of hardcoding it.",
"take_screenshot returns null content on iOS (the image is still shown to the assistant). On iOS prefer 'xcrun simctl io <udid> screenshot <file>'. On the 'chromium' device take_screenshot returns real base64 image content.",
"Maestro text matchers are FULL-STRING regex with IGNORE_CASE: text 'Foo' does not match 'Foo bar'. Use '.*Foo.*' or an anchored regex.",
"React Native placeholders are not accessibility text nodes (e.g. the cart's 'Select a coupon'); tap/assert those by point.",
"Leftover modals (Remove Item / Delete Address / iOS Save Password) silently block every subsequent tap in a flow; dismiss them explicitly.",
"The MCP server is a long-lived JVM; after heavy flow churn restart it before starting a new batch."
],
"device_ids": {
"ios_simulator": "5A64695E-F4D4-4E2E-90F3-EC3493A2B457",
"web": "chromium"
}
}
}

View file

@ -40,6 +40,7 @@ react-native. They are available in the common-ui as MyText, MyTextInput, MyTouc
- No test framework currently configured
- When adding tests, use Jest + React Native Testing Library
- Test files: `*.test.tsx` or `*.spec.tsx`
- Even when explicitly asked for, don't test push notifications or anything related to OTP
### Architecture
- Monorepo with Turbo
@ -48,7 +49,23 @@ react-native. They are available in the common-ui as MyText, MyTextInput, MyTouc
- Database: Drizzle ORM with PostgreSQL
## Important Notes
- Don't do anything with git. Don't do git add or git commit. That will be managed entirely by the user
- Don't do anything with git unless the user explicitly asks for. Don't do git add or git commit. That will be managed entirely by the user.
## Change Log
- there should be a change log file. unless explicitly specified, assume change-log.txt as the name of the log file. Ensure the file exists. If it doesn't exist create it. Before changing any file which is not a md file or txt file write the change to that file exactly. Write the diff to it and then start making changes. for every change add the current time stamp.
## before editing
- there are proper tests for code. While changing code, also scope what changes are needed in the
tests. Tests and code should go hand in hand. One shouldn't be left behind while one is going
forward. Most of the Projects have a test directory.
## mirror projects
- admin-ui is a react native app. It has a web counterpart admin-web. user-ui is also react native
app. It's web counterpart is web-ui. Any changes you do in the react native should have exactly
same changes in their web counterparts too.
## relevant projects
- the db_helper_postgres is an abandoned project. Don't make any changes there or don't report any
errors from there.

View file

@ -1,313 +0,0 @@
# `any` Usage Audit — what each one should be
**Branch:** `DEAD_CODE_CLEAN`
**Scope:** all `any` keyword usages in `apps/*` and `packages/*` source (`.ts`/`.tsx`), excluding `node_modules`, `dist`, `.wrangler`, `.output`, `.expo`, `.turbo`, `.tanstack`, dumps, `*.sql`, and generated route trees (`routeTree.gen.ts`).
**Nature:** documentation only — no code changed.
## Totals (type-level `any`, excluding prose/comments/generated)
| Area | Count | Dominant cause |
|---|---|---|
| `apps/backend` | ~85 | `as any` casts on JWT/Drizzle/error shapes; `: any` where a shared type exists |
| `packages/db_helper_sqlite` + `_postgres` | ~105 | `(x: any)` on already-typed Drizzle results; `Promise<any>` helpers |
| `apps/admin-ui` | ~161 | `onError/catch (e: any)`; `router.push(... as any)`; entity `useState<any>` |
| `apps/user-ui` + `apps/fallback-ui` | ~137 | `catch/onError`; Expo/TanStack `as any`; catalog/cart `item: any` |
| `apps/web-ui` | ~138 | `Record<number, any>`/`(p: any)` product+slot callbacks; `onError` |
| `apps/admin-web` | ~128 | `onError/catch` (36); domain rows; `navigate({ to: ... as any })` |
| `packages/shared` + `web-components` + `ui` + `migrator` | ~28 | untyped component props; RN style/asset props; migrator rows |
| **Total** | **~780** | |
Regex-based raw totals are a bit higher because the word "any" also appears in comments/prose and `tsconfig` files; those are excluded here.
## The replacement playbook ("what it should have been")
1. **`catch (e: any)` / `onError: (e: any)` → `unknown`** (and narrow with `e instanceof Error ? e.message : '…'`). This is the single largest mechanical category (~100 sites across the repo).
2. **`onError: (error: any)` on tRPC hooks → delete the annotation.** tRPC v11 already infers `TRPCClientError<AppRouter>`; `.message` keeps working.
3. **Callback params on typed Drizzle/array results → delete `: any`.** Because `db_index.ts` passes the full `schema` to `drizzle(...)`, `db.query.*` and `.select()` results are fully inferred; `(x: any) => …` is pure noise.
4. **`(item: any)` / `(product: any)` in catalog/cart lists → the real entity type:** `MergedProduct` (catalog), `CartItem` (carts), `AdminSku`, `AdminSlotWithProducts`, `AdminOrderDetails`, `UserOrderSummary`, etc.
5. **`router.push(… as any)` → typed routes** (`Href` from `expo-router`; `FileRouteTypes['to']`/generated union for TanStack Router). Static routes can simply drop the cast.
6. **`Record<string, any>` → `Record<string, unknown>`** for heterogeneous bags.
7. **`z.any()` → `z.unknown()`** in Zod schemas (or a precise union).
8. **RN/Expo props → their real types:** `StyleProp<ViewStyle>` / `StyleProp<ImageStyle>`, `NativeSyntheticEvent<NativeScrollEvent>`, `TextStyle['fontWeight']`, `ImagePicker.ImagePickerAsset`.
9. **Icon `name={x as any}` → `React.ComponentProps<typeof MaterialIcons>['name']`** (the glyph-key union).
10. **`Promise<any>` db-helper returns → `InferSelectModel<typeof table>` / explicit `Pick<Row, …>`.**
## Highest-leverage shared fixes (fix once, removes many)
These untyped *shared* declarations force `any` at dozens of call sites — tighten them first:
| Fix | File | Impact |
|---|---|---|
| `value: any` → a `ConstValueType \| ConstValueType[]` union (union already defined at line 18) | `packages/shared/types/const.types.ts:8` | Removes `value.map((id: any) => …)` in admin-ui **and** admin-web reorder screens |
| `ListItemProps.item: any`, `CompactProductCardProps.item: any`, `OffersSectionProps.products: any[]`, `AddedToCartProduct.product: any` → hoist a shared structural product type (or make the props generic) | `packages/shared/types/app-common.types.ts:60,78,87,96` | Caps how far web-ui/user-ui flash/offers/complaints props can be tightened |
| `queryParams?: Record<string, any>` → `Record<string, unknown>` | `packages/shared/types/app-common.types.ts:20` | Consumer only does `String(value)` |
| `setFile: (file: any) => void` → `ImagePickerAsset \| ImagePickerAsset[] \| null` | `packages/ui/src/components/use-pick-image.tsx:13` | Type flows into admin-ui `setFile: (assets: any)` (3 sites) and `profile-image`/`ImageUploaderNeo` |
| Export app-local entity types: `MergedProduct`, `CartItem`, `SlotInfo`/`ProductSlotMap` (web-ui/user-ui); `ProductFormData`, `Variant`, `Attribute`, `CouponFormValues` (admin-ui/admin-web) | respective hook/component files | Removes dozens of `values: any` / `item: any` in mutations and list callbacks |
| Backend procedures returning `any[]` (coupon getAll/getReservedCoupons, admin `getUserIncidents`, store) → concrete shared types | `apps/backend/.../admin-apis/apis/{coupon,user,store}.ts` | Removes the downstream `Coupon`/`UserIncident` `any`s in both admin frontends |
---
## apps/backend
### Summary
- **85** `any` keywords across **83 lines / 31 files**.
- **Top files:** `coupon.ts` & `const-store.ts` (7 each), `admin/user.ts`, `post-order-handler.ts`, `app.ts` (6 each), `admin/product.ts` (5), `auth.ts`, `cache-creator.ts` (4).
- **Dominant patterns:** (1) `x as any` around JWT payloads, Drizzle `json` columns, and untyped db-helper returns; (2) `: any` params/locals where a concrete shared type exists (`OrderWithFullData`, `AdminVendorSnippet`, `TagBasicData`, `StaffRole`); (3) generic defaults `<T = any>` and catch clauses.
- **10 of the 85 are inside commented-out "Old implementation" blocks** → delete, don't retype.
| Location | Current code | Should be | Why |
|---|---|---|---|
| `app.ts:57`, `middleware/auth.middleware.ts:19` | `const decoded = payload as any` | `AppJwtPayload` = `{ userId?: number; staffId?: number; name?: string }` | jose `JWTPayload`; tokens are signed as `SignJWT({ userId })` / `SignJWT({ staffId, name })` |
| `app.ts:131,132` | `(err as any).statusCode` | `err instanceof ApiError ? err.statusCode` | `ApiError` is the only error with `statusCode` |
| `app.ts:134,135` | `(err as any).status` | `err instanceof HTTPException ? err.status` | Hono `HTTPException` |
| `app.ts:141` | `c.json({ message }, status as any)` | `status as StatusCode` | Hono status union |
| `types/hono.d.ts:5`, `trpc/trpc-index.ts:7` | `user?: any` | `AppJwtPayload` | consumed as `ctx.user?.userId` |
| `trpc/trpc-index.ts:37` | `const err = error as any` | `unknown` + narrow | catch var; reads name/message/code/stack/meta/sql |
| `jobs/cache-creator.ts:10,13` | `state: any` | `DurableObjectState` | uses storage/alarm |
| `jobs/cache-creator.ts:11,13` | `env: any` | `WorkerEnv` (needs domain input) | passed to `ensureWorkerInit` |
| `jobs/payment-status-checker.ts:3,4,5` | `payment:any; order:any; slot:any` | `typeof payments.$inferSelect` / `{id;userId}` / row types | stub interface; only `order.id/.userId` read |
| `lib/queue-consumer.ts:4,27,40` | `batch: any` | `MessageBatch<NotifQueueMessage>` / `<{orderIds:number[]}>` / `<CancellationMessage>` | pushed message shapes are known |
| `lib/const-store.ts:34,58` | `<T = any>` | `<T = unknown>` | generic default |
| `lib/const-store.ts:90,102,107` | `Record<…, any>` | `Record<…, unknown>` | opaque KV values |
| `lib/api-error.ts:3,5` | `details?: any` | `unknown` | never consumed typed |
| `lib/notif-job.ts:11,22` | `notificationQueue:any`, `notificationWorker:any` | bullmq `Queue`/`Worker` or `Record<string, never>` | stubbed (`{}`) |
| `lib/notif-job.ts:91` | `scheduleNotification(userId, payload: any, …)` | `{ title; body; type; orderId? }` | callers pass exactly this |
| `lib/worker-init.ts:3,4` | `env: any`, `(globalThis as any).ENV` | `WorkerEnv` / typed global | matches existing typed-global pattern |
| `lib/post-order-handler.ts:44,52,95,167,168` | `ordersData: any[]`, `(item: any)`, `createdOrders: any[]`, `Map<…, any[]>` | `OrderWithFullData[]`, `OrderWithFullData['orderItems'][number]`, `PlacedOrder[]` | db-helper return types |
| `lib/post-order-handler.ts:86` | `orderData: any` | `OrderWithCancellationData & { refundStatus: string }` | known shape |
| `lib/flash-delivery-cron.ts:12` | `env: any` | `WorkerEnv` | |
| `lib/env-exporter.ts:62` | `(globalThis as any).ENV \|\| (globalThis as any).process?.env` | typed structural cast | matches rest of codebase |
| `lib/notif-job.ts:91`, `trpc/.../staff-user.ts:64,112` | mixture | `AdminVendorSnippet`, `StaffRole` | concrete shared types exist |
| `admin-apis/apis/store.ts:17,37` | `stores: any[]`, `store: any` | `Store & { owner: User }` | query includes `owner` |
| `admin-apis/apis/banner.ts:59`, `user-apis/apis/auth.ts:274` | `catch (e: any)` | `unknown` + narrow | |
| `admin-apis/apis/const.ts:38` | `z.any()` | `z.unknown()` | |
| `admin-apis/apis/slots.ts:74` | `deliverySequence: z.any()` | `Record<string, number[]>` union | shared `AdminDeliverySequence` |
| `user-apis/apis/payments.ts:129` | `payload as any` | `Record<string, unknown>` | schema is `jsonText<unknown>` |
| `admin-apis/apis/product.ts:265,357,754` | `as any` casts / `product: any` | `CreateProductInput` / `AdminProductTagWithProducts` | helpers/return types exist |
| `user-apis/apis/user.ts:61`, `auth.ts:110,374` | `new Date(userDetail.dateOfBirth as any)` | drop cast | field is `Date \| null` |
| `user-apis/apis/order.ts:293` | `slotId: null as any` | `null` | param is `number \| null` |
| `admin-apis/apis/coupon.ts:129,141,153,154,351,366,440` | `coupons: any[]`, `Promise<any>`, `(au:any)`, `(ap:any)`, `coupon: any` | `Coupon & { applicableUsers; applicableProducts }` / `ReservedCoupon` (needs domain input) | relations not modelled in shared |
| `common-apis/common.ts:79,84,85` | `(id:any)`, `(tag:any)`, `orderedTags:any[]` | `number`, `TagBasicData`, `TagBasicData[]` | `getConstant<T>` default; `getAllTagsForCache()` |
| `admin-apis/apis/user.ts:48,60,98,117,170,258` | `(u:any)` etc | `Pick<User,…>`, `Pick<PlacedOrder,…>`, `UserIncident` (needs domain input) | select shapes |
| Dead-code `any`s (delete) | `product.ts:565,700`, `banner.ts:194`, `slots.ts:176,347`, `address.ts:192`, `admin/order.ts:384`, `vendor-snippets.ts:260`, `const-store.ts:91,97` | — | commented-out old impls |
**Easy wins:** drop redundant `as any` (`product.ts:265/357`, `order.ts:293`, `user.ts:61`, `auth.ts:110/374`, `payments.ts:129`); `: any`→`unknown` (`api-error`, `const-store` generics, `payment-status-checker`, `payments-utils`); `catch`→`unknown` (`banner.ts:59`, `auth.ts:274`); `z.any()`→`z.unknown()`; delete dead `any`s; define `AppJwtPayload` once.
---
## packages/db_helper_sqlite + db_helper_postgres
**Summary:** **105** tokens across **98 lines / 17 files**. Top: `sqlite/admin-apis/product.ts` (27), `sqlite/admin-apis/order.ts` (19), `run-batched.ts` (7), `admin-apis/user.ts` (7 each pkg), `admin-apis/coupon.ts` (6 each). Dominant: `(x: any)` on already-typed Drizzle results (~60) — just delete. `Row<T>` = `InferSelectModel<typeof T>`, `Insert<T>` = `InferInsertModel<typeof T>`.
| Location | Current code | Should be | Why |
|---|---|---|---|
| `sqlite/admin-apis/product.ts:182,235,385,483,530` | `(ci\|f: any)` | `CreateComboItemInput` / `SkuFeatureLike` | element types of typed relations |
| `product.ts:185,238` | `(f: any)` | `Row<skuFeatures>` | |
| `product.ts:596` | `(tag: any)` | inferred (cast at 594) | |
| `product.ts:598,669,709` | `(assignment: any)` | `Row<productTags> & { sku: … }` | |
| `product.ts:756` | `(review: any)` | inferred select shape | |
| `product.ts:817,822` | `(group:any)`, `(membership:any)` | inferred | |
| `product.ts:367` | `updateProduct(id, input: any)` | `UpdateProductInput` (domain) | |
| `product.ts:39,41,114,340,498,545` | `any[]`/`(ci:any)` | `CreateComboItemInput` / `AdminProductComboItem[]` | |
| `product.ts:384,398,401` | `(sku: any)` | `CreateSkuInput & { id?: number }` | |
| `product.ts:956` | `const updateData: any` | `Partial<Insert<productMarketStats>>` | |
| `sqlite/admin-apis/order.ts:174,239,250,364,369,378,388,412,523,528,538,549,554,577,615,616,622,643` | `(u\|item\|f\|order\|acc: any)` | delete → inferred | typed query results |
| `sqlite/admin-apis/slots.ts:122,125,133,199` | `(item\|s\|sku: any)` | delete → inferred | |
| `slots.ts:194` | `(item: any)` + reads `item.isDeleted` | inferred; **add `isDeleted: true` to `columns` at :191** | hidden bug surfaced by typing |
| `slots.ts:56` | `fetchExistingSkuIds(tx: any, …)` | Drizzle tx type (`Parameters<Parameters<typeof db.transaction>[0]>[0]`) | |
| `stores/store-helpers.ts:312,315,326` | `(item\|s\|sku: any)` | delete → inferred | |
| `admin-apis/store.ts:7,17` (both pkgs) | `Promise<any[]>` / `Promise<any\|null>` | `Array<Row<storeInfo> & { owner: Row<staffUsers>\|null }>` | |
| `admin-apis/staff-user.ts:22,78` (both) | `Promise<any[]>` | inferred relation / `StaffRole[]` | |
| `admin-apis/user.ts:5,28,95,122,184,224,245` (both) | `Promise<any…>` | `Row<users>`, `Pick<Row<users>,…>`, `Row<userIncidents>`, etc. | select shapes |
| `admin-apis/coupon.ts:10,53,175,211,213,300` (both) | `any[]`/`Promise<any…>`/`input: any` | `Row<coupons> & {…}`, `Row<reservedCoupons>`, `ReservedCouponInput` | InferInsertModel |
| `user-apis/auth.ts:102,119` (both) | `const userUpdate: any` | `Partial<Insert<users>>` / `Partial<Insert<userDetails>>` | |
| `user-apis/auth.ts:184` (both) | `catch (error: any)` | `unknown` + narrow | `23505` is pg-only |
| `lib/run-batched.ts:3,19` | `(cb: (tx: infer Tx) => any, ...args: any[]) => any` | `unknown` | unused callback return/args |
| `lib/automated-jobs.ts:25` (both) | `value: any` | `unknown` | |
**Easy wins:** delete `: any` from ~60 map/filter callbacks; `run-batched` `any`→`unknown`; `automated-jobs` `value: unknown`; object literals → `Partial<Insert<…>>`; `catch`→`unknown`; **free bug fix** at `slots.ts:191/194`; ~35 `Promise<any>` return annotations via `Row`/`Insert`.
---
## apps/admin-ui
**Summary:** **161** code occurrences / 49 files. Top: `delivery-sequences/index.tsx` (10), `prices-overview` (11), `products/add+edit` (14), `_layout.tsx` (13). Dominant: `catch/onError (error: any)` (35) and `router.* as any` (36) — both mechanical.
| Location | Current code | Should be | Why |
|---|---|---|---|
| `_layout.tsx:53…137`, `dashboard/index.tsx:32,99,242`, banners/products/slots/stores/prices/manage-orders (≈18 files) | `router.push("…" as any)` | `as Href` (`expo-router`); drop cast for static routes | typed routes |
| `dashboard/index.tsx:39,250,275`, `manage-orders/index.tsx:77` | `name={item.icon as any}` | `keyof typeof MaterialIcons.glyphMap` | glyph union |
| `TagMenu.tsx:62`, `stores/edit:28`, `send-notifications:48`, `coupons/*`, `prices:286`, `SlotForm:92,107`, `delivery-sequences`, `order-details`, `orders` (≈24) | `onError: (error: any)` | delete annotation | tRPC infers |
| VendorSnippet/ProductGroupForm/products/coupons/stores/vendor-snippets/product-tags/send-notifications (≈11) | `catch (error: any)` | `unknown` + narrow | |
| `coupons/index.tsx:11,111` | `item: any` | `Coupon & {relations}` / reserved (domain) | backend returns `any[]` |
| `stores/index.tsx:15` | `item: any` | `Store` | |
| `products/index.tsx:148` | `{ item: any }` | `Omit<AdminProductWithRelations,'skus'> & { skus: SerializedAdminSku[] }` | |
| `slots/index.tsx:11`, `rebalance-orders:10` | `item: any` | `AdminSlotWithProducts` | |
| `slots/slot-details.tsx:24`, `product-groupings:130`, `products/detail:146` | `useState<any…>` | `AdminSlotProductSummary[]`, `AdminSku[]`, `AdminProductReviewWithSignedUrls` | |
| `slots/index:238`, `rebalance:123` | `useState<any[]>` | `string[]` | product names |
| `products/add:15,64,29,36,80`, `edit` (same) | `values: any`, `(variant:any)`, `(a:any)`, `(ci:any)` | `ProductFormData`, `Variant`, `Attribute`, `CreateComboItemInput` (export from ProductForm) | |
| `BannerForm:66`, `StoreForm:72`, `products/detail:32` | `setFile: async (assets: any)` | `ImagePicker.ImagePickerAsset \| ImagePickerAsset[]` | |
| `TagForm.tsx:40` | `forwardRef<any,…>` | `unknown` | no imperative handle |
| `TagForm.tsx:57` | `(sku: any)` | `SkuSummary` | |
| `toaster.tsx:39` | `data: any` | `{ rideId?; carId? } \| null` (domain) | |
| `CouponForm.tsx:60,66,156,191,192,205,237,238` | `function(value:any)`, `(values as any)`, `(errors.couponCodes as any)` | `CouponFormValues`, narrow error shapes | |
| `ProductGroupForm:13`, `SnippetOrdersView:21`, `SlotForm:37,48,191` | `products: any[]`, `sequence: any[]`, `(snippet/p: any)` | `AdminSku[]`, `number[]`, `AdminVendorSnippetWithAccess`, `AdminSlotProductSummary` | |
| `UserIncidentsView:141` | `(incident: any)` | `UserIncident` (domain) | |
| `customize-app/index:9,58,59,60` | `Record<string,any>`, `value:any`, `setFieldValue(any)`, `router:any` | `Record<string,unknown>`, `unknown`, `Router` | |
| `popular-items:139`, `all-items-order:111`, `product-tags/order:102` | `value.map((id: any) => parseInt(id))` | `number` (root: `Constant.value`) | |
| `prices-overview:25,28,29,30,46,153,204,224,270` | `sku:any`, `Record<string,any>`, `const update:any` | local `PriceSku`, existing `PendingChange`, mutation input | |
| `delivery-sequences:53,354,373,389,438,588,622` | `orders:any[]`, `(deliverySequence as any)` | `AdminSlotOrder[]`, drop cast (`AdminDeliverySequence`) | |
| `order-details:148` | `const mutationData:any` | `initiateRefund` input | |
| `coupons/create:27` | `values: any` | `CouponFormValues` | |
**Easy wins:** drop `: any` on 24 `onError`; `catch`→`unknown` (11); `as any`→`as Href` (36); icon glyph types (4); drop `deliverySequence as any` (6); remove `products/edit:180 as any`; `triggerStyle` → `StyleProp<ViewStyle>`; export `ProductFormData/Variant/Attribute`.
---
## apps/user-ui + apps/fallback-ui
**Summary:** **137** real type-level / 46 files (4 non-type "any" words ignored). Top: `home/index.tsx` (20), `cart-page` (11), `ProductDetail` (11). Dominant: `catch/onError` (29); router casts (23); catalog/cart `item: any` (30+).
| Location | Current code | Should be | Why |
|---|---|---|---|
| login/register/edit-profile/ComplaintForm/OrderMenu/ProductDetail/registration-form + fallback create-coupon/demo | `catch (error: any)` | `unknown` + narrow | |
| many `onError: (error: any)` (14+) | `onError: (error: any)` | `unknown` / delete (tRPC infers) | |
| `me/index`, `SlotSpecificView`, `cart-page` (≈12) | `router.replace/push(target as any)` | `Href` | |
| fallback AuthWrapper/home/login/super-admin/user-home (≈13) | `navigate({ to: '…' as any })` | drop cast | routes registered |
| `me/index:137`, `my-orders:111,278` | icon `as any` | `ComponentProps<typeof Ionicons/MaterialIcons>['name']` | |
| `my-orders:68,69` | `getStatusColor(): any` | typed `StatusColor` | |
| `home/index.tsx` (many) | `slot: any`, `(p: any)`, `dashboardTags:any[]`, `Record<number,any[]>`, `useRef<any>`, `onLayout(e:any)`, `useState<any[]>` | `UserSlotWithProducts`, `UserSlotProduct`, `AllProductsApiType['tags']`, `MergedProduct[]`, `ComponentRef<typeof ScrollView>`, `LayoutChangeEvent` | catalog types exist |
| `ProductDetail:48,75,76,79,87,147,710` | `useState<any[]>`, `(slot/p/a/b/item:any)`, `setFile(assets:any)` | review/cart/slot types + `ImagePickerAsset` | shared `UserProductReviewWithSignedUrls` missing `adminResponse`/`signedAdminImageUrls` (domain) |
| `cart-page:60` | `coupon: any` | `UserCouponWithRelations` | |
| `registration-form:29` | `useState<any>` | `ImagePicker.ImagePickerAsset` | |
| `useUploadToObjectStore:26` | `contextString as any` | drop cast | shared `ContextString` assignable |
| `notif-context:45,46` | `useRef<any>` | listener return types | |
| `toaster:5` | `data: any` | `Record<string, unknown>` | |
| `AddToCartDialog` (6) | `(item/slot/p: any)`, `Record<number,any>` | `CartItem`, `UserSlotWithProducts`, `UserSlotProduct` | |
| `AuthContext:14` | `Record<string,any>` | tighten shared `AuthRedirectOptions.queryParams` | |
| `getCurrentUserId:8` | `jwtDecode(token)` any | `jwtDecode<{id?;userId?}>` | |
| fallback `order-details:33,51,223`, `user-details:44,45,141`, `login:23`, `demo:11,76`, `inauguration:74` | `as any` / `any[]` / `any` | `AdminOrderDetails`, inferred, `ReturnType<typeof setInterval>`, local `DemoResponse` | |
| `ProductCard:22,29,84,93,94` | `item:any`, `ComponentType<any>`, `(cartItem:any)`, `Record<number,any>`, `(slot:any)` | `MergedProduct`, `ComponentType<PropsWithChildren>`, `CartItem`, `UserSlotWithProducts` | |
| `SlotSpecificView:232,252,457` | `item:any`, `(cartItem:any)`, `(p:any)` | `MergedProduct`, `CartItem` | |
| `PaymentAndOrderComponent:17,24,25` | `cartItems:any[]`, `constsData:any`, `selectedCoupons:any[]` | `CartItem[]`, `EssentialConstsApiType`, `EligibleCoupon[]` | |
| `hooks/useProductSlotIdentifier:18,25`, `prominent-api-hooks:127` | `(slot/a/b/p: any)` | drop → inferred | |
**Easy wins:** bulk `unknown` (29); delete fallback `as any` casts (≈18 incl. `contextString`); catalog/cart annotations (≈30) → `MergedProduct`/`CartItem`; icon types (4); trivial typed `any`s (jwt, setInterval, notif refs, toaster, styles).
---
## apps/web-ui
**Summary:** **138** annotations / 35 files (2 prose excluded). Top: `slot-view` (20), `home.index` (18), `flash` (10), `home.product.$id` (9). Dominant: untyped list callbacks over cached API data (`MergedProduct`, `UserSlotWithProducts`), then `(error: any)`.
| Location | Current code | Should be | Why |
|---|---|---|---|
| `FloatingCartBar:43,44`, `PaymentAndOrderComponent:34,35`, `cart:18,19`, `checkout:38,39`, `home.cart:18,19` | `Record<number,any>` / `(p:any)` | `Record<number, MergedProduct>` / `(p: MergedProduct)` | from `useAllProducts()` |
| `AddToCartDialog:45,78`, `ProductCard:38`, `home.product.$id:63`, `flash:205` | `(item:any)` | `CartItem` | `useGetCart()` |
| `slot-view:399` | `(cartItem:any).productId` | `(cartItem: CartItem).skuId` | **latent bug** |
| `AddToCartDialog:53,57,59,143`, `usePopulateCentralStores:15,30,31,43`, `home.product.$id:51,52,55,94,316,397`, `slot-view:58…153`, `home.index:623` | `(slot:any)`, `slot.products.forEach((p:any)`, slot maps, `(a/b:any)` | `UserSlotWithProducts`, `UserSlotProduct`, `Record<number, UserSlotWithProducts>` | `useSlots()` |
| `usePopulateCentralStores:15` (+43–48) | extra fields `deliveryDate/displayDate/displayTime` | **domain**: not on `UserSlotWithProducts` but required by `SlotInfo` | stale/dead-field mismatch |
| `usePopulateCentralStores:25` | `Record<number,any>` | `ProductSlotMap[number]` (export) | |
| `flash:38,67,77,83,166`, `home.index:154,155,225,326`, `home.search:87,166`, `offers:32,67,68`, `slot-view:139…238`, `stores.$storeId:44,125,163`, `usePopulateCentralStores:28`, `prominent-api-hooks:167` | `(product/p/a/b:any)` | `MergedProduct` | |
| `stores.$storeId:28,38` | `new Map<number,any>`, `(product:any)` | `Map<number, MergedProduct>`, `(product: UserStoreProduct)` | |
| `home.index:133,135,142,143` | `Record<number,any[]>`, `Map<number,any>`, `const ordered/rest: any[]` | `MergedProduct[]` etc | |
| `ProductCard:11` | `item:any` | `MergedProduct` | |
| `flash:36,54,124,156`, `home.index:378,530`, `slot-view:228,294,339`, `stores:78,104`, `stores:161` | `(store:any)`, `stores:any[]`, `(product:any)` | `UserStoreSummary`, `UserStoreSampleProduct` | |
| `checkout-hooks:16,44,67`, `CheckoutAddressSelector:11,72`, `checkout:31`, `flash.checkout:74`, `home.checkout:75` | `useState<any>`, `(addr/address:any)` | `UserAddress` | |
| `AddressForm:48,59,90,92`, `MeOrderMenu:68,95`, `PaymentAndOrderComponent:67`, `me.addresses:121,149`, `me.edit-profile:46,56,103`, `me.orders.$id:42,54` | `onError/catch (e:any)`, `(error:any)` | delete / `unknown`; `AddressForm` narrow `Yup.ValidationError` | |
| `me.orders.$id:99` | `order as any` | drop (`UserOrderDetail`) | |
| `me.orders.$id:117,301`, `me.orders:189,75,325` | `(item/product:any)`, `useState<any[]>` | `UserOrderItemSummary`, `UserOrderSummary` | |
| `BottomNavigation:72`, `Sidebar:81`, `me:167` | `to: … as any` | generated route union | |
| `Topbar:27` | `'/home/search' as any` | drop cast | |
| `home.index:122,291,472,474,513` | `(t/tag/b/_:any)`, `banners:any[]` | tag type, `UserBanner`, `string` | |
| `home.product.$id:379` | `(deal:any)` | `SpecialDealCore` | |
| `lib/auth-context:15,24,110` | `userDetails:any`, `(details:any)` | local `User` | |
| `flash-cart-store:4,5` | `any \| null` | `MergedProduct \| null` (domain) | |
| `useUploadToObjectStorage:26` | `contextString as any` | drop | |
| `ProductCard:47,48`, `PaymentAndOrderComponent:13`, `slot-view:101,104`, `me.complaints:168` | `Record<number,any>`, `(slot:any)`, `cartItems:any[]`, `as any` time, `(complaint:any)` | `SlotInfo`, `CartItem[]`, widen helper, `UserComplaint` | |
**Easy wins:** drop redundant annotations on tRPC `onError` (10) and `cartData.items.find` (5); replace 5-file `productsById` boilerplate (10); `catch`→`unknown` (4); export `CartItem` + `SlotInfo`/`ProductSlotMap`; drop `navigate` casts; **fix `slot-view:399` bug**.
---
## apps/admin-web
**Summary:** **128** annotations (3 prose excluded) / 50 files. Top: `orders.sequence` (11), `prices` (10), `products.edit` (9). Dominant: `onError/catch` (36 = 28%), untyped rows, route casts.
| Location | Current code | Should be | Why |
|---|---|---|---|
| 24 sites (`stores.edit:35`, `orders.sequence:471,623,665`, `orders.list:71,171`, `coupons.*`, `slots:51`, `complaints:81`, `SlotForm:91,106`, `notifications:35`, `TagMenu:56`, `UserIncidentsView:31`, `staff-auth:62`, `orders.$id:68,84,95,105`, `CancelOrderDialog:34`, `prices:281`, `stores.new:27`) | `onError: (error:any)` | delete | tRPC infers |
| 13 sites (`product-tags.new:50`, `product-tags.edit:65`, `coupons.new:57`, `products.$id:81`, `notifications:72`, `vendor-snippets:54,296`, `OrderOptionsMenu:69`, `products.new:106`, ProductGroupForm:68, VendorSnippetForm:87, products.edit:189, stores:114) | `catch (error:any)` | `unknown` + narrow | |
| `orders.sequence:363,382,398,456,603,635` | `(deliverySequence as any)` | drop → `AdminDeliverySequence` | |
| `slots.$id.edit:48`, `slots:28`, `rebalance:28`, `slots.new:43`, `SlotForm:47` | `(p:any)` | `AdminSlotProductSummary` | |
| `SlotForm:36` | `(snippet:any)` | `AdminVendorSnippetWithAccess` (shape mismatch, domain) | |
| `SlotForm:189`, `TagForm:114`, `prices:41` | `(prod/sku/f:any)` | `AdminSku`, `SkuSummary`, `AdminSkuFeature` | |
| `product-tags.edit:92` | `(p:any)` | `AdminProductTagAssignment` | |
| `ProductGroupForm:12`, `product-groupings:25,108` | `products:any[]`, `useState<any[]>` | `AdminSku[]` | |
| `UserIncidentsView:142` | `(incident:any)` | `UserIncident` (domain) | |
| `products:149` | `(product:any)` | `AdminProductWithRelations` | |
| `rebalance:13`, `slots:14` | `item:any` | `AdminSlotWithProducts` | |
| `rebalance:16,128`, `slots:15,242` | `Dispatch<…any[]>`, `useState<any[]>` | `string[]` | |
| `slots.detail:31` | `useState<any[]>` | domain (`AdminSlotProductSummary` lacks `shortDescription`) | |
| `orders.sequence:69` | `orders:any[]` | `AdminSlotOrder[]` | |
| `prices:20,23,24,25,148,199,219,265` | `sku:any`, `Record<string,any>`, `const update:any` | `SkuRow`, existing `PendingChange`, mutation input | |
| `vendor-snippets:233` | `useState<any>` | `{ orders; snippetCode }` (align `totalAmount` number/string) | |
| `SnippetOrdersView:20` | `sequence:any[]` | `unknown`/`number[]` | shared is `unknown` |
| `coupons.new:30`, `products.edit:87`, `products.new:19` | `values: any` | export `CouponFormValues` / `ProductFormData` | |
| `CouponForm:78,84,171,206,207,220,252,253` | `function(value:any)`, `(values as any)`, `(errors as any)` | `CouponFormValues`, narrow | |
| `coupons.tsx:14,17,114,220,363` | `item/coupon:any` | `Coupon & {relations}` / reserved (domain) | |
| `MultiSelect:25`, `SearchableSelect:23`, `coupons:302,430` | `triggerComponent?: any` | `(props:{onClick:()=>void}) => ReactNode` | |
| `SnippetMenu:20`, `TagMenu:11` | `triggerStyle?: any` | `string \| CSSProperties` | |
| `TagForm:96` | `forwardRef<any,…>` | `unknown` (ref unused) | |
| `customize-app:12,61,62,63` | `Record<string,any>`, `value:any`, `setFieldValue(any)`, `router:any` | `Record<string,unknown>`, `unknown`, local router shape | |
| `customize-app.ordering:113`, `popular:126`, `product-tags.order:106` | `value.map((id:any)=>parseInt(id))` | root: `Constant.value` | |
| `stores.edit:33`, `dashboard.index:82`, `customize-app:173`, `orders.tsx:24`, `dashboard.tsx:108` | `navigate({to: … as any})` | generated route union / drop | |
| `products.edit:66,101,108,139,162,166,183`, `products.new:33,40,68,84,88` | `(variant/ci/a/attr:any)`, `as any` | `Variant`, `AdminProductComboItem`, `SkuFeatureLike`, `CreateComboItemInput` | |
| `orders.$id:159` | `const mutationData:any` | `initiateRefund` input | |
| `toaster:16`, `event-bus:6,11` | `_data:any`, `...args: any[]` | `unknown` | |
**Easy wins:** drop 23 `onError`; 13 `catch`→`unknown`; type slot rows (9); `prices` `SkuRow`+`PendingChange` (10); export `ProductFormData/Variant/Attribute/CouponFormValues`; fix shared `Constant.value`; typed routes (5).
---
## packages/shared + web-components + ui + migrator
**Summary:** **28** tokens / 17 files. Top: `app-common.types.ts` (5), `migrator/sqliteToPostgres` (4), `web-components/data-table.tsx` (4). Dominant: untyped component props + RN style/asset props. (No `catch (e: any)` in scope.)
| Location | Current code | Should be | Why |
|---|---|---|---|
| `packages/shared/types/app-common.types.ts:20` | `queryParams?: Record<string, any>` | `Record<string, unknown>` | only `String(value)` |
| `app-common.types.ts:60` | `item: any` | generic `ListItemProps<T>` (domain) | shared list renderer |
| `app-common.types.ts:78` | `item: any` | hoist shared product type (domain) | consumers use id/images/name/flashPrice/incrementStep |
| `app-common.types.ts:87` | `products: any[]` | shared product type (domain) | offers section |
| `app-common.types.ts:96` | `product: any` | shared product type (domain) | AddToCartDialog |
| `packages/shared/types/const.types.ts:8` | `value: any` | `ConstValueType \| ConstValueType[]` (defined line 18) | consumers branch/narrow |
| `migrator/sqliteToPostgres/index.ts:47` | `.all() as any[]` | named `SqliteColumnRow` | PRAGMA shape fixed |
| `migrator/.../index.ts:113` | `parseValue(value:any): any` | `unknown` | returns JSON.parse/raw |
| `migrator/.../index.ts:181` | `.all() as any[]` | `Record<string, unknown>[]` | dynamic `SELECT *` |
| `packages/ui/src/services/axios.ts:56` | `(err as any).original = error` | `Object.assign` / typed `Error & { original: unknown }` | |
| `packages/ui/src/lib/refresh-context.tsx:7` | `queryClient: any` | `QueryClient` | dep exists |
| `packages/ui/src/lib/tailwind.ts:6` | `create(tailwindConfig as any)` | `as TwConfig` (`twrnc`) | |
| `packages/ui/src/components/image-viewer.tsx:16` | `style?: any` | `StyleProp<ImageStyle>` | |
| `packages/ui/src/components/info-dialog.tsx:15`, `dropdown.tsx:17` | `style?: any` | `StyleProp<ViewStyle>` | |
| `packages/ui/src/components/search-bar.tsx:21` | `forwardRef<any,…>` | `React.ElementRef<typeof PaperTextInput>` | |
| `packages/ui/src/components/text.tsx:25` | `let fontWeight: any` | `TextStyle['fontWeight']` | |
| `packages/ui/src/components/profile-image.tsx:11,25` | `file?: any`, `setFile:(file:any)` | `ImagePickerAsset & { name }` | |
| `packages/ui/src/components/use-pick-image.tsx:13` | `setFile: (file: any) => void` | `ImagePickerAsset \| ImagePickerAsset[] \| null` | root of many `assets: any` |
| `packages/ui/src/components/ImageUploaderNeo.tsx:22` | `(files: any)` | `ImagePickerAsset \| ImagePickerAsset[] \| null` | |
| `packages/ui/src/components/ImageCarousel.tsx:27` | `(event: any)` | `NativeSyntheticEvent<NativeScrollEvent>` | |
| `packages/web-components/.../my-text-input.tsx:45` | `{...(props as any)}` | `TextareaHTMLAttributes` union | spread onto `<textarea>` |
| `packages/web-components/.../data-table.tsx:7,12,13` | `(value:any,row:any)`, `data:any[]`, `(row:any,index)` | generic `Column<T>` / `DataTableProps<T>`, `T extends Record<string, unknown>` | |
**Easy wins:** `queryParams`/`Constant.value`; migrator `unknown` + typed PRAGMA row; `QueryClient`/`TwConfig`; RN prop types (10); `Object.assign`; make `DataTable` generic. **4 domain items:** product-shaped props in `app-common.types.ts`.
---
## Suggested remediation order
1. **Mechanical, huge payoff (~200 sites, no domain knowledge):** `catch`/`onError` → `unknown`; delete tRPC `onError` annotations; `Record<string, any>` → `unknown`; `z.any()` → `z.unknown()`; delete `: any` from typed Drizzle callbacks.
2. **Shared root causes (removes dozens downstream):** `Constant.value`, `app-common.types.ts`, `use-pick-image.tsx`, export `CartItem`/`SlotInfo`/`MergedProduct` and `ProductFormData`/`CouponFormValues`.
3. **Backend result typing:** replace `Promise<any…>` db-helper returns and `any[]` procedures with `InferSelectModel`/shared types — unblocks both admin frontends.
4. **Typed routes:** Expo `Href` / TanStack generated union (removes ~50 `as any`).
5. **Domain-input types to define:** `UserIncident`, reserved-coupon/client-coupon-with-relations, `RefundInput`, shared product type, `NotificationToast` payload.
6. **Bugs masked by `any` (fix while typing):** `web-ui/src/routes/slot-view.tsx:399` (`cartItem.productId` → `skuId`), `db_helper_sqlite/src/admin-apis/slots.ts:191/194` (`isDeleted` not selected), `usePopulateCentralStores.ts:15` (`deliveryDate`/`displayDate`/`displayTime` fields not on the slot type).

View file

@ -1,162 +0,0 @@
# Dead Code Report — branch `DEAD_CODE_CLEAN`
> **Status: EXECUTED.** The dead code listed below has been removed (see "Removal status" at the bottom). The one exception is the Drizzle relation exports, which were kept after verification.
Static-analysis sweep for reachable-code / caller-less code across the monorepo.
**Method:** ripgrep-based caller search + manual verification.
- **tRPC endpoints:** every procedure in `admin`/`user`/`common` routers was enumerated, then searched for callers (`trpc.<path>` and `trpcClient.<path>`) in `apps/admin-ui`, `apps/user-ui`, `apps/web-ui`, `apps/admin-web`, `apps/fallback-ui`, `apps/info-site`.
- **Methods/functions:** exported + local `function`/`const` definitions in `apps/backend/src` and `packages/db_helper_sqlite/src` were searched repo-wide; classified as *truly uncalled* only when they appear nowhere except their definition (and pure re-export files).
- **Files:** inbound-reference scan by module name.
- Excludes `node_modules`, `dist`, `.wrangler`, `.output`, `.expo`, `.turbo`, `.tanstack`.
> Caveats at the bottom — some of these may be intentional (manual tooling, external API consumers, planned features). Verify before deleting.
---
## 1. Dead tRPC endpoints (15)
No caller in any client app (native or web). Each is still registered on the router, so it is reachable over HTTP but unused by this repo.
| Endpoint | File | Line | Note |
|---|---|---|---|
| `trpc.admin.coupon.validate` | `apps/backend/src/trpc/apis/admin-apis/apis/coupon.ts` | 265 | Admin coupon validation |
| `trpc.admin.vendorSnippets.getById` | `.../admin-apis/apis/vendor-snippets.ts` | 184 | Single snippet fetch |
| `trpc.admin.vendorSnippets.getVendorOrders` | `.../admin-apis/apis/vendor-snippets.ts` | 464 | Vendor orders |
| `trpc.admin.slots.getSlotsProductIds` | `.../admin-apis/apis/slots.ts` | 138 | Dup of product.* variant |
| `trpc.admin.slots.updateSlotProducts` | `.../admin-apis/apis/slots.ts` | 194 | Dup of product.* variant |
| `trpc.admin.slots.getSlots` | `.../admin-apis/apis/slots.ts` | 387 | Only `trpc.user.slots.getSlots` is used |
| `trpc.admin.slots.deleteSlot` | `.../admin-apis/apis/slots.ts` | 583 | No delete-slot UI |
| `trpc.admin.product.updateSlotProducts` | `.../admin-apis/apis/product.ts` | 392 | Duplicate router entry |
| `trpc.admin.product.getSlotsProductIds` | `.../admin-apis/apis/product.ts` | 462 | Duplicate router entry |
| `trpc.admin.staffUser.getUsers` | `.../admin-apis/apis/staff-user.ts` | 79 | `admin.user.getAllUsers` is the used one |
| `trpc.admin.staffUser.getUserDetails` | `.../admin-apis/apis/staff-user.ts` | 104 | `admin.user.getUserDetails` is used |
| `trpc.admin.staffUser.updateUserSuspension` | `.../admin-apis/apis/staff-user.ts` | 128 | `admin.user.updateUserSuspension` is used |
| `trpc.admin.user.createUserByMobile` | `.../admin-apis/apis/user.ts` | 29 | No caller |
| `trpc.common.product.getDashboardTags` | `.../common-apis/common.ts` | 144 | Home reads tags from `products.json`, not this |
| `trpc.hello` | `apps/backend/src/trpc/router.ts` | 14 | Scaffold sample endpoint |
**Notable:** the `slots` ↔ `product` routers have **four duplicated** procedures (`getSlotsProductIds`, `updateSlotProducts`) — both copies are dead. The `staffUser` router duplicates three user-management procedures that are only ever called via the `admin.user` router.
---
## 2. Dead backend functions / constants (truly uncalled)
Defined/exported but never referenced anywhere else in the repo.
### Env / config
| Symbol | File |
|---|---|
| `getJwtSecret` | `apps/backend/src/lib/env-exporter.ts` |
| `getRedisUrl` | `apps/backend/src/lib/env-exporter.ts` |
| `getPhonePeBaseUrl` | `apps/backend/src/lib/env-exporter.ts` |
| `getPhonePeClientId` | `apps/backend/src/lib/env-exporter.ts` |
| `getPhonePeClientVersion` | `apps/backend/src/lib/env-exporter.ts` |
| `getPhonePeClientSecret` | `apps/backend/src/lib/env-exporter.ts` |
| `getPhonePeMerchantId` | `apps/backend/src/lib/env-exporter.ts` |
| `READABLE_ORDER_ID_KEY` | `apps/backend/src/lib/const-strings.ts` |
| `WELCOME_MESSAGE` | `apps/backend/src/lib/const-strings.ts` |
| `defaultRole` | `apps/backend/src/lib/roles-manager.ts` |
### Notifications / jobs
| Symbol | File | Note |
|---|---|---|
| `sendPushNotificationsMany` | `apps/backend/src/lib/expo-service.ts` | Whole file has no importers (see §4) |
| `sendOrderPlacedNotification` | `apps/backend/src/lib/notif-job.ts` | Only an unused import + a commented call in `user-apis/order.ts` |
| `sendOrderCancelledNotification` | `apps/backend/src/lib/notif-job.ts` | Same — imported, call commented |
| `sendPaymentFailedNotification` | `apps/backend/src/lib/notif-job.ts` | No reference |
| `sendOrderOutForDeliveryNotification` | `apps/backend/src/lib/notif-job.ts` | No reference |
| `sendRefundInitiatedNotification` | `apps/backend/src/lib/notif-job.ts` | No reference |
*(Alive: `sendAdminNotification` via `queue-consumer.ts` ← `worker.ts`; `sendOrderPackagedNotification` and `sendOrderDeliveredNotification` via admin order api; `scheduleNotification` via those.)*
### Stores / cache / misc
| Symbol | File |
|---|---|
| `getOrderDetailsWrapper` | `apps/backend/src/dbService.ts` |
| `clearAllCache` | `apps/backend/src/lib/cloud_cache.ts` |
| `getAllBanners` | `apps/backend/src/stores/banner-store.ts` |
| `getTagById` | `apps/backend/src/stores/product-tag-store.ts` |
| `getAllTags` | `apps/backend/src/stores/product-tag-store.ts` |
| `getProductSlots` | `apps/backend/src/stores/slot-store.ts` |
| `getAllProductsSlots` | `apps/backend/src/stores/slot-store.ts` |
| `getUserNegativity` | `apps/backend/src/stores/user-negativity-store.ts` |
| `createTRPCRouter` | `apps/backend/src/trpc/trpc-index.ts` (alias re-export, unused) |
---
## 3. Dead exports in `db_helper_sqlite`
| Symbol | File | Note |
|---|---|---|
| `mergeDuplicateProducts` | `packages/db_helper_sqlite/src/admin-apis/merge-duplicate-products.ts` | Exported via index + `sqliteImporter`, but **no code calls it** (function had a "how to use manually" doc comment → manual utility). **Removed.** |
`productSkusRelations`, `productMarketStatsRelations`, `skuFeaturesRelations`, `productCombosRelations` (`src/db/schema.ts`) looked unreferenced but are **NOT dead** — Drizzle registers relation exports via `import * as schema` in `db_index.ts`, and `db.query.*.findMany({ with: … })` depends on them. **Kept.**
Used only inside their own file (helpers of live code — **not dead**): `parseDuplicateProductsMd` (deleted with the merge utility), `splitQuantityFeature`, `cleanFeatureValue`, `productTypeEnum`.
---
## 4. Dead / unreachable files & endpoints
| Item | File | Note |
|---|---|---|
| Expo push service | `apps/backend/src/lib/expo-service.ts` | No module imports it; its only export is uncalled |
| `av-router` | `apps/backend/src/apis/admin-apis/apis/av-router.ts` | Mounted at `/api/v1/av` but registers **zero routes** (staff-auth middleware only) |
| REST product summary | `apps/backend/src/apis/common-apis/apis/common-product.controller.ts` (`getAllProductsSummary`) | Reachable at `/api/v1/cm/products/summary`, but **no client calls it** (apps use tRPC) |
`/api/test` (`test-controller.ts`) is referenced only by `apps/fallback-ui/src/routes/demo.tsx` (a demo page).
---
## 5. Unused imports that point at dead code
| File | Unused import | Reality |
|---|---|---|
| `apps/backend/src/trpc/apis/user-apis/apis/order.ts` | `sendOrderPlacedNotification` (line 29) | Call is commented out (line 235) |
| `apps/backend/src/trpc/apis/user-apis/apis/order.ts` | `sendOrderCancelledNotification` (line 30) | Call is commented out (line 598) |
---
## 6. Commented-out / unreachable code blocks
Not "callers-less" but unreachable. Many "Old implementation" blocks were kept across the backend; the most notable registered-looking ones:
- `apps/backend/src/trpc/apis/common-apis/common.ts:160-176` — `getStoresSummary` and `healthCheck` procedures inside a `/* … */` block (NOT registered; the live ones are in `common-trpc-index.ts`).
- `apps/backend/src/main-router.ts` — `// router.route('/av', avRouter)` (route disabled).
- Numerous `// Old implementation - direct DB queries:` blocks in `admin-apis/*`, `user-apis/*`, and db helpers (historical only).
---
## 7. Checked and NOT dead (for reference)
- `apps/admin-ui` / `user-ui` / `web-ui` exports: **0 truly-unused**. 18 shared exports (`AdminOrderItemCore`, `SkuFlagCore`, `UserStoreSummaryCore`, …) are referenced only within their own file to compose other types — that's normal, not dead.
- Backend functions used only inside their own file (e.g. `cloud_cache` internals `createProductsFileInternal`, `constructCacheUrl`, `clearUrlCache`; `slot-store` `transformSlotToStoreSlot`/`extractSlotInfo`/`fetchAllTransformedSlots`; `trpc-index` `createCallerFactory`) — all reachable via their parent functions, **not dead**.
- `queue-consumer.ts` — although it imports only-in-backend, it IS used by `worker.ts`, so alive.
---
## Caveats
1. **Static analysis only.** A tRPC procedure can still be called by an external/undisclosed client (mobile build, partner integration). Confirm before removing public procedures.
2. **`mergeDuplicateProducts`** and **`expo-service`** look intentionally kept for manual/one-off use — decide whether to delete or document.
3. The `admin-web` tree is present on disk but **untracked** on this branch; it was included in the caller search.
4. Some "dead" management procedures (`staffUser.*`, duplicated `slots`/`product` entries) may be leftovers from older UI screens; safe to remove once confirmed.
## Removal status (executed)
**Removed — 15 tRPC procedures:** `admin.coupon.validate`; `admin.vendorSnippets.getById`, `getVendorOrders`; `admin.slots.getSlotsProductIds`, `updateSlotProducts`, `getSlots`, `deleteSlot`; `admin.product.updateSlotProducts`, `getSlotsProductIds`; `admin.staffUser.getUsers`, `getUserDetails`, `updateUserSuspension`; `admin.user.createUserByMobile`; `common.product.getDashboardTags`; `trpc.hello`.
**Removed — backend functions/constants:** `getJwtSecret`, `getRedisUrl`, `getExpoAccessToken`, `getPhonePeBaseUrl/ClientId/ClientVersion/ClientSecret/MerchantId`, `READABLE_ORDER_ID_KEY`, `WELCOME_MESSAGE`, `defaultRole`, `getOrderDetailsWrapper`, `clearAllCache`, `getAllBanners`, `getTagById`, `getAllTags`, `getDashboardTags`, `getProductSlots`, `getAllProductsSlots`, `getUserNegativity`, `createTRPCRouter`, `createCallerFactory`, and the notification senders `sendOrderPlacedNotification`, `sendPaymentFailedNotification`, `sendOrderOutForDeliveryNotification`, `sendOrderCancelledNotification`, `sendRefundInitiatedNotification` + their message constants.
**Removed — DB helper functions orphaned by the procedures above (from BOTH `db_helper_sqlite` and `db_helper_postgres`, plus their barrel exports and `sqliteImporter` re-exports):**
`createUserByMobile`, `deleteSlotById`, `getVendorOrders`, `updateSlotProducts`, `getSlotsProductIds` (the five behind the deleted endpoints) **and** `getActiveSlots`, `getAllUsers`, `getUserWithDetails`, `validateCoupon`, `checkUnitExists`, `getProductImagesById`, `replaceProductTags` (same class, missed by the first scan because their names also exist in the parallel package).
**Removed — files:** `apps/backend/src/lib/expo-service.ts`, `apps/backend/src/middleware/staff-auth.ts` (only used by the empty `av-router`), `apps/backend/src/apis/admin-apis/apis/av-router.ts` (empty router), `packages/db_helper_sqlite/src/admin-apis/merge-duplicate-products.ts`.
**Removed — wiring:** `avRouter` import/route from `main-router.ts` + `v1-router.ts`; `mergeDuplicateProducts` exports from `db_helper_sqlite/index.ts` and `sqliteImporter.ts`; unused `sendOrder*Notification` import + commented calls in `user-apis/order.ts`; orphaned imports in all touched files.
**Kept (false positives / intentional):** the four Drizzle relation exports (implicitly registered); `mergeDuplicateProducts` was deleted per §3.
**Verification:** `tsc` clean for `apps/backend`, `packages/db_helper_sqlite`, `apps/web-ui`, `apps/admin-ui`, `apps/user-ui`, `apps/admin-web`. (`apps/fallback-ui` has one pre-existing `vite.config.ts` error unrelated to this change.)

View file

@ -0,0 +1,464 @@
-- ============================================================
-- address-bound-coord-updates.sql
-- Generated from address_util/vague-address-bounds.txt (416 rows).
--
-- bound_id = 1: 332
-- bound_id = 2: 63
-- bound_id = NULL: 21 (blank Bound in the txt)
-- latitude/longitude updates (area coords): 130
-- vague_backfilled_coords = 1 for every row in this batch.
--
-- Every statement is idempotent and scoped to one id. Every row in the
-- batch also sets vague_backfilled_coords = 1, including the 130 rows that
-- receive area-level coordinates.
--
-- Apply:
-- wrangler d1 execute <db-name> --remote --config wrangler.prod.toml \
-- --file address_util/address-bound-coord-updates.sql
-- ============================================================
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 1;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 2;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 3;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 4;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 5;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 6;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 7;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 8;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 9;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 10;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 11;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 12;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 13;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 14;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 15;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 16;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 21;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 22;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 23;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 25;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 28;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 29;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 30;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 31;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 32;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 33;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 34;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 35;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 36;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 37;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 39;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 40;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 41;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 42;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 43;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 44;
UPDATE addresses SET bound_id = 1, latitude = 16.733798, longitude = 77.999953, vague_backfilled_coords = 1 WHERE id = 45;
UPDATE addresses SET bound_id = 2, latitude = 16.755649, longitude = 78.017013, vague_backfilled_coords = 1 WHERE id = 46;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 51;
UPDATE addresses SET bound_id = 1, latitude = 16.740450, longitude = 78.004159, vague_backfilled_coords = 1 WHERE id = 52;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 53;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 55;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 56;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 57;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 60;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 66;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 69;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 73;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 74;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 81;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 83;
UPDATE addresses SET bound_id = 2, latitude = 16.749234, longitude = 78.027886, vague_backfilled_coords = 1 WHERE id = 84;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 86;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 87;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 88;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 89;
UPDATE addresses SET bound_id = 2, latitude = 16.749234, longitude = 78.027886, vague_backfilled_coords = 1 WHERE id = 90;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 91;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 93;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 94;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 95;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 96;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 98;
UPDATE addresses SET bound_id = 1, latitude = 16.733798, longitude = 77.999953, vague_backfilled_coords = 1 WHERE id = 99;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 100;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 101;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 102;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 103;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 106;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 108;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 111;
UPDATE addresses SET bound_id = 1, latitude = 16.752972, longitude = 78.017824, vague_backfilled_coords = 1 WHERE id = 112;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 114;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 116;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 117;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 119;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 120;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 121;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 124;
UPDATE addresses SET bound_id = 1, latitude = 16.740450, longitude = 78.004159, vague_backfilled_coords = 1 WHERE id = 125;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 126;
UPDATE addresses SET bound_id = 1, latitude = 16.740450, longitude = 78.004159, vague_backfilled_coords = 1 WHERE id = 128;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 131;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 135;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 137;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 138;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 139;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 141;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 142;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 146;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 147;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 150;
UPDATE addresses SET bound_id = 1, latitude = 16.733798, longitude = 77.999953, vague_backfilled_coords = 1 WHERE id = 151;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 153;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 154;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 155;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 157;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 159;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 162;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 164;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 165;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 166;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 169;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 171;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 172;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 173;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 178;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 179;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 182;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 183;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 184;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 185;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 186;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 188;
UPDATE addresses SET bound_id = 2, vague_backfilled_coords = 1 WHERE id = 190;
UPDATE addresses SET bound_id = 2, latitude = 16.749234, longitude = 78.027886, vague_backfilled_coords = 1 WHERE id = 195;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 196;
UPDATE addresses SET bound_id = 1, latitude = 16.740450, longitude = 78.004159, vague_backfilled_coords = 1 WHERE id = 197;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 199;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 203;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 204;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 205;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 208;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 210;
UPDATE addresses SET bound_id = 2, latitude = 16.744645, longitude = 78.014443, vague_backfilled_coords = 1 WHERE id = 211;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 214;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 215;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 216;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 218;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 220;
UPDATE addresses SET bound_id = 2, vague_backfilled_coords = 1 WHERE id = 222;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 224;
UPDATE addresses SET bound_id = 1, latitude = 16.733798, longitude = 77.999953, vague_backfilled_coords = 1 WHERE id = 225;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 227;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 228;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 229;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 230;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 234;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 235;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 236;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 238;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 245;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 246;
UPDATE addresses SET bound_id = 1, latitude = 16.740450, longitude = 78.004159, vague_backfilled_coords = 1 WHERE id = 248;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 249;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 251;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 253;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 254;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 258;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 259;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 260;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 261;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 262;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 265;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 268;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 269;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 271;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 272;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 273;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 274;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 276;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 277;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 278;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 279;
UPDATE addresses SET bound_id = 1, latitude = 16.740450, longitude = 78.004159, vague_backfilled_coords = 1 WHERE id = 282;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 283;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 285;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 287;
UPDATE addresses SET bound_id = 1, latitude = 16.740450, longitude = 78.004159, vague_backfilled_coords = 1 WHERE id = 288;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 289;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 290;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 291;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 295;
UPDATE addresses SET bound_id = 1, latitude = 16.733798, longitude = 77.999953, vague_backfilled_coords = 1 WHERE id = 299;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 302;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 303;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 304;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 305;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 309;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 311;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 312;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 316;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 320;
UPDATE addresses SET bound_id = 1, latitude = 16.740450, longitude = 78.004159, vague_backfilled_coords = 1 WHERE id = 321;
UPDATE addresses SET bound_id = 2, latitude = 16.744645, longitude = 78.014443, vague_backfilled_coords = 1 WHERE id = 323;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 324;
UPDATE addresses SET bound_id = 1, latitude = 16.740450, longitude = 78.004159, vague_backfilled_coords = 1 WHERE id = 327;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 330;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 331;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 333;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 336;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 338;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 345;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 347;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 348;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 350;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 351;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 353;
UPDATE addresses SET bound_id = 2, latitude = 16.749234, longitude = 78.027886, vague_backfilled_coords = 1 WHERE id = 357;
UPDATE addresses SET bound_id = 2, vague_backfilled_coords = 1 WHERE id = 358;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 359;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 360;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 363;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 366;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 368;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 373;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 374;
UPDATE addresses SET bound_id = 2, vague_backfilled_coords = 1 WHERE id = 377;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 379;
UPDATE addresses SET bound_id = 1, latitude = 16.733798, longitude = 77.999953, vague_backfilled_coords = 1 WHERE id = 381;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 382;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 383;
UPDATE addresses SET bound_id = 2, vague_backfilled_coords = 1 WHERE id = 385;
UPDATE addresses SET bound_id = 2, latitude = 16.724600, longitude = 77.984973, vague_backfilled_coords = 1 WHERE id = 386;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 387;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 390;
UPDATE addresses SET bound_id = 1, latitude = 16.733798, longitude = 77.999953, vague_backfilled_coords = 1 WHERE id = 391;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 392;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 401;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 406;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 411;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 415;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 417;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 421;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 425;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 426;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 427;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 430;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 431;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 432;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 435;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 439;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 440;
UPDATE addresses SET bound_id = 1, latitude = 16.740450, longitude = 78.004159, vague_backfilled_coords = 1 WHERE id = 446;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 451;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 452;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 453;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 454;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 456;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 459;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 460;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 461;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 462;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 463;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 465;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 471;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 477;
UPDATE addresses SET bound_id = 2, latitude = 16.755649, longitude = 78.017013, vague_backfilled_coords = 1 WHERE id = 482;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 483;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 485;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 487;
UPDATE addresses SET bound_id = 2, vague_backfilled_coords = 1 WHERE id = 488;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 489;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 490;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 491;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 492;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 494;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 496;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 497;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 504;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 507;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 508;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 511;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 518;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 520;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 524;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 525;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 528;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 530;
UPDATE addresses SET bound_id = 2, vague_backfilled_coords = 1 WHERE id = 534;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 538;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 539;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 544;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 547;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 549;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 550;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 552;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 554;
UPDATE addresses SET bound_id = 2, vague_backfilled_coords = 1 WHERE id = 564;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 567;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 568;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 573;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 575;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 577;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 578;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 584;
UPDATE addresses SET bound_id = 1, latitude = 16.733798, longitude = 77.999953, vague_backfilled_coords = 1 WHERE id = 587;
UPDATE addresses SET bound_id = 1, latitude = 16.752972, longitude = 78.017824, vague_backfilled_coords = 1 WHERE id = 588;
UPDATE addresses SET bound_id = 1, latitude = 16.733798, longitude = 77.999953, vague_backfilled_coords = 1 WHERE id = 589;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 591;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 592;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 593;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 594;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 596;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 597;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 598;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 600;
UPDATE addresses SET bound_id = 2, vague_backfilled_coords = 1 WHERE id = 602;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 605;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 607;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 609;
UPDATE addresses SET bound_id = 2, latitude = 16.749234, longitude = 78.027886, vague_backfilled_coords = 1 WHERE id = 613;
UPDATE addresses SET bound_id = 2, latitude = 16.755649, longitude = 78.017013, vague_backfilled_coords = 1 WHERE id = 614;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 616;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 617;
UPDATE addresses SET bound_id = 2, latitude = 16.758734, longitude = 78.041012, vague_backfilled_coords = 1 WHERE id = 618;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 619;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 620;
UPDATE addresses SET bound_id = 2, latitude = 16.724600, longitude = 77.984973, vague_backfilled_coords = 1 WHERE id = 622;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 624;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 625;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 626;
UPDATE addresses SET bound_id = 2, latitude = 16.724600, longitude = 77.984973, vague_backfilled_coords = 1 WHERE id = 631;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 632;
UPDATE addresses SET bound_id = 1, latitude = 16.740450, longitude = 78.004159, vague_backfilled_coords = 1 WHERE id = 635;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 638;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 640;
UPDATE addresses SET bound_id = 2, vague_backfilled_coords = 1 WHERE id = 642;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 643;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 644;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 648;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 649;
UPDATE addresses SET bound_id = 2, latitude = 16.758734, longitude = 78.041012, vague_backfilled_coords = 1 WHERE id = 650;
UPDATE addresses SET bound_id = 1, latitude = 16.758734, longitude = 78.041012, vague_backfilled_coords = 1 WHERE id = 655;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 656;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 658;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 659;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 661;
UPDATE addresses SET bound_id = 2, latitude = 16.749234, longitude = 78.027886, vague_backfilled_coords = 1 WHERE id = 665;
UPDATE addresses SET bound_id = 2, latitude = 16.753344, longitude = 78.032133, vague_backfilled_coords = 1 WHERE id = 667;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 670;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 673;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 679;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 682;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 684;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 688;
UPDATE addresses SET bound_id = 2, vague_backfilled_coords = 1 WHERE id = 691;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 692;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 695;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 698;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 704;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 706;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 707;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 708;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 713;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 714;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 717;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 720;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 722;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 726;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 730;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 735;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 738;
UPDATE addresses SET bound_id = 1, latitude = 16.740450, longitude = 78.004159, vague_backfilled_coords = 1 WHERE id = 741;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 743;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 744;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 745;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 753;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 754;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 755;
UPDATE addresses SET bound_id = 2, latitude = 16.755649, longitude = 78.017013, vague_backfilled_coords = 1 WHERE id = 756;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 761;
UPDATE addresses SET bound_id = 1, latitude = 16.740450, longitude = 78.004159, vague_backfilled_coords = 1 WHERE id = 766;
UPDATE addresses SET bound_id = 1, latitude = 16.733798, longitude = 77.999953, vague_backfilled_coords = 1 WHERE id = 768;
UPDATE addresses SET bound_id = 2, latitude = 16.721995, longitude = 78.018658, vague_backfilled_coords = 1 WHERE id = 769;
UPDATE addresses SET bound_id = 2, vague_backfilled_coords = 1 WHERE id = 775;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 780;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 782;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 783;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 784;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 785;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 788;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 795;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 799;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 802;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 807;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 808;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 809;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 811;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 814;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 816;
UPDATE addresses SET bound_id = 1, latitude = 16.740450, longitude = 78.004159, vague_backfilled_coords = 1 WHERE id = 817;
UPDATE addresses SET bound_id = 2, latitude = 16.744645, longitude = 78.014443, vague_backfilled_coords = 1 WHERE id = 818;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 820;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 825;
UPDATE addresses SET bound_id = 2, vague_backfilled_coords = 1 WHERE id = 829;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 830;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 834;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 843;
UPDATE addresses SET bound_id = 2, latitude = 16.760099, longitude = 78.009772, vague_backfilled_coords = 1 WHERE id = 844;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 846;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 848;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 849;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 855;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 856;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 857;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 858;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 859;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 862;
UPDATE addresses SET bound_id = 1, latitude = 16.752972, longitude = 78.017824, vague_backfilled_coords = 1 WHERE id = 864;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 870;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 871;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 872;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 874;
UPDATE addresses SET bound_id = NULL, vague_backfilled_coords = 1 WHERE id = 875;
UPDATE addresses SET bound_id = 2, latitude = 16.749234, longitude = 78.027886, vague_backfilled_coords = 1 WHERE id = 877;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 882;
UPDATE addresses SET bound_id = 1, latitude = 16.733798, longitude = 77.999953, vague_backfilled_coords = 1 WHERE id = 883;
UPDATE addresses SET bound_id = 1, latitude = 16.752972, longitude = 78.017824, vague_backfilled_coords = 1 WHERE id = 886;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 887;
UPDATE addresses SET bound_id = 2, latitude = 16.754539, longitude = 78.035332, vague_backfilled_coords = 1 WHERE id = 897;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 898;
UPDATE addresses SET bound_id = 1, latitude = 16.743916, longitude = 78.012978, vague_backfilled_coords = 1 WHERE id = 900;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 903;
UPDATE addresses SET bound_id = 1, vague_backfilled_coords = 1 WHERE id = 909;
UPDATE addresses SET bound_id = 1, latitude = 16.747980, longitude = 78.005575, vague_backfilled_coords = 1 WHERE id = 912;
-- Verification (only the addressed rows):
-- SELECT COUNT(*) AS addressed,
-- SUM(bound_id = 1) AS bound_1,
-- SUM(bound_id = 2) AS bound_2,
-- SUM(bound_id IS NULL) AS bound_null,
-- SUM(vague_backfilled_coords = 1) AS vague
-- FROM addresses WHERE id IN (
-- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 21, 22, 23, 25,
-- 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44, 45, 46, 51, 52,
-- 53, 55, 56, 57, 60, 66, 69, 73, 74, 81, 83, 84, 86, 87, 88, 89, 90, 91, 93, 94,
-- 95, 96, 98, 99, 100, 101, 102, 103, 106, 108, 111, 112, 114, 116, 117, 119, 120, 121, 124, 125,
-- 126, 128, 131, 135, 137, 138, 139, 141, 142, 146, 147, 150, 151, 153, 154, 155, 157, 159, 162, 164,
-- 165, 166, 169, 171, 172, 173, 178, 179, 182, 183, 184, 185, 186, 188, 190, 195, 196, 197, 199, 203,
-- 204, 205, 208, 210, 211, 214, 215, 216, 218, 220, 222, 224, 225, 227, 228, 229, 230, 234, 235, 236,
-- 238, 245, 246, 248, 249, 251, 253, 254, 258, 259, 260, 261, 262, 265, 268, 269, 271, 272, 273, 274,
-- 276, 277, 278, 279, 282, 283, 285, 287, 288, 289, 290, 291, 295, 299, 302, 303, 304, 305, 309, 311,
-- 312, 316, 320, 321, 323, 324, 327, 330, 331, 333, 336, 338, 345, 347, 348, 350, 351, 353, 357, 358,
-- 359, 360, 363, 366, 368, 373, 374, 377, 379, 381, 382, 383, 385, 386, 387, 390, 391, 392, 401, 406,
-- 411, 415, 417, 421, 425, 426, 427, 430, 431, 432, 435, 439, 440, 446, 451, 452, 453, 454, 456, 459,
-- 460, 461, 462, 463, 465, 471, 477, 482, 483, 485, 487, 488, 489, 490, 491, 492, 494, 496, 497, 504,
-- 507, 508, 511, 518, 520, 524, 525, 528, 530, 534, 538, 539, 544, 547, 549, 550, 552, 554, 564, 567,
-- 568, 573, 575, 577, 578, 584, 587, 588, 589, 591, 592, 593, 594, 596, 597, 598, 600, 602, 605, 607,
-- 609, 613, 614, 616, 617, 618, 619, 620, 622, 624, 625, 626, 631, 632, 635, 638, 640, 642, 643, 644,
-- 648, 649, 650, 655, 656, 658, 659, 661, 665, 667, 670, 673, 679, 682, 684, 688, 691, 692, 695, 698,
-- 704, 706, 707, 708, 713, 714, 717, 720, 722, 726, 730, 735, 738, 741, 743, 744, 745, 753, 754, 755,
-- 756, 761, 766, 768, 769, 775, 780, 782, 783, 784, 785, 788, 795, 799, 802, 807, 808, 809, 811, 814,
-- 816, 817, 818, 820, 825, 829, 830, 834, 843, 844, 846, 848, 849, 855, 856, 857, 858, 859, 862, 864,
-- 870, 871, 872, 874, 875, 877, 882, 883, 886, 887, 897, 898, 900, 903, 909, 912);

View file

@ -0,0 +1,50 @@
-- Generated by address_util/backfill-address-bounds.ts
-- generated_at: 2026-10-25T06:34:01.225Z
-- source_db: /Users/mohammedshafiuddin/WebDev/freshyo/apps/backend/.wrangler/state/v3/d1/miniflare-D1DatabaseObject/da3a80bd8d2cc8f1f070a313ef55c1800da50af994fa89a51c67a6d3e1f919f2.sqlite
-- thresholds: vague_backfilled_coords excluded=true, outside=set to NULL
-- addresses: total=882 no_coords=0 vague=484 no_region_bounds=0
-- unchanged: 361
-- outside: 28
-- updates: 37
-- resolved: bound=9 (1:0, 2:9, other:0)
--
-- Run against the remote DB with the generated file:
-- wrangler d1 execute <database-name> --remote --config wrangler.prod.toml --file <this file>
--
UPDATE addresses SET bound_id = 2 WHERE id = 70;
UPDATE addresses SET bound_id = NULL WHERE id = 250;
UPDATE addresses SET bound_id = NULL WHERE id = 280;
UPDATE addresses SET bound_id = NULL WHERE id = 310;
UPDATE addresses SET bound_id = 2 WHERE id = 388;
UPDATE addresses SET bound_id = 2 WHERE id = 389;
UPDATE addresses SET bound_id = NULL WHERE id = 394;
UPDATE addresses SET bound_id = 2 WHERE id = 409;
UPDATE addresses SET bound_id = NULL WHERE id = 428;
UPDATE addresses SET bound_id = NULL WHERE id = 442;
UPDATE addresses SET bound_id = NULL WHERE id = 448;
UPDATE addresses SET bound_id = NULL WHERE id = 509;
UPDATE addresses SET bound_id = NULL WHERE id = 517;
UPDATE addresses SET bound_id = 2 WHERE id = 546;
UPDATE addresses SET bound_id = NULL WHERE id = 586;
UPDATE addresses SET bound_id = NULL WHERE id = 599;
UPDATE addresses SET bound_id = NULL WHERE id = 603;
UPDATE addresses SET bound_id = NULL WHERE id = 606;
UPDATE addresses SET bound_id = 2 WHERE id = 611;
UPDATE addresses SET bound_id = NULL WHERE id = 621;
UPDATE addresses SET bound_id = NULL WHERE id = 629;
UPDATE addresses SET bound_id = NULL WHERE id = 637;
UPDATE addresses SET bound_id = NULL WHERE id = 647;
UPDATE addresses SET bound_id = NULL WHERE id = 660;
UPDATE addresses SET bound_id = 2 WHERE id = 664;
UPDATE addresses SET bound_id = NULL WHERE id = 678;
UPDATE addresses SET bound_id = NULL WHERE id = 694;
UPDATE addresses SET bound_id = NULL WHERE id = 696;
UPDATE addresses SET bound_id = NULL WHERE id = 699;
UPDATE addresses SET bound_id = NULL WHERE id = 721;
UPDATE addresses SET bound_id = NULL WHERE id = 734;
UPDATE addresses SET bound_id = 2 WHERE id = 737;
UPDATE addresses SET bound_id = NULL WHERE id = 740;
UPDATE addresses SET bound_id = NULL WHERE id = 765;
UPDATE addresses SET bound_id = NULL WHERE id = 778;
UPDATE addresses SET bound_id = 2 WHERE id = 847;
UPDATE addresses SET bound_id = NULL WHERE id = 881;

1262
address_util/area-bounds.txt Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,568 @@
==============================================================================
AREA / LOCALITY REPORT — vague-backfilled addresses
==============================================================================
Generated: 2026-10-25 13:01 IST
Source db: apps/backend/.wrangler/state/v3/d1/miniflare-D1DatabaseObject/da3a80bd8d2cc8f1f070a313ef55c1800da50af994fa89a51c67a6d3e1f919f2.sqlite
Rows: 416 (vague_backfilled_coords = 1, region 1)
Assigned: 352 (84.6%)
No area: 64
Areas 2+: 55
Areas 1: 38
Dropped: 3 area(s) whose addresses now have admin coords: GPY Colony, Mohamadia Colony, Premnagar
==============================================================================
REPEATED AREAS (2 or more addresses)
==============================================================================
count area
------------------------------------------------------------------------------
27 Shah Saheb Gutta
23 Marlu
20 Mothinagar
14 BK Reddy Colony
12 Habeebnagar
11 Bhageeratha Colony
11 Gol Masjid
11 Ramaiah Bowli
10 Yenugonda
9 Rajendranagar
9 Veerannapet
8 Old Palamoor
7 Lakshmi Nagar Colony
7 Noor Nagar
7 Srinivas Colony
7 TD Gutta
6 BC Colony
6 Hanumanpura
6 RB Palace
5 New Town
5 Shiva Shakti Nagar
4 Brundavan Colony
4 Metugadda
4 Padmavati Colony
4 Palasa Gutta
4 Tayyab Nagar
4 Teachers Colony
4 Venkateshwara Colony
3 Bandameedhi Pally
3 Bhavani Nagar Colony
3 Boyapalli Gate
3 Ganesh Nagar
3 Madina Masjid
3 Masoodnagar
3 Old Hospital Area
3 Palkonda
3 Sagara Colony
3 Vasavi Colony
3 Yedira
2 Alipur
2 Amistapur
2 BN Reddy Colony
2 Christianpally
2 Devuni Gutta
2 Employees Colony
2 Housing Board Colony
2 Kisan Nagar
2 Kurhinishetty Colony
2 Nalbowli
2 Police Line
2 Ravindra Nagar
2 SC Colony
2 Sriram Nagar
2 Tipu Sultan Chowk
2 Vigneshwara Colony
==============================================================================
NOTABLE SPELLING / TRANSLITERATION VARIANTS
==============================================================================
Same place written in more than one way in the address data:
Shah Saheb Gutta <- Shashabgutta, Shah Sahab Gutta, Shah Shab Gutta, Shab Gutta, Shasabgutta, S.S. Gutta, S Guyta
Mothinagar <- Motinagar, Mothi Nagar (incl. "FCD gown motinagar")
Habeebnagar <- Habeeb Nagar (spacing only)
Yenugonda <- Yanugonda, Yenukonda, Yengonda, Youngunda
Bhageeratha Colony <- Bhageritha, Bhagiratha, Bhageerata, Bhageratha
Ramaiah Bowli <- Ramiah Bowli, Ramaiya Bowli, Ramaiyah Bowli, Ramiya Boli, Rama Bouli
Veerannapet <- Veeranapet, Veernapet, Veerana Pet
Lakshmi Nagar Colony <- Laxmi Nagar, Laxminagar, Laxhmenager
Masoodnagar <- Masdoos Nagar, Masdusnagar, Masoosnagar
Tayyab Nagar <- Tayaabnagar
Kurhinishetty Colony <- Kuruhini Shetty Colony
Gol Masjid <- Goal Masjid, Golmasjid
Palasa Gutta <- Palsab Gutta
Tipu Sultan Chowk <- Tippu Sultan Chowk
Boyapalli Gate <- Boyapally, Boyepally
Palkonda <- Palakonda, Palkunda
BC Colony <- B.C. Colony
Kranti Nagar <- Kranti Nager
Srinivas Colony <- Srinivasa Colony, Srinivasa Coloney
Bhavani Nagar Colony <- Bhavaninagar Colony
Padmavati Colony <- Padmavathi, Padhmmavathi
Vigneshwara Colony <- Vigneswara Colony
Shiva Shakti Nagar <- Shiva Shakthi Nagar
Rajendranagar <- Rajendra Nagar
Noor Nagar <- Noori Nagar
Nalbowli <- Nailbowli
Old Palamoor <- Palamoor, Palamour
POSSIBLY DISTINCT — similar names, kept separate
BK Reddy Colony vs BN Reddy Colony <- different initials, not merged
Christianpally vs Christian Colony
New Gunj vs Gunj / Cheruvu Gunj
Pochamma Colony vs Pochamma temple (landmark only)
==============================================================================
AREA DETAIL + SPELLING VARIANTS
==============================================================================
Shah Saheb Gutta — 27 addresses
------------------------------------------------------------------------------
5x shashabgutta ids: 154, 392, 684, 834, 872
5x shah sahab gutta ids: 169, 182, 305, 383, 487
4x shah saheb gutta ids: 492, 785, 825, 912
3x shab gutta ids: 549, 594, 811
3x shashab gutta ids: 552, 593, 607
2x s s gutta ids: 141, 682
2x shah shab gutta ids: 245, 333
1x s guyta ids: 23
1x ss gutta ids: 116
1x shahab gutta ids: 755
Marlu — 23 addresses
------------------------------------------------------------------------------
23x marlu ids: 139, 142, 146, 162, 185, 228, 230, 235, 251, 254, 289, 302 ...
Mothinagar — 20 addresses
------------------------------------------------------------------------------
14x motinagar ids: 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ...
4x mothinagar ids: 22, 216, 278, 373
2x mothi nagar ids: 30, 178
BK Reddy Colony — 14 addresses
------------------------------------------------------------------------------
7x bk reddy colony ids: 52, 197, 248, 282, 321, 327, 635
5x b k reddy colony ids: 128, 288, 741, 766, 817
1x b k ready colony ids: 125
1x bk reddy ids: 446
Habeebnagar — 12 addresses
------------------------------------------------------------------------------
8x habeeb nagar ids: 42, 66, 73, 124, 135, 166, 347, 648
4x habeebnagar ids: 108, 150, 153, 874
Bhageeratha Colony — 11 addresses
------------------------------------------------------------------------------
6x bhageeratha ids: 151, 299, 381, 391, 589, 768
1x bhageerata ids: 45
1x bhageritha ids: 99
1x bhageerath ids: 225
1x bhagiratha ids: 587
1x bhageratha ids: 883
Gol Masjid — 11 addresses
------------------------------------------------------------------------------
6x gol masjid ids: 34, 93, 120, 463, 643, 909
3x goal masjid ids: 41, 55, 83
1x gaolnl masjid ids: 51
1x golmasjid ids: 119
Ramaiah Bowli — 11 addresses
------------------------------------------------------------------------------
7x ramaiah bowli ids: 98, 131, 171, 229, 262, 320, 518
1x ramaiyah bowli ids: 348
1x rama bouli ids: 426
1x ramaiahbowli ids: 508
1x ramiya boli ids: 830
Yenugonda — 10 addresses
------------------------------------------------------------------------------
6x yenugonda ids: 539, 626, 730, 816, 843, 897
2x yanugonda ids: 415, 491
1x youngunda ids: 204
1x yenukonda ids: 490
Rajendranagar — 9 addresses
------------------------------------------------------------------------------
5x rajendra nagar ids: 258, 269, 316, 511, 738
4x rajendranagar ids: 259, 260, 497, 638
Veerannapet — 9 addresses
------------------------------------------------------------------------------
4x veerannapet ids: 489, 620, 656, 783
2x veernapet ids: 57, 91
2x veeranapet ids: 425, 544
1x veerana pet ids: 111
Old Palamoor — 8 addresses
------------------------------------------------------------------------------
8x palamoor ids: 32, 155, 165, 291, 338, 351, 494, 692
Lakshmi Nagar Colony — 7 addresses
------------------------------------------------------------------------------
3x laxminagar ids: 273, 366, 390
2x lakshmi nagar ids: 659, 849
1x laxhmenager ids: 227
1x laxmi nagar ids: 368
Noor Nagar — 7 addresses
------------------------------------------------------------------------------
6x noor nagar ids: 1, 2, 3, 21, 25, 74
1x noori nagar ids: 137
Srinivas Colony — 7 addresses
------------------------------------------------------------------------------
3x srinivas colony ids: 84, 357, 877
3x srinivasa colony ids: 90, 613, 665
1x srinivasa coloney ids: 195
TD Gutta — 7 addresses
------------------------------------------------------------------------------
4x td gutta ids: 43, 261, 276, 485
3x t d gutta ids: 36, 101, 421
BC Colony — 6 addresses
------------------------------------------------------------------------------
4x b c colony ids: 451, 452, 453, 454
2x bc colony ids: 625, 698
Hanumanpura — 6 addresses
------------------------------------------------------------------------------
3x hanumanpura ids: 234, 524, 848
2x hanuman pura ids: 196, 520
1x hanmanpura ids: 870
RB Palace — 6 addresses
------------------------------------------------------------------------------
5x rb palace ids: 100, 103, 114, 188, 203
1x rb palce ids: 577
New Town — 5 addresses
------------------------------------------------------------------------------
3x newtown ids: 268, 287, 459
1x newton ids: 218
1x new town ids: 430
Shiva Shakti Nagar — 5 addresses
------------------------------------------------------------------------------
3x shiva shakti nagar ids: 106, 507, 753
2x shiva shakthi nagar ids: 164, 616
Brundavan Colony — 4 addresses
------------------------------------------------------------------------------
3x brundavan ids: 102, 324, 360
1x brundavanam ids: 186
Metugadda — 4 addresses
------------------------------------------------------------------------------
2x mettugadda ids: 440, 846
2x metugadda ids: 567, 717
Padmavati Colony — 4 addresses
------------------------------------------------------------------------------
2x padmavati ids: 112, 588
2x padmavathi ids: 864, 886
Palasa Gutta — 4 addresses
------------------------------------------------------------------------------
1x palsabgutta ids: 483
1x palsab guta ids: 591
1x palasa gutta ids: 857
1x palsab gutta ids: 882
Tayyab Nagar — 4 addresses
------------------------------------------------------------------------------
2x tayyab nagar ids: 173, 754
1x tayaabnagar ids: 530
1x tayyabnagar ids: 554
Teachers Colony — 4 addresses
------------------------------------------------------------------------------
3x teachers colony ids: 462, 722, 795
1x teacher s colony ids: 81
Venkateshwara Colony — 4 addresses
------------------------------------------------------------------------------
2x venkateshwara colony ids: 46, 482
2x venkateswara colony ids: 614, 756
Bandameedhi Pally — 3 addresses
------------------------------------------------------------------------------
1x bandameedipalli ids: 386
1x bandamidepally ids: 622
1x bandameedhi pally ids: 631
Bhavani Nagar Colony — 3 addresses
------------------------------------------------------------------------------
2x bhavani nagar ids: 95, 199
1x bhavaninagar ids: 550
Boyapalli Gate — 3 addresses
------------------------------------------------------------------------------
2x boyapally ids: 679, 784
1x boyapalli ids: 658
Ganesh Nagar — 3 addresses
------------------------------------------------------------------------------
3x ganesh nagar ids: 312, 411, 903
Madina Masjid — 3 addresses
------------------------------------------------------------------------------
3x madina masjid ids: 88, 89, 238
Masoodnagar — 3 addresses
------------------------------------------------------------------------------
1x masdusnagar ids: 274
1x masdoos nagar ids: 290
1x masoosnagar ids: 374
Old Hospital Area — 3 addresses
------------------------------------------------------------------------------
3x old hospital ids: 330, 331, 417
Palkonda — 3 addresses
------------------------------------------------------------------------------
1x palkunda ids: 211
1x palkonda ids: 323
1x palakonda ids: 818
Sagara Colony — 3 addresses
------------------------------------------------------------------------------
3x sagara colony ids: 35, 695, 871
Vasavi Colony — 3 addresses
------------------------------------------------------------------------------
2x vasavi ids: 183, 271
1x vasavidegree ids: 220
Yedira — 3 addresses
------------------------------------------------------------------------------
2x yedira ids: 688, 799
1x edira ids: 60
Alipur — 2 addresses
------------------------------------------------------------------------------
2x alipur ids: 504, 632
Amistapur — 2 addresses
------------------------------------------------------------------------------
1x amistapur ids: 534
1x amisthapur ids: 829
BN Reddy Colony — 2 addresses
------------------------------------------------------------------------------
1x bn reddy colony ids: 279
1x b n reddy colony ids: 379
Christianpally — 2 addresses
------------------------------------------------------------------------------
1x christianpally ids: 222
1x christian palli ids: 775
Devuni Gutta — 2 addresses
------------------------------------------------------------------------------
1x devunigutta ids: 359
1x tirumala devun gutta ids: 456
Employees Colony — 2 addresses
------------------------------------------------------------------------------
2x employees colony ids: 117, 121
Housing Board Colony — 2 addresses
------------------------------------------------------------------------------
2x housing board colony ids: 568, 670
Kisan Nagar — 2 addresses
------------------------------------------------------------------------------
2x kisan nagar ids: 345, 704
Kurhinishetty Colony — 2 addresses
------------------------------------------------------------------------------
1x kuruhini shetty ids: 619
1x kurhinishetty ids: 644
Nalbowli — 2 addresses
------------------------------------------------------------------------------
1x nailbowli ids: 179
1x nal bowli ids: 272
Police Line — 2 addresses
------------------------------------------------------------------------------
2x police line ids: 431, 432
Ravindra Nagar — 2 addresses
------------------------------------------------------------------------------
1x ravindra nagar ids: 303
1x ravindranagar ids: 745
SC Colony — 2 addresses
------------------------------------------------------------------------------
1x sc colony ids: 624
1x s c colony ids: 706
Sriram Nagar — 2 addresses
------------------------------------------------------------------------------
1x sri rama colony ids: 609
1x sriram nagar ids: 713
Tipu Sultan Chowk — 2 addresses
------------------------------------------------------------------------------
2x tipu sultan chowk ids: 236, 427
Vigneshwara Colony — 2 addresses
------------------------------------------------------------------------------
2x vigneshwara ids: 304, 649
==============================================================================
ADDRESSES THAT MENTION MORE THAN ONE AREA
==============================================================================
Grouped under the first (more specific) area; the others are listed too.
id grouped under also mentions
------------------------------------------------------------------------------
98 Ramaiah Bowli One Town
101 TD Gutta Nalbowli
139 Marlu Employees Colony
146 Marlu Employees Colony
222 Christianpally Bhavani Nagar Colony
271 Vasavi Colony Yenugonda
290 Masoodnagar Gol Masjid
304 Vigneshwara Colony Marlu
333 Shah Saheb Gutta Tipu Sultan Chowk
345 Kisan Nagar Old Hospital Area
366 Lakshmi Nagar Colony Venkateshwara Colony
451 BC Colony Yenugonda
452 BC Colony Yenugonda
453 BC Colony Yenugonda
454 BC Colony Yenugonda
550 Bhavani Nagar Colony Christianpally
554 Tayyab Nagar Ramaiah Bowli, RB Palace
578 Mythri Nagar Balaji Nagar
596 New Gunj Gunj
609 Sriram Nagar Yenugonda
625 BC Colony Amistapur
649 Vigneshwara Colony Marlu
655 Pochamma Colony Yenugonda
656 Veerannapet Madina Masjid
695 Sagara Colony Yenugonda
713 Sriram Nagar Yenugonda
761 Dhanalaxmi Colony Teachers Colony
858 Chaitanya Nagar Colony Yedira
887 Marlu Shah Saheb Gutta
==============================================================================
AREAS WITH EXACTLY ONE ADDRESS
==============================================================================
AZ Colony id 401 line2: Opp municipal park az colony ground floor
Ayodhyanagar Colony id 190 line2: Junaid ku maalum hai...
Balaji Nagar id 809 line2: (blank line2)
Chaitanya Nagar Colony id 858 line2: Chaitanya nagar colony yedira road
Chinndharpally id 714 line2: (blank line2)
Christian Colony id 807 line2: (blank line2)
Dhanalaxmi Colony id 761 line2: Beside anjaneya temple and behind oak ridge school
Divitipally id 538 line2: (blank line2)
Doddalonipally id 844 line2: Masjid arafath pillamari road
Jayashankar Colony id 385 line2: Near bypass road , near chowrasta
KTR Nagar id 253 line2: (blank line2)
Kamla Nehru Colony id 743 line2: Behind Avanthi hotel,kamla nehru colony
Khaleel Chowk id 461 line2: Khaleel chok
Kidwaipet id 673 line2: Old bustand
Kranti Nagar id 618 line2: (blank line2)
Madhuranagar Colony id 295 line2: (blank line2)
Madugu Nagar Colony id 600 line2: Madugu nagar colony opp Hanuman temple
Manikonda id 875 line2: Manikonda
Manyamkonda id 159 line2: (blank line2)
Maruthi Nagar id 708 line2: Maruthi Nagar road number 2
Mythri Nagar id 578 line2: House no 14-4-186-C
Nagireddy Colony id 575 line2: Road number 5
New Gate id 460 line2: Ali Masjid
New Gunj id 596 line2: New gunj
One Town id 172 line2: 1 town back side alis mart colony
Panchowrastha id 56 line2: Panchowrastha
Pasula Kistta Reddy Colony id 283 line2: (blank line2)
Pochamma Colony id 655 line2: (blank line2)
Pragathi Nagar id 309 line2: Near park
Raj Colony id 406 line2: Right second house
Sathyamanna Colony id 650 line2: (blank line2)
Siddarth Nagar id 769 line2: Back side eenadu office
Subhash Nagar id 782 line2: (blank line2)
Talab Katta id 44 line2: Talab katta
Veepurigeri id 780 line2: Near Hanuman temple
Veerabhadra Colony id 592 line2: Patha gate mahabubnagar
Vinayaka Nagar id 642 line2: Vinayaka nagar colony mahabubnagar bypass road str
Vivekananda Colony id 667 line2: Near ram reddy eye hospital
==============================================================================
NO AREA DETECTED (landmark / junk / city only)
==============================================================================
id 28 line2: H line1: Hh
id 29 line2: H line1: Hh
id 31 line2: 11 line1: 1-10
id 33 line2: (blank line2) line1: Yogi tiffin
id 37 line2: (blank line2) line1: Hjuu
id 39 line2: (blank line2) line1: near bharath talkies road,beside punjab bakery
id 40 line2: Address line 2 optional line1: Address line 1
id 53 line2: Opp golbanglaw beside royal cement n steel line1: House no 1-1-77/b/3
id 69 line2: Fz water plant patel masjid line1: 3-11-137/A/11Veernapet shareef calony
id 86 line2: (blank line2) line1: Balaji convention hall
id 87 line2: (blank line2) line1: rayeesa masjid trasfaram mbnr
id 94 line2: Near, Masjid e Mustafa line1: H.no 14-8-121
id 96 line2: (blank line2) line1: Opposite of Malabar gold and diamonds
id 126 line2: Opp rayeesa masjid line line1: H.no.5-7-30/L/10/C
id 138 line2: Pasula kistta reddy colony line1: 14_6_13/9/a2
id 147 line2: 1-10-87/3/A line1: 1-10-87/3/A
id 157 line2: Beside masjid e ibrahim back road line1: 14-6-14/6
id 184 line2: (blank line2) line1: 1-10-95/A/5 Behind Cosmic Sanitary Near Graveyard Main Gate
id 205 line2: (blank line2) line1: Near karishma kiranam
id 208 line2: Just opposite to dmart nallagandla line1: A 2004,aprna sarovar zenith near neo mall
id 210 line2: (blank line2) line1: Opposite pragna high school
id 214 line2: (blank line2) line1: C-71
id 215 line2: Near daksha high school line1: Malabargold beside lane
id 224 line2: 5-7-35/l/9 line1: Khaja kiranam
id 246 line2: Imran kiranam line1: Pochamma temple
id 249 line2: (blank line2) line1: Near Almas function hall
id 277 line2: Dargah line1: 5-64/c
id 285 line2: Mbnr line1: Mbnr
id 311 line2: H.no.1-10-19/3/6/a line1: Two taps
id 336 line2: (blank line2) line1: N
id 350 line2: (blank line2) line1: Neat o baby store
id 358 line2: (blank line2) line1: SVS medical collage pg boys hostel
id 363 line2: (blank line2) line1: Mahabubnagar
id 377 line2: (blank line2) line1: SVS staff quarters 303
id 382 line2: (blank line2) line1: Near fareed madarsa street no. 3
id 387 line2: Sofiya masjid line1: Devar katra raad
id 435 line2: Opp Hdfc bank Standard Electrical line1: 5-4-102 ,Taj-Un-Najm,
id 439 line2: Beside iron shop green gate 1st floor line1: 2-9-15 expert high school lane opposite transformer
id 465 line2: Near asif kiranam store line1: Basravi function hall
id 471 line2: Police headcoutar line1: Monappagutta chai duniya
id 477 line2: Grave yard line1: Behind Cosmic sanitary
id 488 line2: (blank line2) line1: Panchavati school
id 496 line2: Bsn Reddy apartment 1 flour line1: Goutam hospital opposite
id 525 line2: Ground floor line1: Near navodaya hospital
id 547 line2: (blank line2) line1: Mlm na 😜
id 564 line2: (blank line2) line1: Flat no 3007 3rd floor PBR Residency
id 573 line2: Near Nalanda Auto Stand line1: F.n.414,Metropolis Manatown Aprtment
id 602 line2: Shivalayam temple road line1: Near Fathima Vidyalayam school,
id 605 line2: (blank line2) line1: Near janatha garrage
id 640 line2: Old Central library line1: Old Central library
id 691 line2: Near svs near hospital and college line1: Sai ram mess
id 707 line2: (blank line2) line1: 14-11-8/5/2 near mi Eden plaza function hall
id 726 line2: Dk aruna downstreet line1: Bangaru mysamma temple opp street
id 735 line2: Meraj masjid gate opposite lane line1: Saddalgundu
id 744 line2: Opposite Gayatri appartment line1: Aleem trader's
id 788 line2: Near pista House bypass 🛣️ line1: PBR residency 3rd floor b block 3016
id 808 line2: Hanuman temple line1: Svdc college back side Hanuman temple
id 814 line2: Near srikrishna theatre mahabubnagar line1: Aleem traders opposite Gayatri appartment
id 820 line2: (blank line2) line1: Samreen chicken center
id 855 line2: Opposite Sarika township flat no.505 line1: Giridhari construction , green meridian county
id 856 line2: Opposite Sarika township line1: Giridhari construction green meridian apartment
id 859 line2: Akbar masjid road line1: Mg functional
id 862 line2: Near nalanda auto stand line1: Kakatiya techno school
id 898 line2: (blank line2) line1: Habeeb manzil
==============================================================================

View file

@ -0,0 +1,378 @@
#!/usr/bin/env bun
/**
* backfill-address-bounds — one-off data script (LOCAL DB -> SQL file).
*
* Reads a LOCAL SQLite copy of the D1 database, resolves every address to the
* bound of its region that contains its coordinates (lowest priority wins,
* exactly like `resolveRegionAndBound` in src/lib/region-geo.ts), and emits a
* plain SQL file:
*
* UPDATE addresses SET bound_id = 2 WHERE id = 123;
*
* Run the generated file against the remote DB yourself:
*
* wrangler d1 execute <database-name> --remote \
* --config wrangler.prod.toml --file address-bound-updates.sql
*
* Usage (from the repo root):
*
* bun run address_util/backfill-address-bounds.ts
* bun run address_util/backfill-address-bounds.ts --db apps/backend/dumps/copy.sqlite \
* --out /tmp/address-bound-updates.sql
* bun run address_util/backfill-address-bounds.ts --include-vague
* bun run address_util/backfill-address-bounds.ts --keep-outside
*
* Options:
* --db <path> Local SQLite file. Default: auto-discovers the D1 file
* under .wrangler/state/v3/d1/miniflare-D1DatabaseObject.
* --out <path> Output .sql file. Default: address_util/address-bound-updates.sql
* --include-vague Also resolve addresses whose coordinates are the migration's
* fabricated region centre (vague_backfilled_coords = 1).
* --keep-outside Do not touch addresses that fall outside every polygon.
* Default: set bound_id = NULL for them.
* --help Show this help.
*
* Nothing is written to the database: the only side effect is the .sql file.
*/
import { Database } from 'bun:sqlite'
import { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import { booleanPointInPolygon } from '@turf/boolean-point-in-polygon'
import { point as turfPoint, polygon as turfPolygon } from '@turf/helpers'
const USAGE = `backfill-address-bounds — emit UPDATE statements for addresses.bound_id
Usage:
bun run address_util/backfill-address-bounds.ts [options]
Options:
--db <path> Local SQLite file (default: auto-discover .wrangler D1 file)
--out <path> Output .sql file (default: address_util/address-bound-updates.sql)
--include-vague Include vague_backfilled_coords = 1 rows
--keep-outside Leave addresses that fall outside all polygons untouched
--help Show this help
`
const argv = process.argv.slice(2)
const has = (name: string) => argv.includes(`--${name}`)
if (has('help') || has('h')) {
console.log(USAGE)
process.exit(0)
}
function option(name: string): string | undefined {
const eq = argv.find((arg) => arg.startsWith(`--${name}=`))
if (eq) return eq.slice(name.length + 3)
const index = argv.indexOf(`--${name}`)
if (index !== -1 && argv[index + 1] && !argv[index + 1].startsWith('--')) {
return argv[index + 1]
}
return undefined
}
const REPO_ROOT = resolve(import.meta.dir, '..')
const BACKEND_DIR = join(REPO_ROOT, 'apps/backend')
const includeVague = has('include-vague')
const keepOutside = has('keep-outside')
/* -------------------------------------------------------------------------- */
/* Resolve the local DB + output paths */
/* -------------------------------------------------------------------------- */
function discoverLocalDb(): string {
const d1Dir = join(BACKEND_DIR, '.wrangler/state/v3/d1/miniflare-D1DatabaseObject')
if (!existsSync(d1Dir)) {
throw new Error(`No local D1 directory at ${d1Dir}. Pass --db <path>.`)
}
const files = readdirSync(d1Dir).filter(
(file) => file.endsWith('.sqlite') && !file.startsWith('metadata')
)
for (const file of files) {
const fullPath = join(d1Dir, file)
try {
// Opened read-write: a WAL database cannot be opened read-only when the
// `-shm` file is absent (server stopped). This script never writes.
const db = new Database(fullPath)
const columns = db
.query("PRAGMA table_info('addresses')")
.all() as Array<{ name: string }>
db.close()
const names = new Set(columns.map((column) => column.name))
if (names.has('bound_id') && names.has('vague_backfilled_coords')) {
return fullPath
}
} catch {
// not a database this script can use; try the next one
}
}
throw new Error(
`No local D1 SQLite file with addresses.bound_id + vague_backfilled_coords under ${d1Dir}. ` +
`Pass --db <path>. Files found: ${files.join(', ') || '(none)'}`
)
}
const dbPath = resolve(option('db') ?? discoverLocalDb())
const outPath = resolve(option('out') ?? join(import.meta.dir, 'address-bound-updates.sql'))
if (!existsSync(dbPath)) {
throw new Error(`SQLite file not found: ${dbPath}`)
}
/* -------------------------------------------------------------------------- */
/* Load rows */
/* -------------------------------------------------------------------------- */
interface BoundRow {
id: number
region_id: number
priority: number
geojson: string | null
}
interface AddressRow {
id: number
region_id: number | null
latitude: number | null
longitude: number | null
bound_id: number | null
vague: number
}
const db = new Database(dbPath)
const addressColumns = (
db.query("PRAGMA table_info('addresses')").all() as Array<{ name: string }>
).map((column) => column.name)
for (const required of ['id', 'region_id', 'latitude', 'longitude', 'bound_id']) {
if (!addressColumns.includes(required)) {
throw new Error(
`addresses.${required} is missing in ${dbPath}. This script expects the regionalized schema.`
)
}
}
const hasVagueColumn = addressColumns.includes('vague_backfilled_coords')
const bounds = db
.query(
`SELECT id, region_id, CAST(priority AS REAL) AS priority, geojson
FROM region_bounds
WHERE geojson IS NOT NULL
ORDER BY region_id ASC, priority ASC, id ASC`
)
.all() as BoundRow[]
const addresses = db
.query(
`SELECT id, region_id, latitude, longitude, bound_id, ${
hasVagueColumn ? 'vague_backfilled_coords' : '0'
} AS vague
FROM addresses
ORDER BY id ASC`
)
.all() as AddressRow[]
db.close()
/* -------------------------------------------------------------------------- */
/* Turn every bound into turf polygons (identical to boundToPolygons) */
/* -------------------------------------------------------------------------- */
type TurfPolygon = ReturnType<typeof turfPolygon>
interface PreparedBound {
id: number
regionId: number
priority: number
polygons: TurfPolygon[]
}
let invalidGeometries = 0
function polygonsOf(geojson: string): TurfPolygon[] {
const polygons: TurfPolygon[] = []
let parsed: any
try {
parsed = JSON.parse(geojson)
} catch {
invalidGeometries += 1
return polygons
}
for (const feature of parsed?.features ?? []) {
const geometry = feature?.geometry
if (!geometry) continue
if (geometry.type === 'Polygon') {
polygons.push(turfPolygon(geometry.coordinates))
} else if (geometry.type === 'MultiPolygon') {
for (const coordinates of geometry.coordinates) {
polygons.push(turfPolygon(coordinates))
}
}
}
return polygons
}
const boundsByRegion = new Map<number, PreparedBound[]>()
for (const bound of bounds) {
const prepared: PreparedBound = {
id: bound.id,
regionId: bound.region_id,
priority: Number(bound.priority),
polygons: polygonsOf(bound.geojson!),
}
if (prepared.polygons.length === 0) continue
const list = boundsByRegion.get(prepared.regionId) ?? []
list.push(prepared)
boundsByRegion.set(prepared.regionId, list)
}
for (const list of boundsByRegion.values()) {
list.sort((a, b) => a.priority - b.priority || a.id - b.id)
}
/* -------------------------------------------------------------------------- */
/* Resolve + build the UPDATE statements */
/* -------------------------------------------------------------------------- */
type Resolution =
| { kind: 'bound'; boundId: number }
| { kind: 'outside' }
| { kind: 'no-bounds' }
function resolveBound(address: AddressRow): Resolution {
if (address.region_id == null) return { kind: 'no-bounds' }
const candidates = boundsByRegion.get(address.region_id)
if (!candidates || candidates.length === 0) return { kind: 'no-bounds' }
const location = turfPoint([address.longitude!, address.latitude!])
for (const bound of candidates) {
if (bound.polygons.some((poly) => booleanPointInPolygon(location, poly))) {
return { kind: 'bound', boundId: bound.id }
}
}
return { kind: 'outside' }
}
const updates: string[] = []
const stats = {
total: addresses.length,
skippedNoCoords: 0,
skippedVague: 0,
skippedNoBounds: 0,
unchanged: 0,
outside: 0,
outsideKept: 0,
bound1: 0,
bound2: 0,
boundOther: 0,
}
const perBound = new Map<number, number[]>()
for (const address of addresses) {
if (address.latitude == null || address.longitude == null) {
stats.skippedNoCoords += 1
continue
}
if (address.vague === 1 && !includeVague) {
stats.skippedVague += 1
continue
}
const resolution = resolveBound(address)
if (resolution.kind === 'no-bounds') {
stats.skippedNoBounds += 1
continue
}
if (resolution.kind === 'outside') {
stats.outside += 1
if (keepOutside) {
stats.outsideKept += 1
continue
}
if (address.bound_id == null) {
stats.unchanged += 1
continue
}
updates.push(`UPDATE addresses SET bound_id = NULL WHERE id = ${address.id};`)
continue
}
if (address.bound_id === resolution.boundId) {
stats.unchanged += 1
continue
}
if (resolution.boundId === 1) stats.bound1 += 1
else if (resolution.boundId === 2) stats.bound2 += 1
else stats.boundOther += 1
const list = perBound.get(resolution.boundId) ?? []
list.push(address.id)
perBound.set(resolution.boundId, list)
updates.push(
`UPDATE addresses SET bound_id = ${resolution.boundId} WHERE id = ${address.id};`
)
}
/* -------------------------------------------------------------------------- */
/* Emit the SQL file */
/* -------------------------------------------------------------------------- */
const generatedAt = new Date().toISOString()
const outsideMode = keepOutside ? 'kept as-is' : 'set to NULL'
const header = [
'-- Generated by address_util/backfill-address-bounds.ts',
`-- generated_at: ${generatedAt}`,
`-- source_db: ${dbPath}`,
`-- thresholds: vague_backfilled_coords excluded=${!includeVague}, outside=${outsideMode}`,
`-- addresses: total=${stats.total} no_coords=${stats.skippedNoCoords} vague=${stats.skippedVague} no_region_bounds=${stats.skippedNoBounds}`,
`-- unchanged: ${stats.unchanged}`,
`-- outside: ${stats.outside}${keepOutside ? ` (kept ${stats.outsideKept})` : ''}`,
`-- updates: ${updates.length}`,
`-- resolved: bound=${stats.bound1 + stats.bound2 + stats.boundOther} (1:${stats.bound1}, 2:${stats.bound2}, other:${stats.boundOther})`,
'--',
'-- Run against the remote DB with the generated file:',
'-- wrangler d1 execute <database-name> --remote --config wrangler.prod.toml --file <this file>',
'--',
'',
].join('\n')
const body = updates.length > 0 ? updates.join('\n') + '\n' : '-- nothing to update\n'
mkdirSync(dirname(outPath), { recursive: true })
writeFileSync(outPath, header + body, 'utf8')
/* -------------------------------------------------------------------------- */
/* Report */
/* -------------------------------------------------------------------------- */
console.log(`source db : ${dbPath}`)
console.log(`output : ${outPath}`)
console.log(
`addresses : ${stats.total} (no coords ${stats.skippedNoCoords}, vague ${stats.skippedVague}, no region bounds ${stats.skippedNoBounds})`
)
console.log(`outside : ${stats.outside} (${outsideMode})`)
console.log(`unchanged : ${stats.unchanged}`)
console.log(
`updates : ${updates.length}` +
(perBound.size
? ` (${[...perBound.entries()]
.sort((a, b) => a[0] - b[0])
.map(([boundId, ids]) => `bound ${boundId}: ${ids.length}`)
.join(', ')})`
: '')
)
if (invalidGeometries > 0) {
console.warn(`warning : ${invalidGeometries} bound geometry row(s) were not valid JSON; skipped.`)
}
console.log('')
console.log('Apply it with:')
console.log(
` wrangler d1 execute <database-name> --remote --config wrangler.prod.toml --file "${outPath}"`
)

View file

@ -0,0 +1,59 @@
-- ============================================================
-- backfill-admin-coords.sql
--
-- Prefer the admin-pinned coordinates over the user coordinates, and use the
-- Mahabubnagar region centre ("vague" coords) only when neither is available.
-- Mirrors the `__new_addresses` copy in
-- packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql.
--
-- Safe to re-run (every statement is idempotent).
--
-- Local:
-- wrangler d1 execute <db-name> --local --file address_util/backfill-admin-coords.sql
-- Remote:
-- wrangler d1 execute <db-name> --remote --config wrangler.prod.toml \
-- --file address_util/backfill-admin-coords.sql
-- ============================================================
-- 1) Both admin coordinates present: admin wins, even when the user's
-- latitude/longitude are also present. The row is no longer "vague".
UPDATE addresses
SET latitude = admin_latitude,
longitude = admin_longitude,
vague_backfilled_coords = 0
WHERE admin_latitude IS NOT NULL
AND admin_longitude IS NOT NULL;
-- 2) Only admin latitude present: take it. The longitude keeps whatever it had;
-- vague is left untouched because that longitude may still be the fabricated
-- region centre. (No such rows in the current DB.)
UPDATE addresses
SET latitude = admin_latitude
WHERE admin_latitude IS NOT NULL
AND admin_longitude IS NULL;
-- 3) Only admin longitude present: take it. (No such rows in the current DB.)
UPDATE addresses
SET longitude = admin_longitude
WHERE admin_longitude IS NOT NULL
AND admin_latitude IS NULL;
-- 4) No admin coordinates and a missing coordinate: backfill the Mahabubnagar
-- region centre and mark the row vague. (No such rows in the current DB;
-- kept so the rule is complete on other/future databases.)
UPDATE addresses
SET latitude = COALESCE(latitude, 16.750504),
longitude = COALESCE(longitude, 77.993621),
vague_backfilled_coords = 1
WHERE admin_latitude IS NULL
AND admin_longitude IS NULL
AND (latitude IS NULL OR longitude IS NULL);
-- Verify:
-- SELECT
-- SUM(vague_backfilled_coords = 1) AS vague,
-- SUM(admin_latitude IS NOT NULL AND admin_longitude IS NOT NULL) AS admin_rows,
-- SUM(admin_latitude IS NOT NULL AND admin_longitude IS NOT NULL
-- AND vague_backfilled_coords = 1) AS admin_still_vague
-- FROM addresses;
-- Expected after this file: admin_still_vague = 0.

View file

@ -0,0 +1,486 @@
-- ============================================================
-- computed-bounds-466.sql
--
-- 466 addresses that already had real coordinates before the manual vague review:
-- * 398 with real latitude/longitude (vague_backfilled_coords = 0)
-- * 68 whose admin coords replaced the vague region centre
--
-- Generated by address_util/backfill-address-bounds.ts (turf, same logic as
-- resolveRegionAndBound). The 416 vague rows are NOT included and are left untouched.
--
-- Note: the script ran against a throwaway copy with bound_id = 0 for these rows,
-- so every row is emitted below (otherwise bound-1 rows would be omitted as no-ops).
--
-- Result: bound 1 = 432, bound 2 = 12, outside both polygons = 22 (NULL)
--
-- Apply:
-- wrangler d1 execute <db-name> --remote --config wrangler.prod.toml \
-- --file address_util/computed-bounds-466.sql
-- ============================================================
UPDATE addresses SET bound_id = 1 WHERE id = 20;
UPDATE addresses SET bound_id = 1 WHERE id = 24;
UPDATE addresses SET bound_id = 1 WHERE id = 26;
UPDATE addresses SET bound_id = 1 WHERE id = 38;
UPDATE addresses SET bound_id = 1 WHERE id = 50;
UPDATE addresses SET bound_id = 1 WHERE id = 54;
UPDATE addresses SET bound_id = 1 WHERE id = 58;
UPDATE addresses SET bound_id = 1 WHERE id = 59;
UPDATE addresses SET bound_id = 1 WHERE id = 67;
UPDATE addresses SET bound_id = 2 WHERE id = 70;
UPDATE addresses SET bound_id = 1 WHERE id = 71;
UPDATE addresses SET bound_id = 1 WHERE id = 72;
UPDATE addresses SET bound_id = 1 WHERE id = 82;
UPDATE addresses SET bound_id = 1 WHERE id = 85;
UPDATE addresses SET bound_id = 1 WHERE id = 92;
UPDATE addresses SET bound_id = 1 WHERE id = 104;
UPDATE addresses SET bound_id = 1 WHERE id = 105;
UPDATE addresses SET bound_id = 1 WHERE id = 107;
UPDATE addresses SET bound_id = 1 WHERE id = 109;
UPDATE addresses SET bound_id = 1 WHERE id = 110;
UPDATE addresses SET bound_id = 1 WHERE id = 113;
UPDATE addresses SET bound_id = 1 WHERE id = 115;
UPDATE addresses SET bound_id = 1 WHERE id = 118;
UPDATE addresses SET bound_id = 1 WHERE id = 122;
UPDATE addresses SET bound_id = 1 WHERE id = 123;
UPDATE addresses SET bound_id = 1 WHERE id = 127;
UPDATE addresses SET bound_id = 1 WHERE id = 129;
UPDATE addresses SET bound_id = 1 WHERE id = 130;
UPDATE addresses SET bound_id = 1 WHERE id = 132;
UPDATE addresses SET bound_id = 1 WHERE id = 133;
UPDATE addresses SET bound_id = 1 WHERE id = 134;
UPDATE addresses SET bound_id = 1 WHERE id = 136;
UPDATE addresses SET bound_id = 1 WHERE id = 140;
UPDATE addresses SET bound_id = 1 WHERE id = 143;
UPDATE addresses SET bound_id = 1 WHERE id = 144;
UPDATE addresses SET bound_id = 1 WHERE id = 145;
UPDATE addresses SET bound_id = 1 WHERE id = 148;
UPDATE addresses SET bound_id = 1 WHERE id = 149;
UPDATE addresses SET bound_id = 1 WHERE id = 152;
UPDATE addresses SET bound_id = 1 WHERE id = 156;
UPDATE addresses SET bound_id = 1 WHERE id = 158;
UPDATE addresses SET bound_id = 1 WHERE id = 160;
UPDATE addresses SET bound_id = 1 WHERE id = 161;
UPDATE addresses SET bound_id = 1 WHERE id = 163;
UPDATE addresses SET bound_id = 1 WHERE id = 167;
UPDATE addresses SET bound_id = 1 WHERE id = 168;
UPDATE addresses SET bound_id = 1 WHERE id = 170;
UPDATE addresses SET bound_id = 1 WHERE id = 174;
UPDATE addresses SET bound_id = 1 WHERE id = 175;
UPDATE addresses SET bound_id = 1 WHERE id = 176;
UPDATE addresses SET bound_id = 1 WHERE id = 177;
UPDATE addresses SET bound_id = 1 WHERE id = 180;
UPDATE addresses SET bound_id = 1 WHERE id = 181;
UPDATE addresses SET bound_id = 1 WHERE id = 187;
UPDATE addresses SET bound_id = 1 WHERE id = 189;
UPDATE addresses SET bound_id = 1 WHERE id = 191;
UPDATE addresses SET bound_id = 1 WHERE id = 192;
UPDATE addresses SET bound_id = 1 WHERE id = 193;
UPDATE addresses SET bound_id = 1 WHERE id = 194;
UPDATE addresses SET bound_id = 1 WHERE id = 198;
UPDATE addresses SET bound_id = 1 WHERE id = 200;
UPDATE addresses SET bound_id = 1 WHERE id = 201;
UPDATE addresses SET bound_id = 1 WHERE id = 202;
UPDATE addresses SET bound_id = 1 WHERE id = 206;
UPDATE addresses SET bound_id = 1 WHERE id = 207;
UPDATE addresses SET bound_id = 1 WHERE id = 209;
UPDATE addresses SET bound_id = 1 WHERE id = 212;
UPDATE addresses SET bound_id = 1 WHERE id = 213;
UPDATE addresses SET bound_id = 1 WHERE id = 217;
UPDATE addresses SET bound_id = 1 WHERE id = 221;
UPDATE addresses SET bound_id = 1 WHERE id = 223;
UPDATE addresses SET bound_id = 1 WHERE id = 226;
UPDATE addresses SET bound_id = 1 WHERE id = 231;
UPDATE addresses SET bound_id = 1 WHERE id = 233;
UPDATE addresses SET bound_id = 1 WHERE id = 237;
UPDATE addresses SET bound_id = 1 WHERE id = 239;
UPDATE addresses SET bound_id = 1 WHERE id = 240;
UPDATE addresses SET bound_id = 1 WHERE id = 241;
UPDATE addresses SET bound_id = 1 WHERE id = 242;
UPDATE addresses SET bound_id = 1 WHERE id = 243;
UPDATE addresses SET bound_id = 1 WHERE id = 244;
UPDATE addresses SET bound_id = 1 WHERE id = 247;
UPDATE addresses SET bound_id = NULL WHERE id = 250;
UPDATE addresses SET bound_id = 1 WHERE id = 252;
UPDATE addresses SET bound_id = 1 WHERE id = 255;
UPDATE addresses SET bound_id = 1 WHERE id = 256;
UPDATE addresses SET bound_id = 1 WHERE id = 263;
UPDATE addresses SET bound_id = 1 WHERE id = 264;
UPDATE addresses SET bound_id = 1 WHERE id = 266;
UPDATE addresses SET bound_id = 1 WHERE id = 267;
UPDATE addresses SET bound_id = 1 WHERE id = 270;
UPDATE addresses SET bound_id = 1 WHERE id = 275;
UPDATE addresses SET bound_id = NULL WHERE id = 280;
UPDATE addresses SET bound_id = 1 WHERE id = 281;
UPDATE addresses SET bound_id = 1 WHERE id = 284;
UPDATE addresses SET bound_id = 1 WHERE id = 286;
UPDATE addresses SET bound_id = 1 WHERE id = 292;
UPDATE addresses SET bound_id = 1 WHERE id = 293;
UPDATE addresses SET bound_id = 1 WHERE id = 294;
UPDATE addresses SET bound_id = 1 WHERE id = 296;
UPDATE addresses SET bound_id = 1 WHERE id = 297;
UPDATE addresses SET bound_id = 1 WHERE id = 298;
UPDATE addresses SET bound_id = 1 WHERE id = 300;
UPDATE addresses SET bound_id = 1 WHERE id = 301;
UPDATE addresses SET bound_id = 1 WHERE id = 306;
UPDATE addresses SET bound_id = 1 WHERE id = 307;
UPDATE addresses SET bound_id = 1 WHERE id = 308;
UPDATE addresses SET bound_id = NULL WHERE id = 310;
UPDATE addresses SET bound_id = 1 WHERE id = 313;
UPDATE addresses SET bound_id = 1 WHERE id = 314;
UPDATE addresses SET bound_id = 1 WHERE id = 315;
UPDATE addresses SET bound_id = 1 WHERE id = 317;
UPDATE addresses SET bound_id = 1 WHERE id = 318;
UPDATE addresses SET bound_id = 1 WHERE id = 319;
UPDATE addresses SET bound_id = 1 WHERE id = 322;
UPDATE addresses SET bound_id = 1 WHERE id = 325;
UPDATE addresses SET bound_id = 1 WHERE id = 326;
UPDATE addresses SET bound_id = 1 WHERE id = 328;
UPDATE addresses SET bound_id = 1 WHERE id = 329;
UPDATE addresses SET bound_id = 1 WHERE id = 332;
UPDATE addresses SET bound_id = 1 WHERE id = 334;
UPDATE addresses SET bound_id = 1 WHERE id = 335;
UPDATE addresses SET bound_id = 1 WHERE id = 337;
UPDATE addresses SET bound_id = 1 WHERE id = 339;
UPDATE addresses SET bound_id = 1 WHERE id = 340;
UPDATE addresses SET bound_id = 1 WHERE id = 341;
UPDATE addresses SET bound_id = 1 WHERE id = 342;
UPDATE addresses SET bound_id = 1 WHERE id = 343;
UPDATE addresses SET bound_id = 1 WHERE id = 344;
UPDATE addresses SET bound_id = 1 WHERE id = 346;
UPDATE addresses SET bound_id = 1 WHERE id = 349;
UPDATE addresses SET bound_id = 1 WHERE id = 352;
UPDATE addresses SET bound_id = 1 WHERE id = 354;
UPDATE addresses SET bound_id = 1 WHERE id = 355;
UPDATE addresses SET bound_id = 1 WHERE id = 356;
UPDATE addresses SET bound_id = 1 WHERE id = 361;
UPDATE addresses SET bound_id = 1 WHERE id = 362;
UPDATE addresses SET bound_id = 1 WHERE id = 364;
UPDATE addresses SET bound_id = 1 WHERE id = 365;
UPDATE addresses SET bound_id = 1 WHERE id = 367;
UPDATE addresses SET bound_id = 1 WHERE id = 369;
UPDATE addresses SET bound_id = 1 WHERE id = 370;
UPDATE addresses SET bound_id = 1 WHERE id = 371;
UPDATE addresses SET bound_id = 1 WHERE id = 372;
UPDATE addresses SET bound_id = 1 WHERE id = 375;
UPDATE addresses SET bound_id = 1 WHERE id = 376;
UPDATE addresses SET bound_id = 1 WHERE id = 378;
UPDATE addresses SET bound_id = 1 WHERE id = 380;
UPDATE addresses SET bound_id = 1 WHERE id = 384;
UPDATE addresses SET bound_id = 2 WHERE id = 388;
UPDATE addresses SET bound_id = 2 WHERE id = 389;
UPDATE addresses SET bound_id = 1 WHERE id = 393;
UPDATE addresses SET bound_id = NULL WHERE id = 394;
UPDATE addresses SET bound_id = 1 WHERE id = 395;
UPDATE addresses SET bound_id = 1 WHERE id = 396;
UPDATE addresses SET bound_id = 1 WHERE id = 397;
UPDATE addresses SET bound_id = 1 WHERE id = 398;
UPDATE addresses SET bound_id = 1 WHERE id = 399;
UPDATE addresses SET bound_id = 1 WHERE id = 400;
UPDATE addresses SET bound_id = 1 WHERE id = 402;
UPDATE addresses SET bound_id = 1 WHERE id = 403;
UPDATE addresses SET bound_id = 1 WHERE id = 404;
UPDATE addresses SET bound_id = 1 WHERE id = 405;
UPDATE addresses SET bound_id = 1 WHERE id = 407;
UPDATE addresses SET bound_id = 1 WHERE id = 408;
UPDATE addresses SET bound_id = 2 WHERE id = 409;
UPDATE addresses SET bound_id = 1 WHERE id = 410;
UPDATE addresses SET bound_id = 1 WHERE id = 412;
UPDATE addresses SET bound_id = 1 WHERE id = 416;
UPDATE addresses SET bound_id = 1 WHERE id = 418;
UPDATE addresses SET bound_id = 1 WHERE id = 419;
UPDATE addresses SET bound_id = 1 WHERE id = 422;
UPDATE addresses SET bound_id = 1 WHERE id = 423;
UPDATE addresses SET bound_id = 1 WHERE id = 424;
UPDATE addresses SET bound_id = 1 WHERE id = 428;
UPDATE addresses SET bound_id = 1 WHERE id = 429;
UPDATE addresses SET bound_id = 1 WHERE id = 433;
UPDATE addresses SET bound_id = 1 WHERE id = 436;
UPDATE addresses SET bound_id = 1 WHERE id = 437;
UPDATE addresses SET bound_id = 1 WHERE id = 441;
UPDATE addresses SET bound_id = 1 WHERE id = 442;
UPDATE addresses SET bound_id = 1 WHERE id = 443;
UPDATE addresses SET bound_id = 1 WHERE id = 444;
UPDATE addresses SET bound_id = 1 WHERE id = 445;
UPDATE addresses SET bound_id = 1 WHERE id = 447;
UPDATE addresses SET bound_id = NULL WHERE id = 448;
UPDATE addresses SET bound_id = 1 WHERE id = 449;
UPDATE addresses SET bound_id = 1 WHERE id = 450;
UPDATE addresses SET bound_id = 1 WHERE id = 455;
UPDATE addresses SET bound_id = 1 WHERE id = 457;
UPDATE addresses SET bound_id = 1 WHERE id = 458;
UPDATE addresses SET bound_id = 1 WHERE id = 464;
UPDATE addresses SET bound_id = 1 WHERE id = 466;
UPDATE addresses SET bound_id = 1 WHERE id = 467;
UPDATE addresses SET bound_id = 1 WHERE id = 468;
UPDATE addresses SET bound_id = 1 WHERE id = 470;
UPDATE addresses SET bound_id = 1 WHERE id = 472;
UPDATE addresses SET bound_id = 1 WHERE id = 473;
UPDATE addresses SET bound_id = 1 WHERE id = 474;
UPDATE addresses SET bound_id = 1 WHERE id = 475;
UPDATE addresses SET bound_id = 1 WHERE id = 476;
UPDATE addresses SET bound_id = 1 WHERE id = 478;
UPDATE addresses SET bound_id = 1 WHERE id = 479;
UPDATE addresses SET bound_id = 1 WHERE id = 480;
UPDATE addresses SET bound_id = 1 WHERE id = 481;
UPDATE addresses SET bound_id = 1 WHERE id = 484;
UPDATE addresses SET bound_id = 1 WHERE id = 486;
UPDATE addresses SET bound_id = 1 WHERE id = 493;
UPDATE addresses SET bound_id = 1 WHERE id = 495;
UPDATE addresses SET bound_id = 1 WHERE id = 498;
UPDATE addresses SET bound_id = 1 WHERE id = 499;
UPDATE addresses SET bound_id = 1 WHERE id = 500;
UPDATE addresses SET bound_id = 1 WHERE id = 501;
UPDATE addresses SET bound_id = 1 WHERE id = 502;
UPDATE addresses SET bound_id = 1 WHERE id = 503;
UPDATE addresses SET bound_id = 1 WHERE id = 505;
UPDATE addresses SET bound_id = 1 WHERE id = 506;
UPDATE addresses SET bound_id = 1 WHERE id = 509;
UPDATE addresses SET bound_id = 1 WHERE id = 510;
UPDATE addresses SET bound_id = 1 WHERE id = 512;
UPDATE addresses SET bound_id = 1 WHERE id = 513;
UPDATE addresses SET bound_id = 1 WHERE id = 514;
UPDATE addresses SET bound_id = 1 WHERE id = 515;
UPDATE addresses SET bound_id = 1 WHERE id = 516;
UPDATE addresses SET bound_id = 1 WHERE id = 517;
UPDATE addresses SET bound_id = 1 WHERE id = 519;
UPDATE addresses SET bound_id = 1 WHERE id = 521;
UPDATE addresses SET bound_id = 1 WHERE id = 522;
UPDATE addresses SET bound_id = 1 WHERE id = 523;
UPDATE addresses SET bound_id = 1 WHERE id = 526;
UPDATE addresses SET bound_id = 1 WHERE id = 527;
UPDATE addresses SET bound_id = 1 WHERE id = 529;
UPDATE addresses SET bound_id = 1 WHERE id = 531;
UPDATE addresses SET bound_id = 1 WHERE id = 532;
UPDATE addresses SET bound_id = 1 WHERE id = 533;
UPDATE addresses SET bound_id = 1 WHERE id = 535;
UPDATE addresses SET bound_id = 1 WHERE id = 536;
UPDATE addresses SET bound_id = 1 WHERE id = 540;
UPDATE addresses SET bound_id = 1 WHERE id = 541;
UPDATE addresses SET bound_id = 1 WHERE id = 542;
UPDATE addresses SET bound_id = 1 WHERE id = 543;
UPDATE addresses SET bound_id = 1 WHERE id = 545;
UPDATE addresses SET bound_id = 2 WHERE id = 546;
UPDATE addresses SET bound_id = 1 WHERE id = 548;
UPDATE addresses SET bound_id = 1 WHERE id = 551;
UPDATE addresses SET bound_id = 1 WHERE id = 553;
UPDATE addresses SET bound_id = 1 WHERE id = 555;
UPDATE addresses SET bound_id = 1 WHERE id = 556;
UPDATE addresses SET bound_id = 1 WHERE id = 557;
UPDATE addresses SET bound_id = 1 WHERE id = 558;
UPDATE addresses SET bound_id = 1 WHERE id = 559;
UPDATE addresses SET bound_id = 1 WHERE id = 560;
UPDATE addresses SET bound_id = 1 WHERE id = 561;
UPDATE addresses SET bound_id = 1 WHERE id = 562;
UPDATE addresses SET bound_id = 1 WHERE id = 563;
UPDATE addresses SET bound_id = 1 WHERE id = 565;
UPDATE addresses SET bound_id = 1 WHERE id = 566;
UPDATE addresses SET bound_id = 1 WHERE id = 569;
UPDATE addresses SET bound_id = 1 WHERE id = 570;
UPDATE addresses SET bound_id = 1 WHERE id = 571;
UPDATE addresses SET bound_id = 1 WHERE id = 572;
UPDATE addresses SET bound_id = 1 WHERE id = 574;
UPDATE addresses SET bound_id = 1 WHERE id = 576;
UPDATE addresses SET bound_id = 1 WHERE id = 579;
UPDATE addresses SET bound_id = 1 WHERE id = 580;
UPDATE addresses SET bound_id = 1 WHERE id = 581;
UPDATE addresses SET bound_id = 1 WHERE id = 582;
UPDATE addresses SET bound_id = 1 WHERE id = 583;
UPDATE addresses SET bound_id = 1 WHERE id = 585;
UPDATE addresses SET bound_id = NULL WHERE id = 586;
UPDATE addresses SET bound_id = 1 WHERE id = 590;
UPDATE addresses SET bound_id = NULL WHERE id = 595;
UPDATE addresses SET bound_id = NULL WHERE id = 599;
UPDATE addresses SET bound_id = 1 WHERE id = 601;
UPDATE addresses SET bound_id = NULL WHERE id = 603;
UPDATE addresses SET bound_id = 1 WHERE id = 604;
UPDATE addresses SET bound_id = NULL WHERE id = 606;
UPDATE addresses SET bound_id = 1 WHERE id = 608;
UPDATE addresses SET bound_id = 1 WHERE id = 610;
UPDATE addresses SET bound_id = 2 WHERE id = 611;
UPDATE addresses SET bound_id = 1 WHERE id = 612;
UPDATE addresses SET bound_id = 1 WHERE id = 615;
UPDATE addresses SET bound_id = NULL WHERE id = 621;
UPDATE addresses SET bound_id = 1 WHERE id = 623;
UPDATE addresses SET bound_id = 1 WHERE id = 627;
UPDATE addresses SET bound_id = 1 WHERE id = 628;
UPDATE addresses SET bound_id = NULL WHERE id = 629;
UPDATE addresses SET bound_id = 1 WHERE id = 630;
UPDATE addresses SET bound_id = 1 WHERE id = 633;
UPDATE addresses SET bound_id = 1 WHERE id = 634;
UPDATE addresses SET bound_id = 1 WHERE id = 636;
UPDATE addresses SET bound_id = NULL WHERE id = 637;
UPDATE addresses SET bound_id = 1 WHERE id = 639;
UPDATE addresses SET bound_id = 1 WHERE id = 641;
UPDATE addresses SET bound_id = 1 WHERE id = 645;
UPDATE addresses SET bound_id = 1 WHERE id = 646;
UPDATE addresses SET bound_id = NULL WHERE id = 647;
UPDATE addresses SET bound_id = 1 WHERE id = 651;
UPDATE addresses SET bound_id = 1 WHERE id = 652;
UPDATE addresses SET bound_id = 1 WHERE id = 653;
UPDATE addresses SET bound_id = 1 WHERE id = 654;
UPDATE addresses SET bound_id = 1 WHERE id = 657;
UPDATE addresses SET bound_id = NULL WHERE id = 660;
UPDATE addresses SET bound_id = 1 WHERE id = 662;
UPDATE addresses SET bound_id = 1 WHERE id = 663;
UPDATE addresses SET bound_id = 2 WHERE id = 664;
UPDATE addresses SET bound_id = 1 WHERE id = 666;
UPDATE addresses SET bound_id = 1 WHERE id = 668;
UPDATE addresses SET bound_id = 1 WHERE id = 669;
UPDATE addresses SET bound_id = 1 WHERE id = 671;
UPDATE addresses SET bound_id = 1 WHERE id = 672;
UPDATE addresses SET bound_id = 1 WHERE id = 674;
UPDATE addresses SET bound_id = 1 WHERE id = 675;
UPDATE addresses SET bound_id = 1 WHERE id = 676;
UPDATE addresses SET bound_id = 1 WHERE id = 677;
UPDATE addresses SET bound_id = NULL WHERE id = 678;
UPDATE addresses SET bound_id = 1 WHERE id = 680;
UPDATE addresses SET bound_id = 1 WHERE id = 681;
UPDATE addresses SET bound_id = 1 WHERE id = 683;
UPDATE addresses SET bound_id = 1 WHERE id = 685;
UPDATE addresses SET bound_id = 1 WHERE id = 686;
UPDATE addresses SET bound_id = 1 WHERE id = 687;
UPDATE addresses SET bound_id = 1 WHERE id = 689;
UPDATE addresses SET bound_id = 1 WHERE id = 690;
UPDATE addresses SET bound_id = 1 WHERE id = 693;
UPDATE addresses SET bound_id = NULL WHERE id = 694;
UPDATE addresses SET bound_id = NULL WHERE id = 696;
UPDATE addresses SET bound_id = 1 WHERE id = 697;
UPDATE addresses SET bound_id = NULL WHERE id = 699;
UPDATE addresses SET bound_id = 1 WHERE id = 700;
UPDATE addresses SET bound_id = 1 WHERE id = 701;
UPDATE addresses SET bound_id = 1 WHERE id = 702;
UPDATE addresses SET bound_id = 1 WHERE id = 703;
UPDATE addresses SET bound_id = 1 WHERE id = 705;
UPDATE addresses SET bound_id = 1 WHERE id = 709;
UPDATE addresses SET bound_id = 1 WHERE id = 710;
UPDATE addresses SET bound_id = 1 WHERE id = 711;
UPDATE addresses SET bound_id = 1 WHERE id = 712;
UPDATE addresses SET bound_id = 1 WHERE id = 715;
UPDATE addresses SET bound_id = 1 WHERE id = 716;
UPDATE addresses SET bound_id = 1 WHERE id = 718;
UPDATE addresses SET bound_id = 1 WHERE id = 719;
UPDATE addresses SET bound_id = 2 WHERE id = 721;
UPDATE addresses SET bound_id = 1 WHERE id = 723;
UPDATE addresses SET bound_id = 1 WHERE id = 724;
UPDATE addresses SET bound_id = 1 WHERE id = 725;
UPDATE addresses SET bound_id = 1 WHERE id = 727;
UPDATE addresses SET bound_id = 1 WHERE id = 728;
UPDATE addresses SET bound_id = 1 WHERE id = 729;
UPDATE addresses SET bound_id = 1 WHERE id = 731;
UPDATE addresses SET bound_id = 1 WHERE id = 732;
UPDATE addresses SET bound_id = 1 WHERE id = 733;
UPDATE addresses SET bound_id = 2 WHERE id = 734;
UPDATE addresses SET bound_id = 1 WHERE id = 736;
UPDATE addresses SET bound_id = 2 WHERE id = 737;
UPDATE addresses SET bound_id = 1 WHERE id = 739;
UPDATE addresses SET bound_id = 1 WHERE id = 740;
UPDATE addresses SET bound_id = 1 WHERE id = 742;
UPDATE addresses SET bound_id = 1 WHERE id = 746;
UPDATE addresses SET bound_id = 1 WHERE id = 747;
UPDATE addresses SET bound_id = 1 WHERE id = 748;
UPDATE addresses SET bound_id = 1 WHERE id = 749;
UPDATE addresses SET bound_id = 1 WHERE id = 750;
UPDATE addresses SET bound_id = 1 WHERE id = 751;
UPDATE addresses SET bound_id = 1 WHERE id = 752;
UPDATE addresses SET bound_id = 1 WHERE id = 757;
UPDATE addresses SET bound_id = 1 WHERE id = 758;
UPDATE addresses SET bound_id = 1 WHERE id = 759;
UPDATE addresses SET bound_id = 1 WHERE id = 760;
UPDATE addresses SET bound_id = 1 WHERE id = 762;
UPDATE addresses SET bound_id = 1 WHERE id = 763;
UPDATE addresses SET bound_id = 1 WHERE id = 764;
UPDATE addresses SET bound_id = NULL WHERE id = 765;
UPDATE addresses SET bound_id = 1 WHERE id = 767;
UPDATE addresses SET bound_id = 1 WHERE id = 770;
UPDATE addresses SET bound_id = 1 WHERE id = 771;
UPDATE addresses SET bound_id = 1 WHERE id = 772;
UPDATE addresses SET bound_id = 1 WHERE id = 773;
UPDATE addresses SET bound_id = 2 WHERE id = 774;
UPDATE addresses SET bound_id = 1 WHERE id = 776;
UPDATE addresses SET bound_id = 1 WHERE id = 777;
UPDATE addresses SET bound_id = NULL WHERE id = 778;
UPDATE addresses SET bound_id = 1 WHERE id = 779;
UPDATE addresses SET bound_id = 1 WHERE id = 781;
UPDATE addresses SET bound_id = 1 WHERE id = 786;
UPDATE addresses SET bound_id = 1 WHERE id = 787;
UPDATE addresses SET bound_id = 1 WHERE id = 789;
UPDATE addresses SET bound_id = 1 WHERE id = 790;
UPDATE addresses SET bound_id = 1 WHERE id = 791;
UPDATE addresses SET bound_id = 1 WHERE id = 792;
UPDATE addresses SET bound_id = 1 WHERE id = 793;
UPDATE addresses SET bound_id = 1 WHERE id = 794;
UPDATE addresses SET bound_id = 1 WHERE id = 796;
UPDATE addresses SET bound_id = 1 WHERE id = 797;
UPDATE addresses SET bound_id = 1 WHERE id = 798;
UPDATE addresses SET bound_id = 1 WHERE id = 800;
UPDATE addresses SET bound_id = 1 WHERE id = 801;
UPDATE addresses SET bound_id = 1 WHERE id = 803;
UPDATE addresses SET bound_id = 1 WHERE id = 804;
UPDATE addresses SET bound_id = 1 WHERE id = 805;
UPDATE addresses SET bound_id = 1 WHERE id = 806;
UPDATE addresses SET bound_id = 1 WHERE id = 810;
UPDATE addresses SET bound_id = 1 WHERE id = 812;
UPDATE addresses SET bound_id = 1 WHERE id = 813;
UPDATE addresses SET bound_id = 1 WHERE id = 815;
UPDATE addresses SET bound_id = 1 WHERE id = 819;
UPDATE addresses SET bound_id = 1 WHERE id = 821;
UPDATE addresses SET bound_id = 1 WHERE id = 822;
UPDATE addresses SET bound_id = 1 WHERE id = 823;
UPDATE addresses SET bound_id = 1 WHERE id = 824;
UPDATE addresses SET bound_id = 1 WHERE id = 826;
UPDATE addresses SET bound_id = 1 WHERE id = 827;
UPDATE addresses SET bound_id = 1 WHERE id = 828;
UPDATE addresses SET bound_id = 1 WHERE id = 831;
UPDATE addresses SET bound_id = 1 WHERE id = 832;
UPDATE addresses SET bound_id = 1 WHERE id = 833;
UPDATE addresses SET bound_id = 1 WHERE id = 835;
UPDATE addresses SET bound_id = 1 WHERE id = 836;
UPDATE addresses SET bound_id = 1 WHERE id = 837;
UPDATE addresses SET bound_id = 1 WHERE id = 838;
UPDATE addresses SET bound_id = 1 WHERE id = 839;
UPDATE addresses SET bound_id = 1 WHERE id = 840;
UPDATE addresses SET bound_id = 1 WHERE id = 841;
UPDATE addresses SET bound_id = 1 WHERE id = 842;
UPDATE addresses SET bound_id = 1 WHERE id = 845;
UPDATE addresses SET bound_id = 2 WHERE id = 847;
UPDATE addresses SET bound_id = 1 WHERE id = 850;
UPDATE addresses SET bound_id = 1 WHERE id = 851;
UPDATE addresses SET bound_id = 1 WHERE id = 852;
UPDATE addresses SET bound_id = 1 WHERE id = 853;
UPDATE addresses SET bound_id = 1 WHERE id = 854;
UPDATE addresses SET bound_id = 1 WHERE id = 860;
UPDATE addresses SET bound_id = 1 WHERE id = 861;
UPDATE addresses SET bound_id = 1 WHERE id = 863;
UPDATE addresses SET bound_id = 1 WHERE id = 865;
UPDATE addresses SET bound_id = 1 WHERE id = 866;
UPDATE addresses SET bound_id = 1 WHERE id = 867;
UPDATE addresses SET bound_id = 1 WHERE id = 868;
UPDATE addresses SET bound_id = 1 WHERE id = 869;
UPDATE addresses SET bound_id = 1 WHERE id = 873;
UPDATE addresses SET bound_id = 1 WHERE id = 876;
UPDATE addresses SET bound_id = 1 WHERE id = 878;
UPDATE addresses SET bound_id = 1 WHERE id = 879;
UPDATE addresses SET bound_id = 1 WHERE id = 880;
UPDATE addresses SET bound_id = NULL WHERE id = 881;
UPDATE addresses SET bound_id = 1 WHERE id = 884;
UPDATE addresses SET bound_id = 1 WHERE id = 885;
UPDATE addresses SET bound_id = 1 WHERE id = 888;
UPDATE addresses SET bound_id = 1 WHERE id = 889;
UPDATE addresses SET bound_id = 1 WHERE id = 890;
UPDATE addresses SET bound_id = 1 WHERE id = 891;
UPDATE addresses SET bound_id = 1 WHERE id = 892;
UPDATE addresses SET bound_id = 1 WHERE id = 893;
UPDATE addresses SET bound_id = 1 WHERE id = 894;
UPDATE addresses SET bound_id = 1 WHERE id = 895;
UPDATE addresses SET bound_id = 1 WHERE id = 896;
UPDATE addresses SET bound_id = 1 WHERE id = 899;
UPDATE addresses SET bound_id = 1 WHERE id = 901;
UPDATE addresses SET bound_id = 1 WHERE id = 902;
UPDATE addresses SET bound_id = 1 WHERE id = 904;
UPDATE addresses SET bound_id = 1 WHERE id = 905;
UPDATE addresses SET bound_id = 1 WHERE id = 906;
UPDATE addresses SET bound_id = 1 WHERE id = 907;
UPDATE addresses SET bound_id = 1 WHERE id = 908;
UPDATE addresses SET bound_id = 1 WHERE id = 910;
UPDATE addresses SET bound_id = 1 WHERE id = 911;

View file

@ -0,0 +1,83 @@
-- ============================================================
-- delete-orders-before-2026-02-10.sql
--
-- DESTRUCTIVE. Deletes every order created before 2026-02-10 (midnight,
-- exclusive -- anything on/after 2026-02-10 00:00 is kept) and the rows that
-- hang off those orders.
--
-- Cutoff: `created_at < '2026-02-10'` compares correctly for the timestamp
-- shapes the app writes ('2026-02-09T23:00:00.000Z' and '2026-02-09 23:00:00').
--
-- Schema: this targets the post-0006 database (applied to the remote now).
-- 0006 removed online payments, so `payments`, `refunds` and `payment_info` no
-- longer exist and `orders.payment_info_id` is gone -- none are referenced here.
-- (The same statements also run on a pre-0006 copy; they just leave the dropped
-- payment tables alone.)
--
-- Per order it:
-- 1. detaches coupon_usage / complaints / user_incidents (rows kept, order
-- references set to NULL, so coupon limits and complaint history survive)
-- 2. deletes its order_items and order_status rows
-- 3. deletes the order
--
-- Post-0006 orders whose items were archived into `orders.items_json` have no
-- `order_items` rows, so only the order/status row is removed for them.
--
-- Counts from the local dump at time of writing (pre-0006 copy):
-- 110 of 2548 orders (oldest 2025-12-24), 194 order_items, 110 order_status,
-- 23 coupon_usage detached, 1 complaint detached, 0 user_incidents.
-- Counts will differ on the target database.
--
-- Apply from apps/backend:
-- wrangler d1 execute freshyo-backend-dev --file=../../address_util/delete-orders-before-2026-02-10.sql --config wrangler.dev.toml --remote
--
-- Dry run (counts only):
-- SELECT COUNT(*) FROM orders WHERE created_at < '2026-02-10';
-- ============================================================
-- 1. Preserve cross-cutting history; drop only the order references.
UPDATE coupon_usage
SET order_id = NULL,
order_item_id = NULL
WHERE order_id IN (SELECT id FROM orders WHERE created_at < '2026-02-10')
OR order_item_id IN (
SELECT oi.id FROM order_items oi
JOIN orders o ON o.id = oi.order_id
WHERE o.created_at < '2026-02-10'
);
UPDATE complaints
SET order_id = NULL
WHERE order_id IN (SELECT id FROM orders WHERE created_at < '2026-02-10');
UPDATE user_incidents
SET order_id = NULL
WHERE order_id IN (SELECT id FROM orders WHERE created_at < '2026-02-10');
-- 2. Delete the order-owned item/status rows.
DELETE FROM order_items
WHERE order_id IN (SELECT id FROM orders WHERE created_at < '2026-02-10');
DELETE FROM order_status
WHERE order_id IN (SELECT id FROM orders WHERE created_at < '2026-02-10');
-- 3. Delete the orders themselves.
DELETE FROM orders
WHERE created_at < '2026-02-10';
-- Verification (run after applying):
-- SELECT COUNT(*) FROM orders WHERE created_at < '2026-02-10'; -- expect 0
-- SELECT COUNT(*) FROM order_items
-- WHERE order_id NOT IN (SELECT id FROM orders); -- expect 0
-- SELECT COUNT(*) FROM order_status
-- WHERE order_id NOT IN (SELECT id FROM orders); -- expect 0
-- SELECT COUNT(*) FROM coupon_usage
-- WHERE order_id IS NOT NULL
-- AND order_id NOT IN (SELECT id FROM orders); -- expect 0
-- SELECT COUNT(*) FROM complaints
-- WHERE order_id IS NOT NULL
-- AND order_id NOT IN (SELECT id FROM orders); -- expect 0
-- SELECT COUNT(*) FROM user_incidents
-- WHERE order_id IS NOT NULL
-- AND order_id NOT IN (SELECT id FROM orders); -- expect 0
-- PRAGMA foreign_key_check; -- expect no rows

View file

@ -0,0 +1,66 @@
-- ============================================================
-- delete-outside-bound-addresses.sql
--
-- Targets 23 addresses:
-- * 22 whose computed bound is NULL in computed-bounds-466.sql
-- (addresses outside both region polygons), plus
-- * address 285 (user 388, mobile 9676651496, "Mbnr, Mbnr").
--
-- DESTRUCTIVE. For each address it:
-- 1. detaches coupon_usage / complaints / user_incidents from its orders
-- 2. deletes its order_items and order_status rows
-- 3. deletes its orders
-- 4. deletes the address
--
-- Local impact: 46 orders, 2 order_items, 46 order_status,
-- 3 coupon_usage rows (detached, kept), 0 complaints, 0 incidents.
-- 17 of the 23 addresses are users' default addresses.
-- User 388 keeps their account but will have no address after this.
-- If an address is already gone, every statement is a no-op.
--
-- Apply:
-- wrangler d1 execute <db-name> --remote --config wrangler.prod.toml \
-- --file address_util/delete-outside-bound-addresses.sql
-- ============================================================
-- Preserve coupon usage history; drop its reference to the deleted orders/items.
UPDATE coupon_usage
SET order_id = NULL,
order_item_id = NULL
WHERE order_id IN (SELECT id FROM orders WHERE address_id IN (250, 280, 285, 310, 394, 448, 586, 595, 599, 603, 606, 621, 629, 637, 647, 660, 678, 694, 696, 699, 765, 778, 881))
OR order_item_id IN (
SELECT oi.id FROM order_items oi
JOIN orders o ON o.id = oi.order_id
WHERE o.address_id IN (250, 280, 285, 310, 394, 448, 586, 595, 599, 603, 606, 621, 629, 637, 647, 660, 678, 694, 696, 699, 765, 778, 881)
);
-- Preserve complaints / incidents; drop their order reference.
UPDATE complaints
SET order_id = NULL
WHERE order_id IN (SELECT id FROM orders WHERE address_id IN (250, 280, 285, 310, 394, 448, 586, 595, 599, 603, 606, 621, 629, 637, 647, 660, 678, 694, 696, 699, 765, 778, 881));
UPDATE user_incidents
SET order_id = NULL
WHERE order_id IN (SELECT id FROM orders WHERE address_id IN (250, 280, 285, 310, 394, 448, 586, 595, 599, 603, 606, 621, 629, 637, 647, 660, 678, 694, 696, 699, 765, 778, 881));
-- Delete order dependents.
DELETE FROM order_items
WHERE order_id IN (SELECT id FROM orders WHERE address_id IN (250, 280, 285, 310, 394, 448, 586, 595, 599, 603, 606, 621, 629, 637, 647, 660, 678, 694, 696, 699, 765, 778, 881));
DELETE FROM order_status
WHERE order_id IN (SELECT id FROM orders WHERE address_id IN (250, 280, 285, 310, 394, 448, 586, 595, 599, 603, 606, 621, 629, 637, 647, 660, 678, 694, 696, 699, 765, 778, 881));
-- Delete the orders that belong to these addresses.
DELETE FROM orders WHERE address_id IN (250, 280, 285, 310, 394, 448, 586, 595, 599, 603, 606, 621, 629, 637, 647, 660, 678, 694, 696, 699, 765, 778, 881);
-- Delete the addresses.
DELETE FROM addresses WHERE id IN (250, 280, 285, 310, 394, 448, 586, 595, 599, 603, 606, 621, 629, 637, 647, 660, 678, 694, 696, 699, 765, 778, 881);
-- Verification:
-- SELECT COUNT(*) FROM addresses WHERE id IN (250, 280, 285, 310, 394, 448, 586, 595, 599, 603, 606, 621, 629, 637, 647, 660, 678, 694, 696, 699, 765, 778, 881); -- expect 0
-- SELECT COUNT(*) FROM orders WHERE id IN (649, 776, 815, 859, 860, 867, 910, 1038, 1050, 1060, 1209, 1394, 1397, 1471, 1570, 1597, 1654, 1796, 1950, 1952, 1953, 1982, 2009, 2023, 2037, 2040, 2042, 2043, 2085, 2102, 2128, 2153, 2171, 2284, 2317, 2352, 2429, 2455, 2466, 2467, 2522, 2557, 2562, 2590, 2693, 2702); -- expect 0
-- SELECT COUNT(*) FROM order_status WHERE order_id IN (649, 776, 815, 859, 860, 867, 910, 1038, 1050, 1060, 1209, 1394, 1397, 1471, 1570, 1597, 1654, 1796, 1950, 1952, 1953, 1982, 2009, 2023, 2037, 2040, 2042, 2043, 2085, 2102, 2128, 2153, 2171, 2284, 2317, 2352, 2429, 2455, 2466, 2467, 2522, 2557, 2562, 2590, 2693, 2702); -- expect 0
-- SELECT id, order_id, order_item_id FROM coupon_usage WHERE id IN (116, 147, 169);
-- -- expect all rows kept, order_id/order_item_id NULL
-- SELECT COUNT(*) FROM users WHERE id = 388; -- expect 1 (account kept)
-- PRAGMA foreign_key_check; -- expect no rows

View file

@ -0,0 +1,23 @@
# Address-util SQL commands
# Run from apps/backend.
#
# Note: run the delete file last.
# Do NOT run address_util/address-bound-updates.sql (old artifact).
cd apps/backend
# 1. Admin coords (idempotent)
wrangler d1 execute freshyo-dev --file=../../address_util/backfill-admin-coords.sql --config wrangler.prod.toml --remote
# 2. Computed bounds for the 466 non-vague addresses
wrangler d1 execute freshyo-dev --file=../../address_util/computed-bounds-466.sql --config wrangler.prod.toml --remote
# 3. Manual bounds + coords for the 416 vague addresses
wrangler d1 execute freshyo-dev --file=../../address_util/address-bound-coord-updates.sql --config wrangler.prod.toml --remote
# 4. Delete the 23 selected addresses (run last)
wrangler d1 execute freshyo-dev --file=../../address_util/delete-outside-bound-addresses.sql --config wrangler.prod.toml --remote
# Optional verification
wrangler d1 execute freshyo-backend-dev --config wrangler.dev.toml --command="SELECT bound_id, COUNT(*) AS n FROM addresses GROUP BY bound_id ORDER BY bound_id" --remote
wrangler d1 execute freshyo-backend-dev --config wrangler.dev.toml --command="SELECT COUNT(*) AS vague FROM addresses WHERE vague_backfilled_coords = 1" --remote

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

View file

@ -10,6 +10,7 @@ import {
import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import { REFRESH_EVENT } from "common-ui/src/lib/const-strs";
import { useStaffAuth } from "@/components/context/staff-auth-context";
import { trpc } from "@/src/trpc-client";
import { tw, MyText, theme } from "common-ui";
const SCREEN_TITLES: Record<string, string> = {
@ -33,21 +34,45 @@ const SCREEN_TITLES: Record<string, string> = {
function CustomDrawerContent() {
const router = useRouter();
const { logout, staff } = useStaffAuth();
const { logout, staff, isLoggedIn, regionId } = useStaffAuth();
// Server truth for the header: the login payload carries only regionId and a
// session restored from storage may predate this screen, so ask the API.
const { data: me } = trpc.admin.staffUser.me.useQuery(undefined, {
enabled: isLoggedIn,
});
const staffName = me?.name ?? staff?.name ?? "Unknown user";
// regionId 0 is the backend's "staff has no region" value.
const staffRegionId = me?.regionId ?? regionId;
const regionLabel =
me?.regionName ??
(staffRegionId ? `Region #${staffRegionId}` : "No region");
return (
<DrawerContentScrollView>
{staff && (
<View style={tw`p-4 border-b border-gray-200`}>
<View style={tw`p-4 border-b border-gray-200`}>
<View style={tw`flex-row items-center`}>
<MaterialIcons name="person" size={40} color="#3B82F6" />
<View style={tw`mt-2`}>
<MyText style={tw`text-lg font-semibold text-gray-800`}>
{staff.name}
<View style={tw`ml-3 flex-1`}>
<MyText
style={tw`text-lg font-semibold text-gray-800`}
numberOfLines={1}
>
{staffName}
</MyText>
<MyText style={tw`text-sm text-gray-600`}>Staff Member</MyText>
<View style={tw`flex-row items-center mt-1`}>
<MaterialIcons name="place" size={14} color="#6B7280" />
<MyText
style={tw`text-sm text-gray-600 ml-1`}
numberOfLines={1}
>
{regionLabel}
</MyText>
</View>
</View>
</View>
)}
</View>
<DrawerItem
label="Dashboard"
onPress={() => router.dismissTo("/(drawer)/dashboard" as any)}

View file

@ -5,6 +5,7 @@ export default function Layout() {
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen name="index" options={{ title: "Coupons" }} />
<Stack.Screen name="create" options={{ title: "Create Coupon" }} />
<Stack.Screen name="detail/[id]" options={{ title: "Coupon Details" }} />
<Stack.Screen name="edit/[id]" options={{ title: "Edit Coupon" }} />
</Stack>
);

View file

@ -0,0 +1,232 @@
import React from 'react'
import { RefreshControl, ScrollView, View } from 'react-native'
import { useLocalSearchParams, useRouter } from 'expo-router'
import { MaterialCommunityIcons } from '@expo/vector-icons'
import { tw, MyText, MyTouchableOpacity, useMarkDataFetchers } from 'common-ui'
import { trpc } from '@/src/trpc-client'
const money = (value: string | number | null | undefined) =>
value == null || value === '' ? 'None' : `₹${Number(value)}`
const formatDate = (value: string | Date | null | undefined) =>
value ? new Date(value).toLocaleDateString() : 'No expiry'
const couponStatus = (coupon: any) => {
if (coupon.isInvalidated) return 'Inactive'
if (coupon.validTill && new Date(coupon.validTill) <= new Date()) return 'Expired'
return 'Active'
}
const statusStyles = (status: string) => {
if (status === 'Active') return { badge: 'bg-green-100', text: 'text-green-600' }
if (status === 'Expired') return { badge: 'bg-yellow-100', text: 'text-yellow-600' }
return { badge: 'bg-red-100', text: 'text-red-600' }
}
function DetailRow({
icon,
label,
value,
}: {
icon: React.ComponentProps<typeof MaterialCommunityIcons>['name']
label: string
value: string
}) {
return (
<View style={tw`flex-row items-center justify-between py-3 border-b border-gray-100`}>
<View style={tw`flex-row items-center flex-1 mr-3`}>
<MaterialCommunityIcons name={icon} size={18} color="#6b7280" />
<MyText style={tw`text-sm text-gray-500 ml-2`}>{label}</MyText>
</View>
<MyText style={tw`text-sm font-semibold text-gray-800 text-right`}>{value}</MyText>
</View>
)
}
function Section({ title, children }: { title: string; children: React.ReactNode }) {
return (
<View style={tw`bg-white rounded-2xl p-4 mb-4 shadow-sm`}>
<MyText style={tw`text-xs font-bold uppercase tracking-wider text-gray-400 mb-1`}>
{title}
</MyText>
{children}
</View>
)
}
export default function CouponDetails() {
const router = useRouter()
const { id } = useLocalSearchParams()
const rawId = Array.isArray(id) ? id[0] : id
const couponId = Number(rawId)
const hasValidId = Number.isInteger(couponId) && couponId > 0
const { data: coupon, isLoading, isFetching, error, refetch } =
trpc.admin.coupon.getById.useQuery(
{ id: couponId },
{ enabled: hasValidId }
)
useMarkDataFetchers(() => {
refetch()
})
const handleEdit = () => {
router.push(`/(drawer)/dashboard/coupons/edit/${couponId}`)
}
if (isLoading) {
return (
<View style={tw`flex-1 justify-center items-center bg-white`}>
<MaterialCommunityIcons name="loading" size={32} color="#3b82f6" />
<MyText style={tw`text-gray-500 mt-4 font-medium`}>Loading coupon...</MyText>
</View>
)
}
if (error || !coupon) {
return (
<View style={tw`flex-1 justify-center items-center bg-white p-6`}>
<MaterialCommunityIcons name="ticket-percent-outline" size={56} color="#ef4444" />
<MyText style={tw`text-xl font-bold text-gray-900 mt-4`}>Coupon not found</MyText>
<MyTouchableOpacity
testID="coupon-detail-back"
onPress={() => router.back()}
style={tw`mt-6 px-8 py-3 bg-gray-100 rounded-full`}
>
<MyText style={tw`text-gray-800 font-semibold`}>Go Back</MyText>
</MyTouchableOpacity>
</View>
)
}
const status = couponStatus(coupon)
const colors = statusStyles(status)
const isGlobal = coupon.regionId == null
const users = coupon.applicableUsers ?? []
const skuCount = coupon.skuIds?.length ?? 0
const discount = coupon.discountPercent
? `${Number(coupon.discountPercent)}% off`
: coupon.flatDiscount
? `${money(coupon.flatDiscount)} off`
: 'None'
return (
<View style={tw`flex-1 bg-gray-50`}>
<View style={tw`flex-row items-center px-4 py-3 bg-white border-b border-gray-100`}>
<MyTouchableOpacity
testID="coupon-detail-back"
onPress={() => router.back()}
style={tw`p-2 -ml-2 mr-1`}
>
<MaterialCommunityIcons name="arrow-left" size={24} color="#111827" />
</MyTouchableOpacity>
<View style={tw`flex-1`}>
<MyText style={tw`text-lg font-bold text-gray-900`}>Coupon Details</MyText>
<MyText style={tw`text-xs text-gray-500`}>ID: {coupon.id}</MyText>
</View>
{!isGlobal && (
<MyTouchableOpacity
testID="coupon-detail-edit"
onPress={handleEdit}
style={tw`flex-row items-center bg-blue-500 px-3 py-2 rounded-lg`}
>
<MaterialCommunityIcons name="pencil" size={16} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>Edit</MyText>
</MyTouchableOpacity>
)}
</View>
<ScrollView
style={tw`flex-1`}
contentContainerStyle={tw`p-4 pb-10`}
refreshControl={<RefreshControl refreshing={isFetching} onRefresh={refetch} />}
>
<View style={tw`bg-white rounded-2xl p-5 mb-4 shadow-sm`}>
<View style={tw`flex-row items-center flex-wrap`}>
<MyText style={tw`text-2xl font-extrabold text-gray-900 mr-2`}>
{coupon.couponCode}
</MyText>
{isGlobal && (
<View style={tw`px-2 py-0.5 rounded-full bg-indigo-100 border border-indigo-200 mr-2`}>
<MyText style={tw`text-[10px] font-bold text-indigo-700`}>Global</MyText>
</View>
)}
<View style={tw`px-2 py-1 rounded-full ${colors.badge}`}>
<MyText style={tw`text-xs font-semibold ${colors.text}`}>{status}</MyText>
</View>
</View>
<MyText style={tw`text-base font-semibold text-gray-700 mt-3`}>{discount}</MyText>
{isGlobal && (
<View style={tw`mt-3 bg-indigo-50 border border-indigo-100 rounded-lg p-3`}>
<MyText style={tw`text-xs text-indigo-700`}>
Applies to all regions — created and managed by the superadmin.
</MyText>
</View>
)}
</View>
<Section title="Discount">
<DetailRow icon="percent" label="Type" value={coupon.discountPercent ? 'Percentage' : 'Flat amount'} />
<DetailRow icon="cart-outline" label="Min Order" value={money(coupon.minOrder)} />
<DetailRow icon="cash-multiple" label="Max Discount" value={money(coupon.maxValue)} />
<View style={tw`flex-row items-center justify-between py-3`}>
<View style={tw`flex-row items-center flex-1 mr-3`}>
<MaterialCommunityIcons name="repeat" size={18} color="#6b7280" />
<MyText style={tw`text-sm text-gray-500 ml-2`}>Uses / User</MyText>
</View>
<MyText style={tw`text-sm font-semibold text-gray-800 text-right`}>
{coupon.maxLimitForUser ? String(coupon.maxLimitForUser) : 'Unlimited'}
</MyText>
</View>
</Section>
<Section title="Validity & rules">
<DetailRow icon="calendar-blank-outline" label="Valid Till" value={formatDate(coupon.validTill)} />
<DetailRow icon="numeric-1-circle-outline" label="First Order Only" value={coupon.isFirstOrderOnly ? 'Yes' : 'No'} />
<DetailRow icon="lock-outline" label="Exclusive" value={coupon.exclusiveApply ? 'Yes' : 'No'} />
<DetailRow icon="map-marker-outline" label="Region" value={isGlobal ? 'All regions' : `Region #${coupon.regionId}`} />
</Section>
<Section title="Targeting">
<DetailRow
icon="account-group-outline"
label="Audience"
value={coupon.isApplyForAll ? 'All users' : `${users.length} users`}
/>
<DetailRow
icon="package-variant-closed"
label="Products"
value={skuCount === 0 ? 'Whole cart' : `${skuCount} selected`}
/>
{!coupon.isApplyForAll && users.length > 0 && (
<View style={tw`mt-2`}>
{users.map((user: any) => (
<View key={user.id} style={tw`flex-row items-center py-2 border-b border-gray-50`}>
<MaterialCommunityIcons name="account-circle-outline" size={18} color="#9ca3af" />
<MyText style={tw`text-sm text-gray-700 ml-2 flex-1`}>
{user.name || 'Unnamed user'}
</MyText>
<MyText style={tw`text-xs text-gray-500`}>{user.mobile || 'No mobile'}</MyText>
</View>
))}
</View>
)}
</Section>
<Section title="Created">
<DetailRow icon="account-outline" label="Created By" value={coupon.creator?.name || 'Unknown'} />
<View style={tw`flex-row items-center justify-between py-3`}>
<View style={tw`flex-row items-center flex-1 mr-3`}>
<MaterialCommunityIcons name="clock-outline" size={18} color="#6b7280" />
<MyText style={tw`text-sm text-gray-500 ml-2`}>Created On</MyText>
</View>
<MyText style={tw`text-sm font-semibold text-gray-800 text-right`}>
{coupon.createdAt ? new Date(coupon.createdAt).toLocaleDateString() : 'Unknown'}
</MyText>
</View>
</Section>
</ScrollView>
</View>
)
}

View file

@ -78,7 +78,7 @@ export default function EditCoupon() {
validTill: coupon.validTill ? dayjs(coupon.validTill).format('YYYY-MM-DD') : undefined,
maxLimitForUser: coupon.maxLimitForUser || undefined,
isFirstOrderOnly: coupon.isFirstOrderOnly,
skuIds: coupon.skuIds,
skuIds: coupon.skuIds ?? [],
isReservedCoupon: false, // Normal coupons
};

View file

@ -18,6 +18,9 @@ const CouponItem = ({ item, onDelete }: { item: any; onDelete: (id: number) => v
};
const status = getCouponStatus(item);
// Global coupons (region_id NULL) are created by the superadmin and apply to
// every region, so a region admin can only view them.
const isGlobal = item.regionId == null;
const getBorderColor = () => {
if (status === 'active') return 'border-green-500';
@ -54,7 +57,14 @@ const CouponItem = ({ item, onDelete }: { item: any; onDelete: (id: number) => v
/>
</View>
<View style={tw`flex-1`}>
<MyText style={tw`text-lg font-bold text-gray-800`}>{item.couponCode}</MyText>
<View style={tw`flex-row items-center flex-wrap`}>
<MyText style={tw`text-lg font-bold text-gray-800`}>{item.couponCode}</MyText>
{isGlobal && (
<View style={tw`ml-2 px-2 py-0.5 rounded-full bg-indigo-100 border border-indigo-200`}>
<MyText style={tw`text-[10px] font-bold text-indigo-700`}>Global</MyText>
</View>
)}
</View>
<MyText style={tw`text-sm text-gray-500`}>ID: {item.id}</MyText>
</View>
<View style={tw`px-2 py-1 rounded-full ${getBgColor()}`}>
@ -81,29 +91,47 @@ const CouponItem = ({ item, onDelete }: { item: any; onDelete: (id: number) => v
<MyText style={tw`text-sm text-gray-700 mb-1`}>
<MaterialCommunityIcons name="account-group" size={14} color="#6b7280" /> Target: {item.isApplyForAll ? 'All Users' : item.applicableUsers?.length > 0 ? `${item.applicableUsers.length} Users` : 'All Users'}
</MyText>
{item.applicableProducts && item.applicableProducts.length > 0 && (
{item.skuIds && item.skuIds.length > 0 && (
<MyText style={tw`text-sm text-gray-700`}>
<MaterialCommunityIcons name="package-variant" size={14} color="#6b7280" /> Products: {item.applicableProducts.length} selected
<MaterialCommunityIcons name="package-variant" size={14} color="#6b7280" /> Products: {item.skuIds.length} selected
</MyText>
)}
</View>
<View style={tw`flex-row mt-3 gap-2`}>
<TouchableOpacity
onPress={() => router.push(`/(drawer)/dashboard/coupons/edit/${item.id}`)}
style={tw`bg-blue-500 p-3 rounded-lg shadow-md flex-1 flex-row items-center justify-center`}
>
<MaterialCommunityIcons name="pencil" size={16} color="white" />
<MyText style={tw`text-white text-center font-semibold ml-1`}>Edit</MyText>
</TouchableOpacity>
<TouchableOpacity
onPress={() => onDelete(item.id)}
style={tw`bg-red-500 p-3 rounded-lg shadow-md flex-1 flex-row items-center justify-center`}
>
<MaterialCommunityIcons name="delete" size={16} color="white" />
<MyText style={tw`text-white text-center font-semibold ml-1`}>Delete</MyText>
</TouchableOpacity>
</View>
<MyTouchableOpacity
testID={`coupon-view-${item.id}`}
onPress={() => router.push(`/(drawer)/dashboard/coupons/detail/${item.id}` as any)}
accessibilityRole="button"
style={tw`flex-row items-center justify-center py-2 mb-2`}
>
<MyText style={tw`text-sm font-semibold text-blue-600`}>View details</MyText>
<MaterialCommunityIcons name="chevron-right" size={18} color="#2563eb" />
</MyTouchableOpacity>
{isGlobal ? (
<View style={tw`mt-1 bg-indigo-50 border border-indigo-100 rounded-lg p-3`}>
<MyText style={tw`text-xs text-indigo-700`}>
Applies to all regions — created and managed by the superadmin.
</MyText>
</View>
) : (
<View style={tw`flex-row mt-3 gap-2`}>
<TouchableOpacity
onPress={() => router.push(`/(drawer)/dashboard/coupons/edit/${item.id}`)}
style={tw`bg-blue-500 p-3 rounded-lg shadow-md flex-1 flex-row items-center justify-center`}
>
<MaterialCommunityIcons name="pencil" size={16} color="white" />
<MyText style={tw`text-white text-center font-semibold ml-1`}>Edit</MyText>
</TouchableOpacity>
<TouchableOpacity
onPress={() => onDelete(item.id)}
style={tw`bg-red-500 p-3 rounded-lg shadow-md flex-1 flex-row items-center justify-center`}
>
<MaterialCommunityIcons name="delete" size={16} color="white" />
<MyText style={tw`text-white text-center font-semibold ml-1`}>Delete</MyText>
</TouchableOpacity>
</View>
)}
</View>
);
};

View file

@ -91,10 +91,10 @@ export default function AllItemsOrder() {
const [products, setProducts] = useState<Product[]>([]);
const [hasChanges, setHasChanges] = useState(false);
// Get current order from constants
const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.const.getConstants.useQuery();
// Get current order from the region constants
const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.region.getRegionConstants.useQuery();
const { data: allProducts, isLoading: isLoadingProducts, error: productsError } = trpc.common.product.getAllProductsSummary.useQuery();
const updateConstants = trpc.admin.const.updateConstants.useMutation();
const updateConstants = trpc.admin.region.updateRegionConstants.useMutation();
// Initialize products from constants
useEffect(() => {
@ -169,14 +169,14 @@ export default function AllItemsOrder() {
{
constants: [{
key: 'allItemsOrder',
value: productIds
value: productIds.join(',')
}]
},
{
onSuccess: () => {
setHasChanges(false);
Alert.alert('Success', 'All items order updated successfully!');
utils.admin.const.getConstants.invalidate();
utils.admin.region.getRegionConstants.invalidate();
},
onError: (error) => {
Alert.alert('Error', 'Failed to update items order. Please try again.');

View file

@ -1,21 +1,36 @@
import React from 'react';
import React, { useEffect, useMemo, useState } from 'react';
import { View, ScrollView, Alert } from 'react-native';
import { Formik } from 'formik';
import { MyText, MyTextInput, MyTouchableOpacity, tw, AppContainer, Checkbox } from 'common-ui';
import { trpc } from '../../../../src/trpc-client';
import { trpc } from '@/src/trpc-client';
import { useRouter } from 'expo-router';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
type ConstantFormData = Record<string, any>
type ConstTab = 'region' | 'bound'
// --- key groups (mirrors packages/db_helper_sqlite/src/lib/const-keys.ts) ---
// Region tab: region_consts minus the version counters (owned by the cache
// pipeline) and tagsOrder (edited on its own Tag Orders screen).
const REGION_KEYS = [
'popularItems', 'allItemsOrder',
'supportMobile', 'supportEmail', 'welcomeMessage',
]
const BOUND_KEYS = [
'freeDeliveryThreshold', 'deliveryCharge',
'flashFreeDeliveryThreshold', 'flashDeliveryCharge',
'isFlashDeliveryEnabled',
]
const CONST_LABELS: Record<string, string> = {
minRegularOrderValue: 'Minimum Regular Order Value',
freeDeliveryThreshold: 'Free Delivery Threshold',
deliveryCharge: 'Delivery Charge',
flashFreeDeliveryThreshold: 'Flash Free Delivery Threshold',
flashDeliveryCharge: 'Flash Delivery Charge',
platformFeePercent: 'Platform Fee Percent',
taxRate: 'Tax Rate',
tester: 'Tester',
minOrderAmountForCoupon: 'Minimum Order Amount for Coupon',
maxCouponDiscount: 'Maximum Coupon Discount',
flashDeliverySlotId: 'Flash Delivery Slot ID',
@ -25,6 +40,7 @@ const CONST_LABELS: Record<string, string> = {
appStoreUrl: 'App Store URL',
popularItems: 'Popular Items',
allItemsOrder: 'All Items Order',
tagsOrder: 'Tags Order',
isFlashDeliveryEnabled: 'Enable Flash Delivery',
supportMobile: 'Support Mobile',
supportEmail: 'Support Email',
@ -32,29 +48,74 @@ const CONST_LABELS: Record<string, string> = {
welcomeMessage: 'Welcome Message',
};
const CONST_VISIBILITY: Record<string, boolean> = {
minRegularOrderValue: true,
freeDeliveryThreshold: true,
deliveryCharge: true,
flashFreeDeliveryThreshold: true,
flashDeliveryCharge: true,
platformFeePercent: false,
taxRate: false,
minOrderAmountForCoupon: false,
maxCouponDiscount: false,
flashDeliverySlotId: false,
readableOrderId: false,
versionNum: false,
playStoreUrl: false,
appStoreUrl: false,
popularItems: true,
allItemsOrder: true,
isFlashDeliveryEnabled: true,
supportMobile: true,
supportEmail: true,
internalAppVersion: false,
welcomeMessage: true,
tester: false,
type ConstValueType = 'number' | 'boolean' | 'array' | 'string'
const KEY_TYPES: Record<string, ConstValueType> = {
freeDeliveryThreshold: 'number',
deliveryCharge: 'number',
flashFreeDeliveryThreshold: 'number',
flashDeliveryCharge: 'number',
popularItems: 'array',
allItemsOrder: 'array',
tagsOrder: 'array',
isFlashDeliveryEnabled: 'boolean',
supportMobile: 'string',
supportEmail: 'string',
welcomeMessage: 'string',
platformFeePercent: 'number',
taxRate: 'number',
tester: 'string',
minOrderAmountForCoupon: 'number',
maxCouponDiscount: 'number',
flashDeliverySlotId: 'number',
readableOrderId: 'number',
versionNum: 'string',
playStoreUrl: 'string',
appStoreUrl: 'string',
internalAppVersion: 'number',
};
/** Convert a stored string value into the type ConstantInput expects. */
const parseConstValue = (key: string, raw: string | null | undefined): any => {
const type = KEY_TYPES[key] ?? 'string';
if (raw === null || raw === undefined || raw === '') {
if (type === 'number') return 0;
if (type === 'boolean') return false;
if (type === 'array') return [];
return '';
}
switch (type) {
case 'number': {
const num = parseFloat(raw);
return isNaN(num) ? 0 : num;
}
case 'boolean':
return raw === 'true' || raw === '1' || raw === 'yes' || raw === 'on';
case 'array':
return raw.split(',').map((s) => s.trim()).filter((s) => s.length > 0);
default:
return raw;
}
};
/** Convert a form value back into the string stored by the constants API. */
const serializeConstValue = (key: string, value: any): string => {
const type = KEY_TYPES[key] ?? 'string';
switch (type) {
case 'number': {
const num = typeof value === 'number' ? value : parseFloat(value);
return isNaN(num) ? '0' : String(num);
}
case 'boolean':
return value ? 'true' : 'false';
case 'array':
return Array.isArray(value) ? value.join(',') : String(value ?? '');
default:
return value === null || value === undefined ? '' : String(value);
}
};
interface ConstantInputProps {
@ -62,13 +123,21 @@ interface ConstantInputProps {
value: any;
setFieldValue: (field: string, value: any) => void;
router: any;
/** When false, popularItems/allItemsOrder render as inline inputs instead of links. */
allowSectionNavigation?: boolean;
}
const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFieldValue, router }) => {
const ConstantInput: React.FC<ConstantInputProps> = ({
constantKey,
value,
setFieldValue,
router,
allowSectionNavigation = true,
}) => {
const fieldName = constantKey
// Special handling for popularItems - show navigation button instead of input
if (constantKey === 'popularItems') {
if (allowSectionNavigation && constantKey === 'popularItems') {
return (
<View>
<MyText style={tw`text-sm font-medium text-gray-700 mb-2`}>
@ -89,8 +158,7 @@ const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFi
}
// Special handling for allItemsOrder - show navigation button instead of input
if (constantKey === 'allItemsOrder') {
if (allowSectionNavigation && constantKey === 'allItemsOrder') {
return (
<View>
<MyText style={tw`text-sm font-medium text-gray-700 mb-2`}>
@ -182,7 +250,6 @@ const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFi
return (
<MyTextInput
topLabel={CONST_LABELS[constantKey] || constantKey}
// value={value === null || value === undefined ? '' : String(value)}
value={value}
onChangeText={(value) => {
setFieldValue(fieldName, value)
@ -194,104 +261,378 @@ const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFi
export default function CustomizeApp() {
const router = useRouter();
const { data: constants, isLoading: isLoadingConstants, refetch } = trpc.admin.const.getConstants.useQuery();
const { mutate: updateConstants, isPending: isUpdating } = trpc.admin.const.updateConstants.useMutation();
const [tab, setTab] = useState<ConstTab>('bound');
const [selectedBoundId, setSelectedBoundId] = useState<number | null>(null);
const handleSubmit = (values: ConstantFormData) => {
// Filter out constants that haven't changed
const changedConstants = (constants || []).filter((constant) => {
const nextValue = values[constant.key]
return JSON.stringify(nextValue) !== JSON.stringify(constant.value)
}).map((constant) => ({
key: constant.key,
value: values[constant.key],
}))
const { data: region } = trpc.admin.region.current.useQuery();
const {
data: bounds,
isLoading: isLoadingBounds,
isError: isBoundsError,
error: boundsError,
refetch: refetchBounds,
} = trpc.admin.region.bounds.useQuery();
if (changedConstants.length === 0) {
Alert.alert('No Changes', 'No constants were modified.');
// Only fetch the selected bound's settings (avoid requesting boundId 0).
const {
data: boundSettings,
isLoading: isLoadingBoundSettings,
isError: isBoundSettingsError,
error: boundSettingsError,
refetch: refetchBoundSettings,
} = trpc.admin.region.getBoundSettings.useQuery(
{ boundId: selectedBoundId ?? 0 },
{ enabled: selectedBoundId !== null }
);
const updateBoundSettings = trpc.admin.region.updateBoundSettings.useMutation();
// Region-scoped constants (region_consts) for the caller's region.
const {
data: regionConstants,
isLoading: isLoadingRegionConstants,
refetch: refetchRegionConstants,
} = trpc.admin.region.getRegionConstants.useQuery();
const updateRegionConstants = trpc.admin.region.updateRegionConstants.useMutation();
// Default-select the lowest-priority bound (first, ascending by priority).
useEffect(() => {
if (bounds && bounds.length > 0) {
setSelectedBoundId((prev) => {
if (prev !== null && bounds.some((b) => b.id === prev)) {
return prev;
}
return bounds[0].id;
});
}
}, [bounds]);
// The effective bound is the one with the lowest-numbered priority.
const effectiveBoundId = useMemo(() => {
if (!bounds || bounds.length === 0) return null;
return bounds.reduce((min, bound) =>
Number(bound.priority) < Number(min.priority) ? bound : min
).id;
}, [bounds]);
// Parse the selected bound's stored settings into form-ready values.
const boundInitialValues: Record<string, any> = useMemo(() => {
const values: Record<string, any> = {};
for (const key of BOUND_KEYS) {
values[key] = parseConstValue(key, boundSettings ? boundSettings[key] : null);
}
return values;
}, [boundSettings]);
const handleBoundSubmit = (values: ConstantFormData) => {
if (selectedBoundId === null) return;
const original = boundSettings ?? {};
const changed = BOUND_KEYS.filter((key) => {
const next = serializeConstValue(key, values[key]);
const prev = original[key] ?? null;
return next !== prev;
}).map((key) => ({
key,
value: serializeConstValue(key, values[key]),
}));
if (changed.length === 0) {
Alert.alert('No Changes', 'No settings were modified.');
return;
}
updateConstants(
{ constants: changedConstants },
updateBoundSettings.mutate(
{ boundId: selectedBoundId, settings: changed },
{
onSuccess: (response) => {
Alert.alert('Success', `Updated ${response.updatedCount} constants successfully.`);
refetch();
Alert.alert('Success', `Updated ${response.updatedCount} settings successfully.`);
refetchBoundSettings();
},
onError: (error) => {
Alert.alert('Error', 'Failed to update constants. Please try again.');
console.error('Update constants error:', error);
Alert.alert('Error', 'Failed to update settings. Please try again.');
console.error('Update bound settings error:', error);
},
}
);
};
if (isLoadingConstants) {
// --- Region tab ---
const regionValueByKey = useMemo(() => {
const map: Record<string, string | null> = {};
for (const row of regionConstants ?? []) map[row.key] = row.value as string | null;
return map;
}, [regionConstants]);
const regionInitialValues: ConstantFormData = useMemo(() => {
const values: ConstantFormData = {};
for (const key of REGION_KEYS) values[key] = parseConstValue(key, regionValueByKey[key]);
return values;
}, [regionValueByKey]);
const handleRegionSubmit = (values: ConstantFormData) => {
const changed = REGION_KEYS.filter((key) => {
const next = serializeConstValue(key, values[key]);
const prev = regionValueByKey[key] ?? null;
return next !== prev;
}).map((key) => ({ key, value: serializeConstValue(key, values[key]) }));
if (changed.length === 0) {
Alert.alert('No Changes', 'No region settings were modified.');
return;
}
updateRegionConstants.mutate(
{ constants: changed },
{
onSuccess: (response) => {
Alert.alert('Success', `Updated ${response.updatedCount} region settings successfully.`);
refetchRegionConstants();
},
onError: (error) => {
Alert.alert('Error', 'Failed to update region settings. Please try again.');
console.error('Update region constants error:', error);
},
}
);
};
const renderBound = () => {
if (isLoadingBounds) {
return (
<View style={tw`py-12 items-center`}>
<MyText style={tw`text-gray-500`}>Loading bounds...</MyText>
</View>
);
}
if (isBoundsError) {
return (
<View style={tw`py-12 items-center`}>
<MaterialIcons name="error-outline" size={48} color="#ef4444" />
<MyText style={tw`text-gray-700 mt-3 font-semibold`}>Failed to load bounds</MyText>
<MyText style={tw`text-gray-500 mt-1 text-center`}>
{boundsError?.message || 'Please try again.'}
</MyText>
<MyTouchableOpacity
onPress={() => refetchBounds()}
style={tw`mt-4 bg-blue-600 px-6 py-2 rounded-full`}
>
<MyText style={tw`text-white font-semibold`}>Retry</MyText>
</MyTouchableOpacity>
</View>
);
}
if (!bounds || bounds.length === 0) {
return (
<View style={tw`py-12 items-center`}>
<MaterialIcons name="map" size={48} color="#d1d5db" />
<MyText style={tw`text-gray-700 mt-3 font-semibold`}>No bounds configured</MyText>
<MyText style={tw`text-gray-500 mt-1 text-center`}>
This region has no bounds yet. Ask a superadmin to configure one.
</MyText>
</View>
);
}
const selectedBound = bounds.find((bound) => bound.id === selectedBoundId) ?? null;
return (
<View style={tw`flex-1 justify-center items-center`}>
<MyText style={tw`text-gray-500`}>Loading constants...</MyText>
<View>
<MyText style={tw`text-gray-600 mb-4`}>
Each bound stores its own business settings. The Effective bound (lowest
priority) is the one whose settings apply to checkout.
</MyText>
{/* One tab per bound, ordered ascending by priority. */}
<ScrollView horizontal showsHorizontalScrollIndicator={false} style={tw`mb-4`}>
{bounds.map((bound) => {
const isSelected = bound.id === selectedBoundId;
const isEffective = bound.id === effectiveBoundId;
return (
<MyTouchableOpacity
key={bound.id}
onPress={() => setSelectedBoundId(bound.id)}
style={tw`mr-2 px-4 py-2 rounded-lg border ${
isSelected ? 'bg-blue-600 border-blue-600' : 'bg-white border-gray-200'
}`}
>
<MyText
style={tw`${isSelected ? 'text-white' : 'text-gray-800'} font-semibold`}
>
{bound.description || `Bound #${bound.id}`}
</MyText>
<View style={tw`flex-row items-center mt-1`}>
<MyText
style={tw`${isSelected ? 'text-blue-100' : 'text-gray-400'} text-xs mr-2`}
>
Priority {bound.priority}
</MyText>
{isEffective && (
<View
style={tw`px-2 py-0.5 rounded-full ${
isSelected ? 'bg-white' : 'bg-green-100'
}`}
>
<MyText
style={tw`${
isSelected ? 'text-blue-700' : 'text-green-700'
} text-[10px] font-bold uppercase`}
>
Effective
</MyText>
</View>
)}
</View>
</MyTouchableOpacity>
);
})}
</ScrollView>
{selectedBound && (
<MyText style={tw`text-gray-500 text-sm mb-4`}>
Editing {selectedBound.description || `Bound #${selectedBound.id}`}
{selectedBound.id === effectiveBoundId ? ' — settings apply to checkout' : ''}
</MyText>
)}
{selectedBoundId === null || isLoadingBoundSettings ? (
<View style={tw`py-12 items-center`}>
<MyText style={tw`text-gray-500`}>Loading settings...</MyText>
</View>
) : isBoundSettingsError ? (
<View style={tw`py-12 items-center`}>
<MaterialIcons name="error-outline" size={48} color="#ef4444" />
<MyText style={tw`text-gray-700 mt-3 font-semibold`}>Failed to load settings</MyText>
<MyText style={tw`text-gray-500 mt-1 text-center`}>
{boundSettingsError?.message || 'Please try again.'}
</MyText>
<MyTouchableOpacity
onPress={() => refetchBoundSettings()}
style={tw`mt-4 bg-blue-600 px-6 py-2 rounded-full`}
>
<MyText style={tw`text-white font-semibold`}>Retry</MyText>
</MyTouchableOpacity>
</View>
) : (
// key forces a fresh form per bound so drafts never leak between tabs.
<Formik
key={selectedBoundId}
initialValues={boundInitialValues}
enableReinitialize
onSubmit={handleBoundSubmit}
>
{({ handleSubmit, values, setFieldValue }) => (
<View>
{BOUND_KEYS.map((key) => (
<View key={key} style={tw`mb-4`}>
<ConstantInput
constantKey={key}
value={values[key]}
setFieldValue={setFieldValue}
router={router}
allowSectionNavigation={false}
/>
</View>
))}
<MyTouchableOpacity
onPress={() => handleSubmit()}
disabled={updateBoundSettings.isPending}
style={tw`bg-blue-500 p-4 rounded-lg mt-6 ${
updateBoundSettings.isPending ? 'opacity-50' : ''
}`}
>
<MyText style={tw`text-white text-center font-semibold`}>
{updateBoundSettings.isPending ? 'Saving...' : 'Save Changes'}
</MyText>
</MyTouchableOpacity>
</View>
)}
</Formik>
)}
</View>
);
}
};
const renderRegion = () => {
if (isLoadingRegionConstants) {
return (
<View style={tw`py-12 items-center`}>
<MyText style={tw`text-gray-500`}>Loading region settings...</MyText>
</View>
);
}
if (!constants) {
return (
<View style={tw`flex-1 justify-center items-center`}>
<MyText style={tw`text-gray-500`}>Failed to load constants</MyText>
</View>
<Formik initialValues={regionInitialValues} enableReinitialize onSubmit={handleRegionSubmit}>
{({ handleSubmit, values, setFieldValue }) => (
<View>
<MyText style={tw`text-gray-500 text-sm mb-4`}>
Region settings apply to every bound in this region.
</MyText>
{REGION_KEYS.map((key) => (
<View key={key} style={tw`mb-4`}>
<ConstantInput
constantKey={key}
value={values[key]}
setFieldValue={setFieldValue}
router={router}
/>
</View>
))}
<MyTouchableOpacity
onPress={() => handleSubmit()}
disabled={updateRegionConstants.isPending}
style={tw`bg-blue-500 p-4 rounded-lg mt-6 ${
updateRegionConstants.isPending ? 'opacity-50' : ''
}`}
>
<MyText style={tw`text-white text-center font-semibold`}>
{updateRegionConstants.isPending ? 'Saving...' : 'Save Changes'}
</MyText>
</MyTouchableOpacity>
</View>
)}
</Formik>
);
}
const initialValues: ConstantFormData = constants.reduce((acc, constant) => {
acc[constant.key] = constant.value ?? ''
return acc
}, {} as ConstantFormData)
};
const tabs: { id: ConstTab; label: string }[] = [
{ id: 'region', label: 'Region' },
{ id: 'bound', label: 'Bound' },
];
return (
<AppContainer>
<View style={tw`flex-1 bg-gray-50 p-4`}>
<MyText style={tw`text-xl font-bold mb-4`}>Customize App Constants</MyText>
<MyText style={tw`text-gray-600 mb-6`}>
Modify application constants. Changes will take effect immediately.
</MyText>
<MyText style={tw`text-xl font-bold`}>Customize App</MyText>
<MyText style={tw`text-gray-500 mt-1`}>
{region?.name ? `Region: ${region.name}` : 'Regional business settings'}
</MyText>
<Formik initialValues={initialValues} onSubmit={handleSubmit}>
{({ handleSubmit, values, setFieldValue }) => (
<View>
{constants.map((constant) => {
if (!CONST_VISIBILITY[constant.key]) {
return null
}
return (
<View key={constant.key} style={tw`mb-4`}>
<ConstantInput
constantKey={constant.key}
value={values[constant.key]}
setFieldValue={setFieldValue}
router={router}
/>
</View>
)
})}
<MyTouchableOpacity
onPress={() => handleSubmit()}
disabled={isUpdating}
style={tw`bg-blue-500 p-4 rounded-lg mt-6 ${isUpdating ? 'opacity-50' : ''}`}
>
<MyText style={tw`text-white text-center font-semibold`}>
{isUpdating ? 'Updating...' : 'Save Changes'}
</MyText>
</MyTouchableOpacity>
</View>
)}
</Formik>
{/* Top-level switch: region vs. per-bound settings. */}
<View style={tw`flex-row bg-gray-100 rounded-lg p-1 mt-4 mb-4`}>
{tabs.map((t) => (
<MyTouchableOpacity
key={t.id}
onPress={() => setTab(t.id)}
style={tw`flex-1 py-2 rounded-md ${tab === t.id ? 'bg-white' : ''}`}
>
<MyText
style={tw`text-center ${
tab === t.id ? 'text-gray-900 font-semibold' : 'text-gray-500'
}`}
>
{t.label}
</MyText>
</MyTouchableOpacity>
))}
</View>
{tab === 'region' && renderRegion()}
{tab === 'bound' && renderBound()}
</AppContainer>
);
}

View file

@ -118,10 +118,10 @@ export default function CustomizePopularItems() {
const [showAddDialog, setShowAddDialog] = useState(false);
const [selectedProductIds, setSelectedProductIds] = useState<number[]>([]);
// Get current popular items from constants
const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.const.getConstants.useQuery();
// Get current popular items from the region constants
const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.region.getRegionConstants.useQuery();
const { data: allProducts, isLoading: isLoadingProducts, error: productsError } = trpc.common.product.getAllProductsSummary.useQuery();
const updateConstants = trpc.admin.const.updateConstants.useMutation();
const updateConstants = trpc.admin.region.updateRegionConstants.useMutation();
// Initialize popular products from constants
useEffect(() => {
@ -203,14 +203,14 @@ export default function CustomizePopularItems() {
{
constants: [{
key: 'popularItems',
value: popularIds
value: popularIds.join(',')
}]
},
{
onSuccess: () => {
setHasChanges(false);
Alert.alert('Success', 'Popular items updated successfully!');
utils.admin.const.getConstants.invalidate();
utils.admin.region.getRegionConstants.invalidate();
},
onError: (error) => {
Alert.alert('Error', 'Failed to update popular items. Please try again.');

View file

@ -410,9 +410,12 @@ export default function DashboardBanners() {
<MaterialIcons name="radio-button-checked" size={16} color="#10B981" />
</View>
)}
<View style={tw`w-2 h-2 rounded-full mr-2 ${
banner.isActive ? 'bg-green-500' : 'bg-gray-400'
}`} />
<View
testID={`banner-status-${banner.id}`}
style={tw`w-2 h-2 rounded-full mr-2 ${
banner.isActive ? 'bg-green-500' : 'bg-gray-400'
}`}
/>
{!editMode && (
<>
<TouchableOpacity onPress={() => handleEdit(banner)} style={tw`p-1 mr-1`}>

View file

@ -137,6 +137,7 @@ const OrderItem: React.FC<OrderItemProps> = ({
{/* Checkbox and Drag Handle */}
<View style={tw`mr-4 flex-col items-center`}>
<Checkbox
testID={`sequence-select-${orderItem.id}`}
checked={selectedOrderIds.includes(orderItem.id)}
onPress={() => onToggleOrder(orderItem.id)}
size={20}
@ -181,6 +182,7 @@ const OrderItem: React.FC<OrderItemProps> = ({
</MyText>
</View>
<TouchableOpacity
testID={`sequence-menu-${orderItem.id}`}
onPress={() => {
setSelectedOrder(orderItem);
setShowOrderMenu(true);
@ -505,6 +507,7 @@ export default function DeliverySequences() {
<View style={tw`flex-2 mx-2`}>
<BottomDropdown
testID="delivery-sequence-slot-dropdown"
label="Select Slot"
options={slotOptions}
value={selectedSlotId || ""}
@ -518,6 +521,7 @@ export default function DeliverySequences() {
</View>
<View style={tw`flex-1 mx-2`}>
<BottomDropdown
testID="delivery-sequence-user-dropdown"
label="Select User"
options={userOptions}
value={selectedUserId}

View file

@ -88,6 +88,7 @@ export default function ManageOrders() {
<>
<View style={tw`mb-6`}>
<BottomDropdown
testID="manage-orders-slot-dropdown"
label='Select Slot'
options={slotOptions}
value={selectedSlotId || ''}

View file

@ -18,13 +18,7 @@ import { UserIncidentsView } from "@/components/UserIncidentsView";
export default function OrderDetails() {
const { id } = useLocalSearchParams<{ id: string }>();
const router = useRouter();
const [generateCouponDialogOpen, setGenerateCouponDialogOpen] =
useState(false);
const [initiateRefundDialogOpen, setInitiateRefundDialogOpen] =
useState(false);
const [cancelDialogOpen, setCancelDialogOpen] = useState(false);
const [refundType, setRefundType] = useState<"percent" | "amount">("percent");
const [refundValue, setRefundValue] = useState("100");
const [updatingItems, setUpdatingItems] = useState<Set<number>>(new Set());
const {
@ -37,45 +31,6 @@ export default function OrderDetails() {
{ enabled: !!id }
);
const generateCouponMutation =
trpc.admin.coupon.generateCancellationCoupon.useMutation({
onSuccess: (coupon) => {
Alert.alert(
"Success",
`Refund coupon generated successfully!\n\nCode: ${coupon.couponCode
}\nValue: ₹${coupon.flatDiscount}\nExpires: ${coupon.validTill
? new Date(coupon.validTill).toLocaleDateString()
: "N/A"
}`
);
refetch();
setGenerateCouponDialogOpen(false);
},
onError: (error: any) => {
Alert.alert(
"Error",
error.message || "Failed to generate refund coupon"
);
},
});
const initiateRefundMutation = trpc.admin.payments.initiateRefund.useMutation(
{
onSuccess: (result) => {
Alert.alert(
"Success",
`Refund initiated successfully!\n\nAmount: `
// `Refund initiated successfully!\n\nAmount: ₹${result.amount}\nStatus: ${result.status}`
);
refetch();
setInitiateRefundDialogOpen(false);
},
onError: (error: any) => {
Alert.alert("Error", error.message || "Failed to initiate refund");
},
}
);
const updateItemPackagingMutation = trpc.admin.order.updateOrderItemPackaging.useMutation({
onSuccess: () => {
// Refetch order details to get updated packaging status
@ -136,35 +91,6 @@ export default function OrderDetails() {
const subtotal = order.items.reduce((sum, item) => sum + item.amount, 0);
const discountAmount = order.discountAmount || 0;
const handleGenerateCoupon = () => {
generateCouponMutation.mutate({ orderId: order.id });
};
const handleInitiateRefund = () => {
const value = parseFloat(refundValue);
if (isNaN(value) || value <= 0) {
Alert.alert("Error", "Please enter a valid refund value");
return;
}
const mutationData: any = {
orderId: order.id,
};
if (refundType === "percent") {
if (value > 100) {
Alert.alert("Error", "Refund percentage cannot exceed 100%");
return;
}
mutationData.refundPercent = value;
} else {
mutationData.refundAmount = value;
}
initiateRefundMutation.mutate(mutationData);
setInitiateRefundDialogOpen(false);
};
const handlePackagingToggle = (itemId: number, field: 'isPackaged' | 'isPackageVerified', value: boolean) => {
// Add item to updating set to disable UI
setUpdatingItems(prev => new Set(prev).add(itemId));
@ -199,30 +125,7 @@ export default function OrderDetails() {
};
const statusStyle = getStatusColor(order.status);
const showRefundOptions = true;
const getRefundDotColor = (status: string) => {
if (status === 'success') return 'bg-green-500';
else if (status === 'pending') return 'bg-yellow-500';
else if (status === 'failed') return 'bg-red-500';
else return 'bg-gray-500';
};
const getRefundTextColor = (status: string) => {
if (status === 'success' || status === 'na') return 'text-green-700';
else if (status === 'pending') return 'text-yellow-700';
else if (status === 'failed') return 'text-red-700';
else return 'text-gray-700';
};
const getRefundStatusText = (status: string) => {
if (status === 'success' || status === 'na') return 'Completed';
else if (status === 'pending') return 'Pending';
else if (status === 'failed') return 'Failed';
else if (status === 'none') return 'Not Initiated';
else if (status === 'na') return 'Not Applicable';
else return 'Unknown';
};
return (
<AppContainer>
@ -369,7 +272,7 @@ export default function OrderDetails() {
</MyText>
{order.isFlashDelivery && (
<MyText style={tw`text-[9px] font-bold text-amber-600 mt-0.5`}>
⚡ 30-Min
⚡ 1-Hour
</MyText>
)}
</View>
@ -380,6 +283,7 @@ export default function OrderDetails() {
{/* Customer Details */}
<TouchableOpacity
testID="customer-details-card"
onPress={() => order.userId && router.push(`/(drawer)/dashboard/user-management/${order.userId}`)}
activeOpacity={0.7}
style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}
@ -435,7 +339,7 @@ export default function OrderDetails() {
{order.address.name} {' '}
{order.address.line1}
{order.address.line2 ? `, ${order.address.line2}` : ""}
{`\n${order.address.city}, ${order.address.state} - ${order.address.pincode}`}
{`\n${order.address.city}, ${order.address.state}`}
</MyText>
</View>
</View>
@ -469,6 +373,7 @@ export default function OrderDetails() {
</MyText>
<View style={tw`flex-row items-center mt-2 gap-3`}>
<TouchableOpacity
testID={`order-item-packaged-${item.id}`}
style={tw`flex-row items-center`}
onPress={() => handlePackagingToggle(item.id, 'isPackaged', !item.isPackaged)}
disabled={updatingItems.has(item.id)}
@ -483,6 +388,7 @@ export default function OrderDetails() {
</MyText>
</TouchableOpacity>
<TouchableOpacity
testID={`order-item-verified-${item.id}`}
style={tw`flex-row items-center`}
onPress={() => handlePackagingToggle(item.id, 'isPackageVerified', !item.isPackageVerified)}
disabled={updatingItems.has(item.id)}
@ -530,6 +436,7 @@ export default function OrderDetails() {
Delivery Charge
</MyText>
<TouchableOpacity
testID="remove-delivery-charge"
onPress={() => {
Alert.alert(
'Remove Delivery Cost',
@ -652,121 +559,6 @@ export default function OrderDetails() {
</View>
)}
{/* Refund Coupon Section */}
{order.orderStatus?.refundCouponId && (
<View style={tw`bg-blue-50 p-5 rounded-2xl shadow-sm mb-4 border border-blue-100`}>
<MyText style={tw`text-lg font-bold text-blue-800 mb-3`}>
Refund Coupon
</MyText>
<View style={tw`bg-blue-100 p-4 rounded-xl border border-blue-200`}>
<View style={tw`flex-row items-center mb-2`}>
<MaterialIcons name="local-offer" size={20} color="#2563EB" />
<MyText style={tw`text-blue-800 font-bold ml-2`}>
{order.couponCode}
</MyText>
</View>
<MyText style={tw`text-blue-700 text-sm`}>
Generated refund coupon for order cancellation
</MyText>
<View style={tw`flex-row justify-between items-center mt-3`}>
<MyText style={tw`text-blue-600 font-medium`}>
Value:
</MyText>
<MyText style={tw`text-blue-800 font-bold text-lg`}>
₹{order.couponData?.discountAmount}
</MyText>
</View>
{/* <View style={tw`flex-row justify-between items-center mt-2`}>
<MyText style={tw`text-blue-600 font-medium`}>
Expires:
</MyText>
<MyText style={tw`text-blue-800 font-medium`}>
{order.couponData?.
? dayjs(order.orderStatus.refundCoupon.validTill).format("DD MMM YYYY")
: "N/A"}
</MyText>
</View> */}
</View>
</View>
)}
{/* TEMPORARILY HIDDEN: Refund Details Section */}
{/* WARNING: This section contains functional refund and cancellation management features */}
{/* DO NOT REMOVE - This is temporarily commented out for UI simplification */}
{/* When ready to re-enable, simply uncomment the entire block below */}
{/*
<View
style={tw`bg-red-50 p-5 rounded-2xl border border-red-100 mb-4`}
>
<MyText style={tw`text-sm font-bold text-red-800 mb-3`}>
{order.status === "cancelled" ? "Cancellation Details" : "Refund Details"}
</MyText>
{order.status === "cancelled" && order.cancelReason && (
<View style={tw`mb-3`}>
<MyText
style={tw`text-xs text-red-600 uppercase font-bold mb-1`}
>
Cancellation Reason
</MyText>
<MyText style={tw`text-sm text-red-900`}>
{order.cancelReason}
</MyText>
</View>
)}
<View
style={tw`flex-row justify-between items-center bg-white/50 p-3 rounded-xl mb-4`}
>
<MyText style={tw`text-sm font-medium text-red-800`}>
Refund Status
</MyText>
<View style={tw`flex-row items-center`}>
<View
style={tw`w-2 h-2 rounded-full mr-2 ${getRefundDotColor(order.refundStatus)}`}
/>
<MyText
style={tw`text-sm font-bold ${getRefundTextColor(order.refundStatus)}`}
>
{getRefundStatusText(order.refundStatus)}
</MyText>
</View>
</View>
{order.refundRecord && (
<View
style={tw`flex-row justify-between items-center bg-white/50 p-3 rounded-xl mb-4`}
>
<MyText style={tw`text-sm font-medium text-red-800`}>
Refund Amount
</MyText>
<MyText style={tw`text-sm font-bold text-red-900`}>
₹{order.refundRecord.refundAmount}
</MyText>
</View>
)}
{(!Boolean(order.refundRecord)) && <View style={tw`flex-row gap-3 mt-2`}>
{!order.isCod && (<TouchableOpacity
style={tw`flex-1 bg-red-500 py-3 px-4 rounded-xl items-center flex-row justify-center shadow-sm`}
onPress={() => setInitiateRefundDialogOpen(true)}
>
<MaterialIcons name="payments" size={18} color="white" style={tw`mr-2`} />
<MyText style={tw`text-white font-bold text-sm`}>
Initiate Refund
</MyText>
</TouchableOpacity>
)}
<TouchableOpacity
style={tw`flex-1 bg-emerald-500 py-3 px-4 rounded-xl items-center flex-row justify-center shadow-sm`}
onPress={() => setGenerateCouponDialogOpen(true)}
>
<MaterialIcons name="local-offer" size={18} color="white" style={tw`mr-2`} />
<MyText style={tw`text-white font-bold text-sm`}>
Generate Refund Coupon
</MyText>
</TouchableOpacity>
</View>}
</View>
*/}
</View>
<View style={tw`h-32`}></View>
@ -777,6 +569,7 @@ export default function OrderDetails() {
>
{order.status !== "cancelled" && (
<TouchableOpacity
testID="order-details-cancel-button"
onPress={() => setCancelDialogOpen(true)}
style={tw`bg-red-500 rounded-xl py-4 items-center shadow-lg mb-3`}
>
@ -786,6 +579,7 @@ export default function OrderDetails() {
</TouchableOpacity>
)}
<TouchableOpacity
testID="order-details-back-button"
onPress={() => router.push("/(drawer)/dashboard/manage-orders")}
style={tw`bg-gray-900 rounded-xl py-4 items-center shadow-lg`}
>
@ -795,163 +589,6 @@ export default function OrderDetails() {
</TouchableOpacity>
</View>
{/* Generate Coupon Dialog */}
<BottomDialog
open={generateCouponDialogOpen}
onClose={() => setGenerateCouponDialogOpen(false)}
>
<View style={tw`p-6`}>
<View style={tw`items-center mb-6`}>
<View style={tw`w-12 h-12 bg-emerald-100 rounded-full items-center justify-center mb-3`}>
<MaterialIcons name="local-offer" size={24} color="#10B981" />
</View>
<MyText style={tw`text-xl font-bold text-gray-900 text-center`}>
Generate Refund Coupon
</MyText>
<MyText style={tw`text-gray-500 text-center mt-2 text-sm leading-5`}>
Create a one-time use coupon for the customer equal to the order amount. Valid for 30 days.
</MyText>
</View>
<View style={tw`bg-amber-50 p-4 rounded-xl border border-amber-100 mb-6 flex-row items-start`}>
<MaterialIcons name="info-outline" size={20} color="#D97706" style={tw`mt-0.5`} />
<MyText style={tw`text-sm text-amber-800 ml-2 flex-1 leading-5`}>
This only works for online payment orders. COD orders cannot generate refund coupons.
</MyText>
</View>
<View style={tw`flex-row gap-3`}>
<TouchableOpacity
style={tw`flex-1 bg-gray-100 py-3.5 rounded-xl items-center`}
onPress={() => setGenerateCouponDialogOpen(false)}
>
<MyText style={tw`text-gray-700 font-bold`}>Cancel</MyText>
</TouchableOpacity>
<TouchableOpacity
style={tw`flex-1 bg-emerald-500 py-3.5 rounded-xl items-center shadow-sm`}
onPress={handleGenerateCoupon}
disabled={generateCouponMutation.isPending}
>
<MyText style={tw`text-white font-bold`}>
{generateCouponMutation.isPending
? "Generating..."
: "Generate Coupon"}
</MyText>
</TouchableOpacity>
</View>
</View>
</BottomDialog>
{/* Initiate Refund Dialog */}
<BottomDialog
open={initiateRefundDialogOpen}
onClose={() => setInitiateRefundDialogOpen(false)}
>
<View style={tw`p-6`}>
<View style={tw`items-center mb-6`}>
<View style={tw`w-12 h-12 bg-red-100 rounded-full items-center justify-center mb-3`}>
<MaterialIcons name="payments" size={24} color="#EF4444" />
</View>
<MyText style={tw`text-xl font-bold text-gray-900 text-center`}>
Initiate Refund
</MyText>
<MyText style={tw`text-gray-500 text-center mt-2 text-sm`}>
Process a refund directly to the customer&apos;s source account via Razorpay.
</MyText>
</View>
{/* Refund Type Selection */}
<View style={tw`mb-6`}>
<MyText style={tw`text-sm font-bold text-gray-900 mb-3 uppercase tracking-wide`}>
Refund Type
</MyText>
<View style={tw`flex-row gap-3`}>
<TouchableOpacity
style={tw`flex-1 p-4 rounded-xl border-2 ${refundType === "percent"
? "border-blue-500 bg-blue-50"
: "border-gray-100 bg-gray-50"
} items-center`}
onPress={() => setRefundType("percent")}
>
<MaterialIcons
name="percent"
size={24}
color={refundType === "percent" ? "#3B82F6" : "#9CA3AF"}
style={tw`mb-2`}
/>
<MyText
style={tw`text-sm font-bold ${refundType === "percent" ? "text-blue-700" : "text-gray-500"
}`}
>
Percentage
</MyText>
</TouchableOpacity>
<TouchableOpacity
style={tw`flex-1 p-4 rounded-xl border-2 ${refundType === "amount"
? "border-blue-500 bg-blue-50"
: "border-gray-100 bg-gray-50"
} items-center`}
onPress={() => setRefundType("amount")}
>
<MaterialIcons
name="attach-money"
size={24}
color={refundType === "amount" ? "#3B82F6" : "#9CA3AF"}
style={tw`mb-2`}
/>
<MyText
style={tw`text-sm font-bold ${refundType === "amount" ? "text-blue-700" : "text-gray-500"
}`}
>
Fixed Amount
</MyText>
</TouchableOpacity>
</View>
</View>
{/* Refund Value Input */}
<View style={tw`mb-6`}>
<MyTextInput
topLabel={`Refund ${refundType === "percent" ? "Percentage (%)" : "Amount (₹)"
}`}
value={refundValue}
onChangeText={setRefundValue}
keyboardType="numeric"
placeholder={refundType === "percent" ? "100" : "0.00"}
style={tw`bg-white`}
/>
</View>
<View style={tw`bg-amber-50 p-4 rounded-xl border border-amber-100 mb-6 flex-row items-start`}>
<MaterialIcons name="info-outline" size={20} color="#D97706" style={tw`mt-0.5`} />
<MyText style={tw`text-sm text-amber-800 ml-2 flex-1 leading-5`}>
For COD orders, refunds are processed immediately upon delivery confirmation.
</MyText>
</View>
<View style={tw`flex-row gap-3`}>
<TouchableOpacity
style={tw`flex-1 bg-gray-100 py-3.5 rounded-xl items-center`}
onPress={() => setInitiateRefundDialogOpen(false)}
>
<MyText style={tw`text-gray-700 font-bold`}>Cancel</MyText>
</TouchableOpacity>
<TouchableOpacity
style={tw`flex-1 bg-red-500 py-3.5 rounded-xl items-center shadow-sm`}
onPress={handleInitiateRefund}
disabled={initiateRefundMutation.isPending}
>
<MyText style={tw`text-white font-bold`}>
{initiateRefundMutation.isPending
? "Processing..."
: "Confirm Refund"}
</MyText>
</TouchableOpacity>
</View>
</View>
</BottomDialog>
{/* Cancel Order Dialog */}
<CancelOrderDialog
orderId={order.id}

View file

@ -154,6 +154,7 @@ const OrderItem = ({ order, refetch }: { order: OrderType; refetch: () => void }
return (
<>
<TouchableOpacity
testID={`order-card-${order.id}`}
style={tw`bg-white mx-4 mb-4 rounded-xl shadow-sm border border-gray-100 overflow-hidden`}
onPress={handleOrderPress}
activeOpacity={0.9}
@ -191,6 +192,7 @@ const OrderItem = ({ order, refetch }: { order: OrderType; refetch: () => void }
</View>
<TouchableOpacity
testID={`order-menu-${order.id}`}
onPress={() => setMenuOpen(true)}
style={tw`p-2 -mr-2 -mt-2 rounded-full`}
>
@ -206,14 +208,10 @@ const OrderItem = ({ order, refetch }: { order: OrderType; refetch: () => void }
{/* <View style={tw`px-2.5 py-1 rounded-full ${getStatusColor(order.status)}`}>
<MyText style={tw`text-xs font-semibold capitalize`}>{order.status}</MyText>
</View> */}
{/* {order.isCod && (
<View style={tw`px-2.5 py-1 rounded-full bg-blue-50 border border-blue-100`}>
<MyText style={tw`text-xs font-semibold text-blue-700`}>COD</MyText>
</View>
)} */}
<View style={tw`flex-row items-center gap-1`}>
<MyText style={tw`text-sm font-semibold text-gray-600`}>Packaged</MyText>
<Checkbox
testID={`order-packaged-${order.id}`}
checked={order.isPackaged}
// onPress={() => handleMarkPackaged(!order.isPackaged)}
onPress={() => {}}
@ -225,6 +223,7 @@ const OrderItem = ({ order, refetch }: { order: OrderType; refetch: () => void }
<View style={tw`flex-row items-center gap-1`}>
<MyText style={tw`text-xs font-semibold text-gray-600`}>Delivered</MyText>
<Checkbox
testID={`order-delivered-${order.id}`}
checked={order.isDelivered}
onPress={() => handleMarkDelivered(!order.isDelivered)}
size={18}
@ -269,6 +268,7 @@ const OrderItem = ({ order, refetch }: { order: OrderType; refetch: () => void }
<View style={tw`mb-2`}>
<View style={tw`flex-row justify-between items-center`}>
<TouchableOpacity
testID={`order-items-${order.id}`}
onPress={() => setItemsDialogOpen(true)}
style={tw`flex-row items-center py-2 px-3 bg-blue-50 rounded-lg flex-1 mr-3`}
>
@ -316,6 +316,7 @@ const OrderItem = ({ order, refetch }: { order: OrderType; refetch: () => void }
<View style={tw`flex-row gap-2`}>
{order.userNotes && (
<TouchableOpacity
testID={`order-user-notes-${order.id}`}
style={tw`flex-row items-center p-3 bg-amber-50 rounded-lg flex-1`}
onPress={() => setUserNotesDialogOpen(true)}
>
@ -327,6 +328,7 @@ const OrderItem = ({ order, refetch }: { order: OrderType; refetch: () => void }
)}
{order.adminNotes && (
<TouchableOpacity
testID={`order-admin-notes-${order.id}`}
style={tw`flex-row items-center p-3 bg-blue-50 rounded-lg flex-1`}
onPress={() => setNotesDialogOpen(true)}
>
@ -414,6 +416,7 @@ const OrderItem = ({ order, refetch }: { order: OrderType; refetch: () => void }
<View style={tw`flex-row items-center gap-1 mr-3`}>
<MyText style={tw`text-sm font-medium text-gray-600`}>pkg</MyText>
<Checkbox
testID={`order-item-packaged-${item.id}`}
checked={item.isPackaged}
onPress={() => handleItemPackagingToggle(item.id!, 'isPackaged', !item.isPackaged)}
size={18}
@ -424,6 +427,7 @@ const OrderItem = ({ order, refetch }: { order: OrderType; refetch: () => void }
<View style={tw`flex-row items-center gap-1`}>
<MyText style={tw`text-sm font-medium text-gray-600`}>verf</MyText>
<Checkbox
testID={`order-item-verified-${item.id}`}
checked={item.isPackageVerified}
onPress={() => handleItemPackagingToggle(item.id!, 'isPackageVerified', !item.isPackageVerified)}
size={18}
@ -563,6 +567,7 @@ export default function Orders() {
<View style={tw`flex-row justify-between items-center p-4 bg-white`}>
<View style={tw`flex-1 mr-4`}>
<BottomDropdown
testID="orders-slot-dropdown"
label="Select Slot"
options={slotOptions}
value={selectedSlotType === 'flash' ? 'flash' : (selectedSlot?.toString() || '')}
@ -591,6 +596,7 @@ export default function Orders() {
/>
</View>
<TouchableOpacity
testID="orders-filter-button"
onPress={() => setFilterDialogOpen(true)}
style={tw`p-2`}
>
@ -625,6 +631,7 @@ export default function Orders() {
<MyText style={tw`text-lg font-semibold mb-2`}>Packaged Status</MyText>
<View style={tw`flex-row items-center mb-2`}>
<Checkbox
testID="filter-packaged"
checked={packagedChecked}
onPress={() => {
const newValue = !packagedChecked;
@ -644,6 +651,7 @@ export default function Orders() {
</View>
<View style={tw`flex-row items-center`}>
<Checkbox
testID="filter-not-packaged"
checked={notPackagedChecked}
onPress={() => {
const newValue = !notPackagedChecked;
@ -666,6 +674,7 @@ export default function Orders() {
<MyText style={tw`text-lg font-semibold mb-2`}>Delivered Status</MyText>
<View style={tw`flex-row items-center mb-2`}>
<Checkbox
testID="filter-delivered"
checked={deliveredChecked}
onPress={() => {
const newValue = !deliveredChecked;
@ -685,6 +694,7 @@ export default function Orders() {
</View>
<View style={tw`flex-row items-center`}>
<Checkbox
testID="filter-not-delivered"
checked={notDeliveredChecked}
onPress={() => {
const newValue = !notDeliveredChecked;
@ -707,6 +717,7 @@ export default function Orders() {
<MyText style={tw`text-lg font-semibold mb-2`}>Cancellation Status</MyText>
<View style={tw`flex-row items-center mb-2`}>
<Checkbox
testID="filter-cancelled"
checked={cancelledChecked}
onPress={() => {
const newValue = !cancelledChecked;
@ -726,6 +737,7 @@ export default function Orders() {
</View>
<View style={tw`flex-row items-center`}>
<Checkbox
testID="filter-not-cancelled"
checked={notCancelledChecked}
onPress={() => {
const newValue = !notCancelledChecked;
@ -748,6 +760,7 @@ export default function Orders() {
<MyText style={tw`text-lg font-semibold mb-2`}>Delivery Type</MyText>
<View style={tw`flex-row items-center mb-2`}>
<Checkbox
testID="filter-flash"
checked={flashChecked}
onPress={() => {
const newValue = !flashChecked;
@ -767,6 +780,7 @@ export default function Orders() {
</View>
<View style={tw`flex-row items-center`}>
<Checkbox
testID="filter-regular"
checked={regularChecked}
onPress={() => {
const newValue = !regularChecked;

View file

@ -78,6 +78,7 @@ const SkuItemComponent: React.FC<SkuItemProps> = ({
</View>
<View style={tw`flex-row items-center ml-2`}>
<Checkbox
testID={`flash-checkbox-${sku.id}`}
checked={change.isFlashAvailable ?? sku.isFlashAvailable ?? false}
onPress={() => {
const currentValue = change.isFlashAvailable ?? sku.isFlashAvailable ?? false;
@ -101,7 +102,7 @@ const SkuItemComponent: React.FC<SkuItemProps> = ({
<MyText style={tw`text-xs text-gray-500 mb-1`}>Our Price</MyText>
<View style={tw`flex-row items-center`}>
<MyText style={tw`text-sm font-bold text-green-600`}>₹{displayPrice}</MyText>
<TouchableOpacity onPress={() => openEditDialog(sku, productName)} style={tw`ml-1`}>
<TouchableOpacity testID={`edit-sku-price-${sku.id}`} onPress={() => openEditDialog(sku, productName)} style={tw`ml-1`}>
<MaterialIcons name="edit" size={14} color="#6b7280" />
</TouchableOpacity>
</View>
@ -267,7 +268,7 @@ export default function PricesOverview() {
const handleSave = () => {
const updates = Object.entries(pendingChanges).map(([skuId, change]) => {
const sku = allSkus.find(s => s.id === parseInt(skuId));
const update: any = { productId: sku?.id };
const update: any = { skuId: sku?.id };
if (change.price !== undefined) update.price = change.price;
if (change.marketPrice !== undefined) update.marketPrice = change.marketPrice;
if (change.flashPrice !== undefined) update.flashPrice = change.flashPrice;
@ -297,6 +298,7 @@ export default function PricesOverview() {
<View style={tw`bg-white px-4 py-4 border-b border-gray-200 flex-row items-center`}>
<View style={tw`flex-1 mr-4`}>
<BottomDropdown
testID="store-filter-dropdown"
label="Filter by Stores"
options={storeOptions}
value={selectedStores}
@ -306,6 +308,7 @@ export default function PricesOverview() {
/>
</View>
<TouchableOpacity
testID="save-prices-button"
style={[
tw`px-4 py-2 rounded-lg flex-row items-center mr-3`,
changeCount > 0 && !updatePricesMutation.isPending ? tw`bg-blue-600` : tw`bg-gray-300`,
@ -333,6 +336,7 @@ export default function PricesOverview() {
</MyText>
</TouchableOpacity>
<TouchableOpacity
testID="prices-options-button"
onPress={() => setShowMenu(true)}
style={tw`p-2 -mr-2`}
>

View file

@ -82,10 +82,10 @@ export default function TagOrders() {
const [tags, setTags] = useState<Tag[]>([]);
const [hasChanges, setHasChanges] = useState(false);
// Get current order from constants
const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.const.getConstants.useQuery();
// Get current order from the region constants
const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.region.getRegionConstants.useQuery();
const { data: tagsData, isLoading: isLoadingTags, error: tagsError } = trpc.admin.product.getProductTags.useQuery();
const updateConstants = trpc.admin.const.updateConstants.useMutation();
const updateConstants = trpc.admin.region.updateRegionConstants.useMutation();
// Initialize tags from the tagsOrder constant
useEffect(() => {
@ -158,14 +158,14 @@ export default function TagOrders() {
{
constants: [{
key: 'tagsOrder',
value: tagIds
value: tagIds.join(',')
}]
},
{
onSuccess: () => {
setHasChanges(false);
Alert.alert('Success', 'Tag order updated successfully!');
utils.admin.const.getConstants.invalidate();
utils.admin.region.getRegionConstants.invalidate();
},
onError: (error) => {
Alert.alert('Error', 'Failed to update tag order. Please try again.');

View file

@ -86,7 +86,7 @@ export default function AddProduct() {
isOffer: variant.isOffer || false,
isComboOnly: variant.isComboOnly || false,
isDeleted: variant.isDeleted || false,
isSuspended: variant.isSuspended || false,
isSuspendedInRegion: variant.isSuspendedInRegion || false,
features: variant.features.map((attr: any) => ({
featureName: attr.featureName,
featureValue: attr.featureValue,
@ -118,7 +118,9 @@ export default function AddProduct() {
name: '',
shortDescription: '',
longDescription: '',
storeId: 1,
// 0 = "no store chosen yet"; ProductForm fills in the first available store
// (regional preferred) once the store list loads.
storeId: 0,
productType: 'item' as const,
variants: [
{
@ -131,7 +133,7 @@ export default function AddProduct() {
isOffer: false,
isComboOnly: false,
isDeleted: false,
isSuspended: false,
isSuspendedInRegion: false,
features: [{ featureName: 'quantity', featureValue: '' }],
comboItems: [],
},

View file

@ -198,7 +198,7 @@ export default function ProductDetail() {
showPaginationDots={true}
/>
) : (
<View style={{ width: screenWidth, height: carouselHeight, backgroundColor: '#E5E7EB', alignItems: 'center', justifyContent: 'center' }} />
<View testID="product-hero-placeholder" style={{ width: screenWidth, height: carouselHeight, backgroundColor: '#E5E7EB', alignItems: 'center', justifyContent: 'center' }} />
)}
{/* Gradient Overlay */}
@ -209,7 +209,7 @@ export default function ProductDetail() {
{/* Floating Header Buttons */}
<View style={tw`absolute top-${Platform.OS === 'ios' ? '12' : '8'} left-4 right-4 flex-row justify-between items-center z-10`}>
<TouchableOpacity onPress={() => router.back()} activeOpacity={0.8}>
<TouchableOpacity testID="product-detail-back" onPress={() => router.back()} activeOpacity={0.8}>
<BlurView intensity={80} tint="dark" style={tw`w-10 h-10 rounded-full items-center justify-center overflow-hidden`}>
<Ionicons name="arrow-back" size={24} color="white" />
</BlurView>

View file

@ -3,6 +3,7 @@ import { View, Alert } from 'react-native';
import { useLocalSearchParams } from 'expo-router';
import { AppContainer, useManualRefresh, MyText, tw, ImageUploaderNeoItem, ImageUploaderNeoPayload } from 'common-ui';
import ProductForm, { ProductFormRef } from '@/src/components/ProductForm';
import GlobalProductForm from '@/src/components/GlobalProductForm';
import { trpc } from '@/src/trpc-client';
import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore';
@ -50,7 +51,7 @@ export default function EditProduct() {
name: productData.name,
shortDescription: productData.shortDescription || '',
longDescription: productData.longDescription || '',
storeId: productData.storeId || 1,
storeId: productData.storeId || 0,
productType: (productData.productType as 'item' | 'combo') || 'item',
variants: (productData.skus || []).map((sku) => ({
id: sku.id,
@ -62,7 +63,12 @@ export default function EditProduct() {
isOffer: sku.isOffer || false,
isComboOnly: sku.isComboOnly || false,
isDeleted: sku.isDeleted || false,
isSuspended: sku.isSuspended || false,
// The product form's suspend toggle is this region's suspension, not the
// superadmin's global kill-switch. Legacy rows still carry suspension in
// the structural column: show it here; the next regional save folds it
// into the region's market row.
isSuspendedInRegion:
sku.isSuspendedInRegion || (!productData.isGlobal && sku.isSuspended) || false,
features: (sku.features || []).map((f) => ({
featureName: f.featureName,
featureValue: f.featureValue,
@ -165,7 +171,8 @@ export default function EditProduct() {
isOffer: variant.isOffer || false,
isComboOnly: variant.isComboOnly || false,
isDeleted: variant.isDeleted || false,
isSuspended: variant.isSuspended || false,
// Region-owned suspension; the structural flag stays superadmin-owned.
isSuspendedInRegion: variant.isSuspendedInRegion || false,
features: variant.features.map((attr: any) => ({
featureName: attr.featureName,
featureValue: attr.featureValue,
@ -218,6 +225,39 @@ export default function EditProduct() {
);
}
// Global products: only the market data for this region is editable.
if (productData.isGlobal) {
const handleGlobalSubmit = async (skus: any[]) => {
try {
await updateProduct.mutateAsync({
id: productId,
name: productData.name,
shortDescription: productData.shortDescription || undefined,
longDescription: productData.longDescription || undefined,
storeId: productData.storeId || 0,
productType: productData.productType,
incrementStep: productData.incrementStep,
skus,
deletedImageKeys: [],
newImageUrls: [],
} as any)
await refetch()
await refetchProducts()
Alert.alert('Success', 'Market data updated for your region')
} catch (error: any) {
Alert.alert('Error', error.message || 'Failed to update product')
}
}
return (
<GlobalProductForm
product={productData as any}
onSubmit={handleGlobalSubmit}
isLoading={updateProduct.isPending}
/>
)
}
return (
<View style={tw`flex-1 bg-white`}>
<ProductForm

View file

@ -6,10 +6,10 @@ import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { MyText, tw, MyButton, useManualRefresh, SearchBar, useMarkDataFetchers, MyFlatList } from 'common-ui';
import { trpc } from '@/src/trpc-client';
import { SuccessToast, ErrorToast } from '@/services/toaster';
import VariantStockDialog from '@/src/components/VariantStockDialog';
import type { AdminSku } from '@packages/shared';
type FilterType = 'all' | 'in-stock' | 'out-of-stock';
type FilterType = 'all' | 'in-stock' | 'out-of-stock' | 'global';
type SerializedAdminSku = Omit<AdminSku, 'createdAt'> & { createdAt: string | Date }
@ -17,6 +17,24 @@ function getDefaultSku(product: { skus?: SerializedAdminSku[] }): SerializedAdmi
return product.skus?.[0] ?? null
}
type StockState = 'in' | 'partial' | 'out'
/** Stock is per variant, so the row, filters and counters must aggregate instead of reading skus[0]. */
function getStockState(product: { skus?: SerializedAdminSku[] }): StockState {
const skus = product.skus ?? []
if (skus.length === 0) return 'in'
const outCount = skus.filter((sku) => sku.isOutOfStock).length
if (outCount === 0) return 'in'
if (outCount === skus.length) return 'out'
return 'partial'
}
const STOCK_STYLES: Record<StockState, { dot: string; text: string; label: string; button: string }> = {
in: { dot: 'bg-green-500', text: 'text-green-500', label: 'In', button: 'bg-green-600' },
partial: { dot: 'bg-amber-500', text: 'text-amber-600', label: 'Partial', button: 'bg-amber-500' },
out: { dot: 'bg-red-500', text: 'text-red-500', label: 'Out', button: 'bg-red-500' },
}
function FilterButton({
filter,
label,
@ -45,16 +63,18 @@ function FilterButton({
type ProductRowProps = {
product: any
isToggling: boolean
onView: (productId: number) => void
onEdit: (productId: number) => void
onToggle: (product: { id: number }) => void
onManageStock: (product: any) => void
}
const ProductRow = React.memo(function ProductRow({ product, isToggling, onView, onEdit, onToggle }: ProductRowProps) {
const ProductRow = React.memo(function ProductRow({ product, onView, onEdit, onManageStock }: ProductRowProps) {
const defaultSku = getDefaultSku(product)
const skuImages = defaultSku?.images ?? null
const isOut = defaultSku?.isOutOfStock ?? false
const stockState = getStockState(product)
const stockStyle = STOCK_STYLES[stockState]
const skuCount = product.skus?.length ?? 0
const outCount = (product.skus ?? []).filter((sku: SerializedAdminSku) => sku.isOutOfStock).length
return (
<View style={tw`bg-white rounded-2xl shadow-lg mb-4 overflow-hidden`}>
@ -68,7 +88,7 @@ const ProductRow = React.memo(function ProductRow({ product, isToggling, onView,
recyclingKey={String(product.id)}
/>
) : (
<View style={tw`w-full h-48 bg-gray-200 justify-center items-center`}>
<View testID={`product-image-placeholder-${product.id}`} style={tw`w-full h-48 bg-gray-200 justify-center items-center`}>
<MaterialIcons name="image" size={48} color="#9CA3AF" />
</View>
)}
@ -79,10 +99,15 @@ const ProductRow = React.memo(function ProductRow({ product, isToggling, onView,
<MyText style={tw`text-lg font-bold text-gray-800 flex-1 mr-2`} numberOfLines={2}>
{product.name}
</MyText>
{product.isGlobal && (
<View style={tw`bg-purple-100 px-2 py-0.5 rounded-full mr-2`}>
<MyText style={tw`text-[10px] font-bold text-purple-700`}>GLOBAL</MyText>
</View>
)}
<View style={tw`flex-row items-center`}>
<View style={tw`w-3 h-3 rounded-full mr-1 ${isOut ? 'bg-red-500' : 'bg-green-500'}`} />
<MyText style={tw`text-sm ${isOut ? 'text-red-500' : 'text-green-500'} font-semibold`}>
{isOut ? 'Out' : 'In'}
<View style={tw`w-3 h-3 rounded-full mr-1 ${stockStyle.dot}`} />
<MyText style={tw`text-sm ${stockStyle.text} font-semibold`}>
{stockStyle.label}
</MyText>
</View>
</View>
@ -95,7 +120,7 @@ const ProductRow = React.memo(function ProductRow({ product, isToggling, onView,
<View style={tw`flex-row justify-between items-center mb-3`}>
<MyText style={tw`text-sm text-gray-500 font-medium`}>
{product.skus?.length ?? 0} Variants
{skuCount} Variants{outCount > 0 ? ` · ${outCount} out` : ''}
</MyText>
</View>
@ -118,14 +143,11 @@ const ProductRow = React.memo(function ProductRow({ product, isToggling, onView,
</TouchableOpacity>
<TouchableOpacity
onPress={() => onToggle(product)}
disabled={isToggling}
style={tw`flex-1 ${isOut ? 'bg-green-500' : 'bg-orange-500'} p-3 rounded-lg flex-row items-center justify-center ${isToggling ? 'opacity-50' : ''}`}
onPress={() => onManageStock(product)}
style={tw`flex-1 ${stockStyle.button} p-3 rounded-lg flex-row items-center justify-center`}
>
<MaterialIcons name={isOut ? 'check-circle' : 'block'} size={16} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>
{isOut ? 'Stock' : 'Out'}
</MyText>
<MaterialIcons name="tune" size={16} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>Stock</MyText>
</TouchableOpacity>
</View>
</View>
@ -140,15 +162,8 @@ export default function Products() {
const { data: productsData, isLoading, error, refetch } = trpc.admin.product.getProducts.useQuery();
const toggleOutOfStock = trpc.admin.product.toggleOutOfStock.useMutation({
onSuccess: async (res) => {
await refetch();
SuccessToast(res.message);
},
onError: (err) => {
ErrorToast(err.message || 'Failed to update stock status');
},
});
// Stock is chosen per variant in a dialog now (the single button used to flip everything).
const [stockDialogProduct, setStockDialogProduct] = useState<any | null>(null);
useManualRefresh(refetch);
@ -165,27 +180,27 @@ export default function Products() {
const filteredProducts = useMemo(() => {
const term = searchTerm.toLowerCase();
return products.filter(product => {
const defaultSku = getDefaultSku(product)
const matchesSearch = product.name.toLowerCase().includes(term) ||
(product.shortDescription?.toLowerCase().includes(term));
const matchesFilter = activeFilter === 'all' ||
(activeFilter === 'in-stock' && !defaultSku?.isOutOfStock) ||
(activeFilter === 'out-of-stock' && defaultSku?.isOutOfStock);
(activeFilter === 'in-stock' && getStockState(product) === 'in') ||
(activeFilter === 'out-of-stock' && getStockState(product) !== 'in') ||
(activeFilter === 'global' && product.isGlobal);
return matchesSearch && matchesFilter;
});
}, [products, searchTerm, activeFilter]);
const inStockCount = useMemo(
() => products.filter(p => { const sku = getDefaultSku(p); return sku && !sku.isOutOfStock }).length,
() => products.filter(p => getStockState(p) === 'in').length,
[products]
);
const outOfStockCount = useMemo(
() => products.filter(p => getDefaultSku(p)?.isOutOfStock).length,
() => products.filter(p => getStockState(p) !== 'in').length,
[products]
);
const globalCount = useMemo(() => products.filter(p => p.isGlobal).length, [products]);
const handleEdit = useCallback((productId: number) => {
router.push(`/(drawer)/dashboard/products/edit?id=${productId}` as any);
@ -195,9 +210,9 @@ export default function Products() {
router.push(`/(drawer)/dashboard/products/detail/${productId}` as any);
}, [router]);
const handleToggleStock = useCallback((product: { id: number }) => {
toggleOutOfStock.mutate({ id: product.id });
}, [toggleOutOfStock]);
const handleManageStock = useCallback((product: any) => {
setStockDialogProduct(product);
}, []);
const handleSelectFilter = useCallback((filter: FilterType) => setActiveFilter(filter), []);
@ -206,12 +221,11 @@ export default function Products() {
const renderItem = useCallback(({ item: product }: { item: any }) => (
<ProductRow
product={product}
isToggling={toggleOutOfStock.isPending && toggleOutOfStock.variables?.id === product.id}
onView={handleViewDetails}
onEdit={handleEdit}
onToggle={handleToggleStock}
onManageStock={handleManageStock}
/>
), [toggleOutOfStock.isPending, toggleOutOfStock.variables?.id, handleViewDetails, handleEdit, handleToggleStock]);
), [handleViewDetails, handleEdit, handleManageStock]);
const listHeader = useMemo(() => (
<>
@ -238,9 +252,10 @@ export default function Products() {
<FilterButton filter="all" label="All" count={products.length} activeFilter={activeFilter} onSelect={handleSelectFilter} />
<FilterButton filter="in-stock" label="In Stock" count={inStockCount} activeFilter={activeFilter} onSelect={handleSelectFilter} />
<FilterButton filter="out-of-stock" label="Out of Stock" count={outOfStockCount} activeFilter={activeFilter} onSelect={handleSelectFilter} />
<FilterButton filter="global" label="Global" count={globalCount} activeFilter={activeFilter} onSelect={handleSelectFilter} />
</View>
</>
), [products.length, inStockCount, outOfStockCount, searchTerm, activeFilter, handleSelectFilter, router]);
), [products.length, inStockCount, outOfStockCount, globalCount, searchTerm, activeFilter, handleSelectFilter, router]);
if (isLoading) {
return (
@ -301,6 +316,13 @@ export default function Products() {
windowSize={5}
removeClippedSubviews
/>
<VariantStockDialog
open={stockDialogProduct != null}
product={stockDialogProduct}
onClose={() => setStockDialogProduct(null)}
onApplied={refetch}
/>
</View>
);
}

View file

@ -30,6 +30,7 @@ const SlotItemComponent: React.FC<SlotItemProps> = ({
return (
<TouchableOpacity
testID={`rebalance-slot-${slot.id}`}
onPress={() => toggleSlotSelection(slot.id)}
activeOpacity={0.7}
style={tw`bg-white p-5 mb-4 rounded-3xl shadow-sm border border-gray-100`}
@ -196,6 +197,7 @@ export default function RebalanceOrders() {
{/* Floating Rebalance Button */}
<MyTouchableOpacity
testID="rebalance-button"
onPress={handleRebalance}
disabled={selectedSlots.length === 0}
activeOpacity={0.95}

View file

@ -122,6 +122,7 @@ export default function SendNotifications() {
{/* Header */}
<View style={tw`bg-white px-4 py-4 border-b border-gray-200 flex-row items-center`}>
<TouchableOpacity
testID="send-notifications-back"
onPress={() => router.back()}
style={tw`p-2 -ml-4`}
>
@ -159,6 +160,7 @@ export default function SendNotifications() {
<View style={tw`bg-white rounded-xl border border-gray-100 p-4 mb-4 shadow-sm`}>
<MyText style={tw`text-base font-bold text-gray-900 mb-3`}>Select Users (Optional)</MyText>
<BottomDropdown
testID="notification-user-dropdown"
label="Select Users"
value={selectedUserIds}
options={dropdownOptions}
@ -177,6 +179,7 @@ export default function SendNotifications() {
{/* Submit Button */}
<TouchableOpacity
testID="send-notification-button"
onPress={handleSend}
disabled={sendNotification.isPending || title.trim().length === 0 || message.trim().length === 0}
style={tw`${

View file

@ -72,6 +72,7 @@ const SlotItemComponent: React.FC<SlotItemProps> = ({
</View>
<View style={tw`flex-row items-center`}>
<TouchableOpacity
testID={`edit-slot-${slot.id}`}
onPress={() => router.push(`/(drawer)/dashboard/slots/edit/${slot.id}` as any)}
style={tw`px-3 py-1 rounded-full bg-pink2 mr-2`}
>
@ -89,6 +90,7 @@ const SlotItemComponent: React.FC<SlotItemProps> = ({
</View>
)}
<TouchableOpacity
testID={`slot-menu-${slot.id}`}
onPress={() => setMenuOpen(true)}
style={tw`ml-2 p-1`}
hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}

View file

@ -32,7 +32,7 @@ export default function AddStore() {
<MyText style={tw`text-2xl font-bold text-gray-800 mb-6`}>Add New Store</MyText>
<StoreForm
mode="create"
initialValues={{ name: '', description: '', owner: 0, products: [] }}
initialValues={{ name: '', description: '', products: [] }}
onSubmit={handleSubmit}
isLoading={createStoreMutation.isPending}
/>

View file

@ -58,10 +58,26 @@ export default function EditStore() {
name: storeData.store.name,
description: storeData.store.description || '',
imageUrl: storeData.store.imageUrl || '',
owner: storeData.store.owner.id,
products: [], // Will be set by StoreForm
};
// Global stores are managed by a superadmin and shared across every region.
if (storeData.store.isGlobal) {
return (
<AppContainer>
<View>
<MyText style={tw`text-2xl font-bold text-gray-800 mb-2`}>{storeData.store.name}</MyText>
<MyText style={tw`text-gray-500 mb-4`}>
Global store — managed by a superadmin and shared across all regions.
</MyText>
{storeData.store.description ? (
<MyText style={tw`text-gray-700`}>{storeData.store.description}</MyText>
) : null}
</View>
</AppContainer>
);
}
return (
<AppContainer>
<View>

View file

@ -30,8 +30,9 @@ const StoreItem: React.FC<StoreItemProps> = ({ item, index, isEditMode, onEdit,
>
<View style={tw`bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden flex-1 relative`}>
{/* Delete Button - Only visible in edit mode */}
{isEditMode && (
{isEditMode && !item.isGlobal && (
<TouchableOpacity
testID={`delete-store-${item.id}`}
onPress={() => onDelete(item.id)}
style={tw`absolute top-2 right-2 z-10 bg-red-500 p-2 rounded-full shadow-lg`}
>
@ -41,9 +42,9 @@ const StoreItem: React.FC<StoreItemProps> = ({ item, index, isEditMode, onEdit,
<TouchableOpacity
activeOpacity={0.9}
onPress={() => onEdit(item.id)}
onPress={isEditMode || item.isGlobal ? undefined : () => onEdit(item.id)}
style={tw`flex-1`}
disabled={isEditMode} // Disable navigation in edit mode
disabled={isEditMode || item.isGlobal}
>
{/* Image Section - Portrait oriented */}
<View style={tw`h-40 w-full bg-gray-50 relative`}>
@ -206,6 +207,7 @@ export default function Stores() {
{/* Floating Action Button for Adding New Store */}
<Animated.View entering={FadeInUp.delay(500)} style={tw`absolute bottom-8 right-6 shadow-xl`}>
<TouchableOpacity
testID="add-store-fab"
activeOpacity={0.8}
onPress={() => router.push('/(drawer)/dashboard/stores/add' as any)}
>

View file

@ -158,6 +158,7 @@ export default function UserDetails() {
{/* Header */}
<View style={tw`bg-white px-4 py-4 border-b border-gray-200 flex-row items-center`}>
<TouchableOpacity
testID="user-detail-back"
onPress={() => router.back()}
style={tw`p-2 -ml-4`}
>

View file

@ -59,11 +59,12 @@ export default function CancelOrderDialog({ orderId, open, onClose, onSuccess }:
Cancel Order
</MyText>
<MyText style={tw`text-gray-500 text-center mt-2 text-sm leading-5`}>
This will cancel the order and mark it as cancelled by admin. A refund record will be created.
This will cancel the order and mark it as cancelled by admin.
</MyText>
</View>
<MyTextInput
testID="cancel-order-reason"
topLabel="Cancellation Reason *"
value={cancelReason}
onChangeText={setCancelReason}
@ -74,12 +75,14 @@ export default function CancelOrderDialog({ orderId, open, onClose, onSuccess }:
<View style={tw`flex-row gap-3 mt-6`}>
<TouchableOpacity
testID="cancel-order-keep"
style={tw`flex-1 bg-gray-100 py-3.5 rounded-xl items-center`}
onPress={onClose}
>
<MyText style={tw`text-gray-700 font-bold`}>Keep Order</MyText>
</TouchableOpacity>
<TouchableOpacity
testID="cancel-order-confirm"
style={tw`flex-1 bg-red-500 py-3.5 rounded-xl items-center shadow-sm ${cancelOrderMutation.isPending ? 'opacity-50' : ''}`}
onPress={handleCancel}
disabled={cancelOrderMutation.isPending || !cancelReason.trim()}

View file

@ -54,7 +54,7 @@ export function OrderOptionsMenu({
onDial,
}: OrderOptionsMenuProps) {
const updateAddressCoordsMutation = trpc.admin.order.updateAddressCoords.useMutation();
const { data: constants } = trpc.admin.const.getConstants.useQuery();
const { data: constants } = trpc.admin.region.getRegionConstants.useQuery();
const welcomeMessage = constants?.find((c) => c.key === 'welcomeMessage')?.value;
const handleAttachLocation = async () => {
@ -145,6 +145,7 @@ export function OrderOptionsMenu({
</View>
<TouchableOpacity
testID="order-menu-view-details"
style={tw`flex-row items-center p-4 bg-white border border-gray-100 rounded-xl mb-3 shadow-sm`}
onPress={() => {
onViewDetails();
@ -167,6 +168,7 @@ export function OrderOptionsMenu({
<View style={tw`flex-row items-center p-4 bg-white border border-gray-100 rounded-xl mb-3 shadow-sm`}>
<View
testID="order-menu-packaged"
style={tw`p-1`}
hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }}
onStartShouldSetResponder={() => true}
@ -193,6 +195,7 @@ export function OrderOptionsMenu({
<View style={tw`flex-row items-center p-4 bg-white border border-gray-100 rounded-xl mb-3 shadow-sm`}>
<View
testID="order-menu-delivered"
style={tw`p-1`}
hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }}
onStartShouldSetResponder={() => true}
@ -218,6 +221,7 @@ export function OrderOptionsMenu({
</View>
<TouchableOpacity
testID="order-menu-admin-notes"
style={tw`flex-row items-center p-4 bg-white border border-gray-100 rounded-xl mb-3 shadow-sm`}
onPress={() => {
onOpenAdminNotes();
@ -240,6 +244,7 @@ export function OrderOptionsMenu({
{order.status !== 'cancelled' && (
<TouchableOpacity
testID="order-menu-cancel"
style={tw`flex-row items-center p-4 bg-white border border-gray-100 rounded-xl mb-3 shadow-sm`}
onPress={() => {
onCancelOrder();
@ -262,6 +267,7 @@ export function OrderOptionsMenu({
)}
<TouchableOpacity
testID="order-menu-attach-location"
style={tw`flex-row items-center p-4 bg-white border border-gray-100 rounded-xl mb-3 shadow-sm`}
onPress={() => {
handleAttachLocation();
@ -331,6 +337,7 @@ export function OrderOptionsMenu({
)}
<TouchableOpacity
testID="order-menu-whatsapp"
style={tw`flex-row items-center p-4 bg-white border border-gray-100 rounded-xl mb-3 shadow-sm`}
onPress={() => {
handleWhatsApp();
@ -352,6 +359,7 @@ export function OrderOptionsMenu({
</TouchableOpacity>
<TouchableOpacity
testID="order-menu-dial"
style={tw`flex-row items-center p-4 bg-white border border-gray-100 rounded-xl mb-3 shadow-sm`}
onPress={() => {
handleDial();

View file

@ -1,15 +1,43 @@
import React from 'react';
import React, { useState } from 'react';
import type { SlotSnippetInput } from '@packages/shared'
import { View, Text, TouchableOpacity, Alert } from 'react-native';
import { View, Text, TouchableOpacity, Alert, Keyboard } from 'react-native';
import { Formik, FieldArray } from 'formik';
import DateTimePickerMod from 'common-ui/src/components/date-time-picker';
import { tw, MyTextInput } from 'common-ui';
import { tw, MyTextInput, BottomDialog } from 'common-ui';
import { trpc } from '../src/trpc-client';
import ProductsSelector from '../components/ProductsSelector';
// Snippet form row — single source in @packages/shared (complete payload)
type VendorSnippet = SlotSnippetInput
// __DEV__ test hook: parse a YYYY-MM-DD + HH:MM wall-clock as IST (UTC+5:30).
// Returns null for bad shapes, out-of-range fields, or impossible dates.
const IST_OFFSET_MS = (5 * 60 + 30) * 60 * 1000
function parseIstDateTime(dateStr: string, timeStr: string): Date | null {
const dateMatch = /^(\d{4})-(\d{2})-(\d{2})$/.exec(dateStr.trim())
const timeMatch = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(timeStr.trim())
if (!dateMatch || !timeMatch) return null
const year = Number(dateMatch[1])
const month = Number(dateMatch[2])
const day = Number(dateMatch[3])
const hour = Number(timeMatch[1])
const minute = Number(timeMatch[2])
const utcMs = Date.UTC(year, month - 1, day, hour, minute) - IST_OFFSET_MS
// Round-trip through the offset: impossible dates (e.g. Feb 30) shift.
const check = new Date(utcMs + IST_OFFSET_MS)
if (
check.getUTCFullYear() !== year ||
check.getUTCMonth() !== month - 1 ||
check.getUTCDate() !== day ||
check.getUTCHours() !== hour ||
check.getUTCMinutes() !== minute
) {
return null
}
return new Date(utcMs)
}
interface SlotFormProps {
onSlotAdded?: () => void;
initialDeliveryTime?: Date | null;
@ -58,6 +86,24 @@ export default function SlotForm({
const { data: groupsData } = trpc.admin.product.getGroups.useQuery();
// __DEV__-only hidden datetime entry (avoids the native date/time scrollers
// in tests). Fields stay blank on every open — no prefill.
const [devDialogOpen, setDevDialogOpen] = useState(false)
const [devDeliveryDate, setDevDeliveryDate] = useState('')
const [devDeliveryTime, setDevDeliveryTime] = useState('')
const [devFreezeDate, setDevFreezeDate] = useState('')
const [devFreezeTime, setDevFreezeTime] = useState('')
const [devError, setDevError] = useState<string | null>(null)
const openDevDialog = () => {
setDevDeliveryDate('')
setDevDeliveryTime('')
setDevFreezeDate('')
setDevFreezeTime('')
setDevError(null)
setDevDialogOpen(true)
}
const handleFormSubmit = (values: typeof initialValues) => {
if (!values.deliveryTime || !values.freezeTime) {
Alert.alert('Error', 'Please fill all fields');
@ -231,6 +277,119 @@ export default function SlotForm({
{isPending ? (isEditMode ? 'Updating...' : 'Creating...') : (isEditMode ? 'Update Slot' : 'Create Slot')}
</Text>
</TouchableOpacity>
{__DEV__ && (
<TouchableOpacity
testID="test-set-current-datetime"
accessibilityRole="button"
accessibilityLabel="test-set-current-datetime"
accessible={true}
onPress={openDevDialog}
// 1x1 transparent pixel instead of left:-1000: iOS drops
// off-screen views from the accessibility tree, so Maestro could
// never find the button by testID. No opacity:0 — a 1x1 fully
// transparent pixel is invisible but stays in the tree.
style={{
position: 'absolute',
top: 0,
left: 0,
width: 1,
height: 1,
}}
/>
)}
{__DEV__ && (
<BottomDialog open={devDialogOpen} onClose={() => setDevDialogOpen(false)}>
<View style={tw`p-6`}>
<TouchableOpacity
testID="dev-datetime-header"
accessibilityRole="button"
activeOpacity={1}
onPress={() => Keyboard.dismiss()}
>
<Text style={tw`text-xl font-bold mb-1 text-center`}>Set Slot Datetimes</Text>
<Text style={tw`text-gray-500 text-center mb-4 text-sm`}>
Dates as YYYY-MM-DD, times as HH:MM (24h). Interpreted as IST.
</Text>
</TouchableOpacity>
<View style={tw`mb-4`}>
<MyTextInput
testID="dev-delivery-date"
topLabel="Delivery Date (YYYY-MM-DD)"
placeholder="YYYY-MM-DD"
value={devDeliveryDate}
onChangeText={setDevDeliveryDate}
/>
</View>
<View style={tw`mb-4`}>
<MyTextInput
testID="dev-delivery-time"
topLabel="Delivery Time (HH:MM)"
placeholder="HH:MM"
value={devDeliveryTime}
onChangeText={setDevDeliveryTime}
/>
</View>
<View style={tw`mb-4`}>
<MyTextInput
testID="dev-freeze-date"
topLabel="Freeze Date (YYYY-MM-DD)"
placeholder="YYYY-MM-DD"
value={devFreezeDate}
onChangeText={setDevFreezeDate}
/>
</View>
<View style={tw`mb-4`}>
<MyTextInput
testID="dev-freeze-time"
topLabel="Freeze Time (HH:MM)"
placeholder="HH:MM"
value={devFreezeTime}
onChangeText={setDevFreezeTime}
/>
</View>
{devError && (
<Text testID="dev-datetime-error" style={tw`text-red-500 mb-4 text-sm`}>
{devError}
</Text>
)}
<View style={tw`flex-row gap-3`}>
<TouchableOpacity
testID="dev-cancel-datetime"
style={tw`flex-1 bg-gray-100 py-3.5 rounded-xl items-center`}
onPress={() => setDevDialogOpen(false)}
>
<Text style={tw`text-gray-700 font-bold`}>Cancel</Text>
</TouchableOpacity>
<TouchableOpacity
testID="dev-apply-datetime"
style={tw`flex-1 bg-pink1 py-3.5 rounded-xl items-center`}
onPress={() => {
const delivery = parseIstDateTime(devDeliveryDate, devDeliveryTime)
const freeze = parseIstDateTime(devFreezeDate, devFreezeTime)
if (!delivery || !freeze) {
setDevError('Use YYYY-MM-DD and HH:MM (24h, IST) for both.')
return
}
if (freeze.getTime() > delivery.getTime()) {
setDevError('Freeze time must be before or equal to delivery time.')
return
}
setFieldValue('deliveryTime', delivery)
setFieldValue('freezeTime', freeze)
setDevDialogOpen(false)
}}
>
<Text style={tw`text-white font-bold`}>Apply</Text>
</TouchableOpacity>
</View>
</View>
</BottomDialog>
)}
</View>
)}}
</Formik>

View file

@ -2,7 +2,7 @@ import React, { useState, useEffect, useMemo } from 'react';
import { View, TouchableOpacity, Alert } from 'react-native';
import { Formik } from 'formik';
import * as Yup from 'yup';
import { MyTextInput, BottomDropdown, MyText, tw, ImageUploader } from 'common-ui';
import { MyTextInput, MyText, tw, ImageUploader } from 'common-ui';
import ProductsSelector from './ProductsSelector';
import { trpc } from '../src/trpc-client';
import usePickImage from 'common-ui/src/components/use-pick-image';
@ -27,12 +27,10 @@ const validationSchema = Yup.object().shape({
name: Yup.string().required('Name is required'),
description: Yup.string(),
imageUrl: Yup.string(),
owner: Yup.number().required('Owner is required'),
products: Yup.array().of(Yup.number()),
});
function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreFormProps) {
const { data: staffData } = trpc.admin.staffUser.getStaff.useQuery();
const { data: productsData } = trpc.admin.product.getProducts.useQuery();
const [formInitialValues, setFormInitialValues] = useState<StoreFormData>(initialValues);
@ -59,13 +57,6 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
[formInitialValues.imageUrl]
)
const staffOptions = staffData?.staff.map((staff: { id: number; name: string }) => ({
label: staff.name,
value: staff.id,
})) || [];
const { uploadSingle, isUploading } = useUploadToObjectStorage();
const handleImagePick = usePickImage({
@ -128,6 +119,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
return (
<View>
<MyTextInput
testID="store-name-input"
topLabel="Store Name"
placeholder="Enter store name"
value={values.name}
@ -136,6 +128,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
style={{ marginBottom: 16 }}
/>
<MyTextInput
testID="store-description-input"
topLabel="Description"
placeholder="Enter store description"
multiline
@ -145,16 +138,8 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
error={!!(touched.description && errors.description)}
style={{ marginBottom: 16 }}
/>
<BottomDropdown
label="Owner"
value={values.owner}
options={staffOptions}
onValueChange={(value) => setFieldValue('owner', value)}
placeholder="Select owner"
error={!!(touched.owner && errors.owner)}
style={{ marginBottom: 16 }}
/>
<ProductsSelector
testID="store-products-selector"
value={values.products || []}
onChange={(value) => setFieldValue('products', value)}
multiple={true}
@ -180,6 +165,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
/>
</View>
<TouchableOpacity
testID="store-submit-button"
onPress={submit}
disabled={isLoading || isUploading}
style={tw`px-4 py-2 rounded-lg shadow-lg items-center mt-2 ${isLoading || isUploading ? 'bg-gray-400' : 'bg-blue-500'}`}

View file

@ -5,6 +5,7 @@ import { MyText, tw, DatePicker, MyTextInput } from 'common-ui';
import BottomDropdown from 'common-ui/src/components/bottom-dropdown';
import ProductsSelector from '../components/ProductsSelector';
import { trpc } from '../src/trpc-client';
import { useStaffAuth } from '@/components/context/staff-auth-context';
import { VendorSnippetForm as VendorSnippetFormType, VendorSnippet } from '../types/vendor-snippets';
interface VendorSnippetFormProps {
@ -21,8 +22,12 @@ const VendorSnippetForm: React.FC<VendorSnippetFormProps> = ({
showIsPermanentCheckbox = false,
}) => {
// Fetch slots
const { data: slotsData } = trpc.user.slots.getSlots.useQuery();
// Fetch the staff user's region's slots (getSlots now requires a region).
const { regionId } = useStaffAuth();
const { data: slotsData } = trpc.user.slots.getSlots.useQuery(
{ regionId: regionId ?? 0 },
{ enabled: regionId != null }
);
const createSnippet = trpc.admin.vendorSnippets.create.useMutation();
const updateSnippet = trpc.admin.vendorSnippets.update.useMutation();
@ -128,6 +133,7 @@ const VendorSnippetForm: React.FC<VendorSnippetFormProps> = ({
{/* Snippet Code */}
<View>
<MyTextInput
testID="snippet-code-input"
topLabel="Snippet Code"
value={formik.values.snippetCode}
onChangeText={formik.handleChange('snippetCode')}
@ -180,6 +186,7 @@ const VendorSnippetForm: React.FC<VendorSnippetFormProps> = ({
{/* Product Selection */}
<View>
<ProductsSelector
testID="snippet-form-products-selector"
value={formik.values.skuIds.map(id => parseInt(id))}
onChange={(selectedProductIds) => formik.setFieldValue('skuIds', (selectedProductIds as number[]).map(id => id.toString()))}
multiple={true}
@ -211,6 +218,7 @@ const VendorSnippetForm: React.FC<VendorSnippetFormProps> = ({
{/* Submit Button */}
<View style={tw`px-6 py-4 border-t border-gray-200`}>
<TouchableOpacity
testID="snippet-submit-button"
onPress={() => formik.handleSubmit()}
disabled={formik.isSubmitting}
style={tw`bg-blue-500 py-3 rounded-lg ${formik.isSubmitting ? 'opacity-50' : ''}`}

View file

@ -4,15 +4,18 @@ import queryClient from "@/utils/queryClient";
import { DeviceEventEmitter } from "react-native";
import { FORCE_LOGOUT_EVENT } from "common-ui/src/lib/const-strs";
import { trpc } from "@/src/trpc-client";
import { saveJWT, getJWT, deleteJWT } from "@/hooks/useJWT";
import { saveJWT, getJWT, deleteJWT, saveStaff, getStaff, deleteStaff } from "@/hooks/useJWT";
import type { IdName } from '@packages/shared';
type Staff = IdName;
interface Staff extends IdName {
regionId?: number | null;
}
interface StaffAuthContextType {
isLoggedIn: boolean;
isLoading: boolean;
staff: Staff | null;
regionId: number | null;
login: (name: string, password: string) => Promise<void>;
logout: () => void;
isLoggingIn: boolean;
@ -35,9 +38,10 @@ export const StaffAuthProvider = ({ children }: { children: ReactNode }) => {
const checkAuth = async () => {
const token = await getJWT();
if (token) {
// TODO: Optionally decode token to get staff info
// Restore the staff identity saved at login so screens (e.g. the drawer
// header) still know who is signed in after a reload.
setStaff(await getStaff());
setIsLoggedIn(true);
// For now, assume staff info is not needed beyond login state
} else {
setIsLoggedIn(false);
if (!pathname.includes("login")) {
@ -57,6 +61,7 @@ export const StaffAuthProvider = ({ children }: { children: ReactNode }) => {
{
onSuccess: async (data) => {
await saveJWT(data.token);
await saveStaff(data.staff);
setStaff(data.staff);
setIsLoggedIn(true);
router.replace("/(drawer)/dashboard");
@ -70,6 +75,7 @@ export const StaffAuthProvider = ({ children }: { children: ReactNode }) => {
const logout = async () => {
await deleteJWT();
await deleteStaff();
setIsLoggedIn(false);
setStaff(null);
queryClient.clear();
@ -94,6 +100,7 @@ export const StaffAuthProvider = ({ children }: { children: ReactNode }) => {
isLoggedIn,
isLoading,
staff,
regionId: staff?.regionId ?? null,
login,
logout,
isLoggingIn: loginMutation.isPending,

View file

@ -1,6 +1,18 @@
import { StorageService } from 'common-ui'
export const JWT_KEY = 'jwt_token'
export const STAFF_KEY = 'staff_session'
/**
* The staff identity returned by `admin.staffUser.login`, persisted so the drawer
* can still show who is signed in after an app reload (the JWT itself only
* carries the staff name, and the region name is fetched from the API).
*/
export interface StoredStaff {
id: number
name: string
regionId?: number | null
}
export async function saveJWT(token: string) {
await StorageService.setItem(JWT_KEY, token)
@ -13,3 +25,21 @@ export async function getJWT() {
export async function deleteJWT() {
await StorageService.removeItem(JWT_KEY)
}
export async function saveStaff(staff: StoredStaff) {
await StorageService.setItem(STAFF_KEY, JSON.stringify(staff))
}
export async function getStaff(): Promise<StoredStaff | null> {
const raw = await StorageService.getItem(STAFF_KEY)
if (!raw) return null
try {
return JSON.parse(raw) as StoredStaff
} catch {
return null
}
}
export async function deleteStaff() {
await StorageService.removeItem(STAFF_KEY)
}

View file

@ -4,6 +4,7 @@ import { Formik } from 'formik';
import * as Yup from 'yup';
import { MyTextInput, MyButton, tw, AppContainer , DateTimePickerMod, Checkbox, BottomDialog, MyText } from 'common-ui';
import { trpc } from '../trpc-client';
import ProductsSelector from '@/components/ProductsSelector';
import { CreateCouponPayload } from 'common-ui/shared-types';
@ -46,6 +47,7 @@ const couponValidationSchema = Yup.object().shape({
isUserBased: Yup.boolean(),
isApplyForAll: Yup.boolean(),
applicableUsers: Yup.array().of(Yup.number()).optional(),
skuIds: Yup.array().of(Yup.number()).optional(),
}).test('discount-validation', 'Must provide exactly one discount type with valid value', function(value) {
const { discountPercent, flatDiscount } = value;
const hasPercent = discountPercent !== undefined && discountPercent > 0;
@ -130,9 +132,8 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
maxValue: undefined,
validTill: undefined,
maxLimitForUser: undefined,
skuIds: undefined,
skuIds: [],
applicableUsers: [],
applicableProducts: [],
exclusiveApply: false,
isFirstOrderOnly: false,
isReservedCoupon: false,
@ -483,6 +484,29 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
</View>
</BottomDialog>
{/* Applicable Products — the coupon's target SKUs. Empty means the
whole cart; shown for reserved coupons too (the secret code's
targets are copied onto the coupon the customer redeems). */}
<View style={tw`mb-4`}>
<Text style={tw`text-base font-bold mb-2`}>Applicable Products (Optional)</Text>
<ProductsSelector
testID="coupon-products-selector"
label="Select Products"
placeholder="All products (whole cart)"
multiple
showGroups={false}
value={values.skuIds ?? []}
onChange={(selected) =>
setFieldValue('skuIds', Array.isArray(selected) ? selected : [])
}
/>
<Text style={tw`text-xs text-gray-500 mt-2`}>
{values.skuIds && values.skuIds.length > 0
? `${values.skuIds.length} product(s) selected - the coupon discounts only these items.`
: 'No products selected - the coupon applies to the whole cart.'}
</Text>
</View>
{/* Add Multiple Coupons Dialog */}
<BottomDialog open={multiDialogOpen} onClose={() => setMultiDialogOpen(false)}>
<View style={tw`p-4`}>

View file

@ -0,0 +1,195 @@
import React, { useMemo, useState } from 'react'
import { View, ScrollView } from 'react-native'
import { Image } from 'expo-image'
import { MyText, MyTextInput, MyButton, Checkbox, tw } from 'common-ui'
import type { AdminProductWithRelations } from '@packages/shared'
/**
* Global products are owned by a superadmin and shared across every region. A
* regional admin may only edit the market data for their own region — the
* product structure (name, descriptions, images, features, combos, store) is
* read-only here.
*/
interface GlobalProductFormProps {
product: AdminProductWithRelations
onSubmit: (skus: any[]) => void
isLoading: boolean
}
interface VariantState {
price: string
marketPrice: string
flashPrice: string
isFlashAvailable: boolean
isOutOfStock: boolean
isOffer: boolean
/** This region's suspension — separate from the superadmin's global kill-switch. */
isSuspendedInRegion: boolean
}
const toNumOrUndef = (v: string): number | undefined => {
const n = parseFloat(v)
return Number.isFinite(n) ? n : undefined
}
function GlobalProductForm({ product, onSubmit, isLoading }: GlobalProductFormProps) {
const skus = product.skus || []
const [variants, setVariants] = useState<VariantState[]>(
useMemo(
() =>
skus.map((sku) => ({
price: sku.price != null ? String(sku.price) : '',
marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : '',
flashPrice: sku.flashPrice != null ? String(sku.flashPrice) : '',
isFlashAvailable: sku.isFlashAvailable ?? false,
isOutOfStock: sku.isOutOfStock ?? false,
isOffer: sku.isOffer ?? false,
isSuspendedInRegion: sku.isSuspendedInRegion ?? false,
})),
[product]
)
)
const setVariant = (index: number, patch: Partial<VariantState>) =>
setVariants((prev) => prev.map((v, i) => (i === index ? { ...v, ...patch } : v)))
const handleSubmit = () => {
const payload = skus.map((sku, i) => {
const v = variants[i]
return {
id: sku.id,
name: sku.name ?? null,
price: toNumOrUndef(v.price) ?? 0,
marketPrice: toNumOrUndef(v.marketPrice) ?? null,
images: sku.images ?? [],
isFlashAvailable: v.isFlashAvailable,
flashPrice: v.isFlashAvailable ? (toNumOrUndef(v.flashPrice) ?? null) : null,
isOutOfStock: v.isOutOfStock,
isOffer: v.isOffer,
isComboOnly: sku.isComboOnly ?? false,
isDeleted: sku.isDeleted ?? false,
// The global kill-switch is read-only for a region; the checkbox only
// owns this region's suspension flag.
isSuspended: sku.isSuspended ?? false,
isSuspendedInRegion: v.isSuspendedInRegion,
features: (sku.features || []).map((f) => ({
featureName: f.featureName,
featureValue: f.featureValue,
})),
comboItems: (sku.comboItems || []).map((ci: any) => ({ skuId: ci.skuId })),
}
})
onSubmit(payload)
}
return (
<ScrollView style={tw`flex-1 bg-gray-50`} contentContainerStyle={tw`p-4 pb-16`}>
<View style={tw`bg-blue-50 border border-blue-100 rounded-2xl p-4 mb-4`}>
<MyText style={tw`text-blue-800 font-bold mb-1`}>Global product</MyText>
<MyText style={tw`text-blue-700 text-sm`}>
Shared across all regions. You can edit the price &amp; stock for your region only.
</MyText>
</View>
{/* Read-only structure */}
<View style={tw`bg-white rounded-2xl p-4 mb-4 border border-gray-100`}>
<MyText style={tw`text-xs uppercase tracking-wider text-gray-400 mb-2`}>Product details (read-only)</MyText>
<MyText style={tw`text-lg font-bold text-gray-900`}>{product.name}</MyText>
{product.shortDescription ? (
<MyText style={tw`text-sm text-gray-500 mt-1`}>{product.shortDescription}</MyText>
) : null}
<MyText style={tw`text-sm text-gray-500 mt-2`}>
Store: {product.store?.name ?? '—'} · Type: {product.productType}
</MyText>
</View>
{skus.map((sku, index) => {
const v = variants[index]
return (
<View key={sku.id} style={tw`bg-white rounded-2xl p-4 mb-4 border border-gray-100`}>
<View style={tw`flex-row items-center mb-3`}>
{sku.images && sku.images[0] ? (
<Image source={{ uri: sku.images[0] }} style={tw`w-12 h-12 rounded-lg mr-3`} contentFit="cover" />
) : null}
<View style={tw`flex-1`}>
<MyText style={tw`font-bold text-gray-900`}>{sku.name || product.name}</MyText>
<MyText style={tw`text-xs text-gray-400`}>
{(sku.features || []).map((f) => f.featureValue).join(' · ') || '—'}
</MyText>
</View>
</View>
<MyText style={tw`text-xs uppercase tracking-wider text-gray-400 mb-2`}>Market data (your region)</MyText>
<MyTextInput
testID={`global-sku-${sku.id}-price`}
topLabel="Price (₹)"
keyboardType="numeric"
value={v.price}
onChangeText={(t) => setVariant(index, { price: t })}
style={{ marginBottom: 12 }}
/>
<MyTextInput
testID={`global-sku-${sku.id}-market-price`}
topLabel="Market price (₹)"
keyboardType="numeric"
value={v.marketPrice}
onChangeText={(t) => setVariant(index, { marketPrice: t })}
style={{ marginBottom: 12 }}
/>
<View style={tw`flex-row items-center mb-3`}>
<Checkbox
testID={`global-sku-${sku.id}-flash`}
checked={v.isFlashAvailable}
onPress={() => setVariant(index, { isFlashAvailable: !v.isFlashAvailable })}
style={tw`mr-3`}
/>
<MyText style={tw`text-gray-700 font-medium`}>Flash available</MyText>
</View>
{v.isFlashAvailable && (
<MyTextInput
testID={`global-sku-${sku.id}-flash-price`}
topLabel="Flash price (₹)"
keyboardType="numeric"
value={v.flashPrice}
onChangeText={(t) => setVariant(index, { flashPrice: t })}
style={{ marginBottom: 12 }}
/>
)}
<View style={tw`flex-row items-center mb-3`}>
<Checkbox
testID={`global-sku-${sku.id}-stock`}
checked={v.isOutOfStock}
onPress={() => setVariant(index, { isOutOfStock: !v.isOutOfStock })}
style={tw`mr-3`}
/>
<MyText style={tw`text-gray-700 font-medium`}>Out of stock</MyText>
</View>
<View style={tw`flex-row items-center mb-3`}>
<Checkbox
testID={`global-sku-${sku.id}-offer`}
checked={v.isOffer}
onPress={() => setVariant(index, { isOffer: !v.isOffer })}
style={tw`mr-3`}
/>
<MyText style={tw`text-gray-700 font-medium`}>Offer SKU</MyText>
</View>
<View style={tw`flex-row items-center mb-1`}>
<Checkbox
testID={`global-sku-${sku.id}-suspend`}
checked={v.isSuspendedInRegion}
onPress={() => setVariant(index, { isSuspendedInRegion: !v.isSuspendedInRegion })}
style={tw`mr-3`}
/>
<MyText style={tw`text-gray-700 font-medium`}>Suspend in my region</MyText>
</View>
</View>
)
})}
<MyButton testID="global-save-button" onPress={handleSubmit} loading={isLoading} textContent="Save market data" />
</ScrollView>
)
}
export default GlobalProductForm

View file

@ -25,7 +25,7 @@ type Variant = Omit<
isFlashAvailable: boolean
isOffer: boolean
isComboOnly: boolean
isSuspended: boolean
isSuspendedInRegion: boolean
features: Attribute[]
comboItems: CreateComboItemInput[]
}
@ -70,14 +70,14 @@ const defaultVariant = (): Variant => ({
isOffer: false,
isComboOnly: false,
isDeleted: false,
isSuspended: false,
isSuspendedInRegion: false,
features: [quantityAttribute()],
comboItems: [],
})
const variantSignature = (attributes: Attribute[]): string =>
attributes
.map((a) => `${(a.featureName ?? '').trim().toLowerCase()}::${a.featureValue.trim().toLowerCase()}`)
.map((a) => `${(a.featureName ?? '').trim().toLowerCase()}::${(a.featureValue ?? '').trim().toLowerCase()}`)
.sort()
.join('|')
@ -177,11 +177,21 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
}), [initialValues.variants])
const { data: storesData } = trpc.common.getStoresSummary.useQuery()
// Global stores are usable from every region, so they are selectable too;
// label them so the choice is explicit (the product still stays in this
// admin's region).
const storeOptions = storesData?.stores.map((store) => ({
label: store.name,
label: store.isGlobal ? `${store.name} (global)` : store.name,
value: store.id,
})) || []
// Fallback for a create form that seeds no store: prefer a regional store,
// else the first option (e.g. a global store) once the list loads.
const defaultStoreId = useMemo(() => {
const stores = storesData?.stores ?? []
return stores.find((store) => !store.isGlobal)?.id ?? stores[0]?.id ?? 0
}, [storesData])
const { data: skusData } = trpc.common.product.getAllSkusSummary.useQuery()
const skuOptions = (skusData?.skus || []).map((sku) => ({
label: sku.label,
@ -193,6 +203,9 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
const formInitialValues = useMemo(() => {
return {
...initialValues,
// An empty seed (create form) adopts the first available store once the
// list has loaded; an existing product keeps its own store.
storeId: initialValues.storeId || defaultStoreId,
variants: (initialValues.variants || []).map((v) => {
const hasQuantity = (v.features || []).some(
(a) => (a.featureName ?? '').trim().toLowerCase() === 'quantity'
@ -201,7 +214,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
return { ...v, features: [quantityAttribute(), ...(v.features || [])] }
}),
}
}, [initialValues])
}, [initialValues, defaultStoreId])
return (
<Formik
@ -376,6 +389,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<View style={tw`flex-row justify-between items-center mb-2`}>
<MyText style={tw`font-medium text-gray-600`}>Attributes</MyText>
<TouchableOpacity
testID={`variant-${vIndex}-add-attr`}
onPress={() => pushAttr(defaultAttribute())}
style={tw`bg-gray-200 px-2 py-0.5 rounded flex-row items-center`}
>
@ -415,7 +429,10 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
/>
</View>
{canDelete && (
<TouchableOpacity onPress={() => removeAttr(aIndex)}>
<TouchableOpacity
testID={`variant-${vIndex}-attr-${aIndex}-remove`}
onPress={() => removeAttr(aIndex)}
>
<MaterialIcons name="close" size={18} color="#EF4444" />
</TouchableOpacity>
)}
@ -424,6 +441,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
})}
<View style={tw`flex-row items-center self-start`}>
<TouchableOpacity
testID={`variant-${vIndex}-add-attr-footer`}
onPress={() => pushAttr(defaultAttribute())}
style={tw`bg-gray-200 px-2 py-0.5 rounded flex-row items-center`}
>
@ -501,11 +519,11 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<View style={tw`flex-row items-center mb-3`}>
<Checkbox
testID={`variant-${vIndex}-suspend`}
checked={variant.isSuspended}
onPress={() => setFieldValue(`variants.${vIndex}.isSuspended`, !variant.isSuspended)}
checked={variant.isSuspendedInRegion}
onPress={() => setFieldValue(`variants.${vIndex}.isSuspendedInRegion`, !variant.isSuspendedInRegion)}
style={tw`mr-3`}
/>
<MyText style={tw`text-gray-700 font-medium`}>Suspend SKU</MyText>
<MyText style={tw`text-gray-700 font-medium`}>Suspend in my region</MyText>
</View>
)}
@ -546,6 +564,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<View style={tw`flex-row justify-between items-center mb-2`}>
<MyText style={tw`font-medium text-gray-600`}>Included Items</MyText>
<TouchableOpacity
testID={`variant-${vIndex}-combo-add`}
onPress={() => {
const items = variant.comboItems || []
items.push({ skuId: 0 })
@ -561,6 +580,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<View key={cIndex} style={tw`flex-row items-center gap-2 mb-2`}>
<View style={tw`flex-1`}>
<BottomDropdown
testID={`variant-${vIndex}-combo-${cIndex}-dropdown`}
label="SKU"
value={ci.skuId}
options={skuOptions.map((opt: { label: string; value: number }) => ({
@ -585,6 +605,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
/>
</View>
<TouchableOpacity
testID={`variant-${vIndex}-combo-${cIndex}-remove`}
onPress={() => {
const items = variant.comboItems.filter((_, i) => i !== cIndex)
setFieldValue(`variants.${vIndex}.comboItems`, items)

View file

@ -0,0 +1,159 @@
import React, { useEffect, useMemo, useState } from 'react'
import { View } from 'react-native'
import { BottomDialog, Checkbox, MyButton, MyText, tw } from 'common-ui'
import { trpc } from '@/src/trpc-client'
import { ErrorToast, SuccessToast } from '@/services/toaster'
type DialogSku = {
id: number
name?: string | null
features?: Array<{ featureName?: string | null; featureValue?: string | null }>
isOutOfStock?: boolean
}
type DialogProduct = {
id: number
name: string
skus?: DialogSku[]
}
/** "500 g" / "500 g, boneless" / the SKU name / a fallback — whatever identifies the variant. */
function variantLabel(sku: DialogSku): string {
const featureValues = (sku.features ?? [])
.map((feature) => feature.featureValue)
.filter((value): value is string => !!value)
if (featureValues.length > 0) return featureValues.join(', ')
if (sku.name) return sku.name
return `Variant #${sku.id}`
}
interface VariantStockDialogProps {
open: boolean
product: DialogProduct | null
onClose: () => void
/** Called after a successful change so the caller can refetch the product list. */
onApplied?: () => void
}
/**
* Per-variant stock control.
*
* The list's single button used to flip every variant at once, which cannot express
* "one variant is out" (PD-06) and silently collapsed a partial state. This dialog
* lets the admin pick which variants to change and in which direction.
*/
const VariantStockDialog: React.FC<VariantStockDialogProps> = ({ open, product, onClose, onApplied }) => {
const skus = useMemo(() => product?.skus ?? [], [product])
const [selected, setSelected] = useState<number[]>([])
// Every time the dialog opens (or targets another product) start from "all variants".
useEffect(() => {
if (open) setSelected(skus.map((sku) => sku.id))
}, [open, product?.id, skus.length])
const toggleSku = (skuId: number) => {
setSelected((current) =>
current.includes(skuId) ? current.filter((id) => id !== skuId) : [...current, skuId]
)
}
const updateStock = trpc.admin.product.toggleOutOfStock.useMutation({
onSuccess: (res) => {
SuccessToast(res.message)
onApplied?.()
onClose()
},
onError: (err) => {
ErrorToast(err.message || 'Failed to update stock status')
},
})
const apply = (isOutOfStock: boolean) => {
if (!product || selected.length === 0) return
updateStock.mutate({ id: product.id, skuIds: selected, isOutOfStock })
}
const outCount = skus.filter((sku) => sku.isOutOfStock).length
const isPartial = outCount > 0 && outCount < skus.length
const allSelected = skus.length > 0 && selected.length === skus.length
return (
<BottomDialog open={open} onClose={onClose}>
<View style={tw`p-5`}>
<MyText style={tw`text-lg font-bold text-gray-900`}>Stock</MyText>
<MyText style={tw`text-gray-500 text-sm mt-1 mb-4`} numberOfLines={2}>
{product?.name ?? ''}
</MyText>
{isPartial && (
<View style={tw`bg-amber-50 border border-amber-200 rounded-lg px-3 py-2 mb-3`}>
<MyText style={tw`text-amber-700 text-xs`}>
{outCount} of {skus.length} variants are out of stock
</MyText>
</View>
)}
<View style={tw`flex-row justify-between items-center mb-2`}>
<MyText style={tw`text-gray-600 text-xs font-semibold uppercase`}>
Variants ({selected.length}/{skus.length})
</MyText>
<MyText
onPress={() => setSelected(allSelected ? [] : skus.map((sku) => sku.id))}
style={tw`text-blue-600 text-xs font-bold`}
>
{allSelected ? 'Clear all' : 'Select all'}
</MyText>
</View>
{skus.map((sku) => (
<View key={sku.id} style={tw`flex-row items-center py-2 border-b border-gray-100`}>
<Checkbox
testID={`variant-stock-${sku.id}`}
checked={selected.includes(sku.id)}
onPress={() => toggleSku(sku.id)}
style={tw`mr-3`}
/>
<MyText style={tw`flex-1 text-gray-800`} numberOfLines={1}>
{variantLabel(sku)}
</MyText>
<View style={tw`flex-row items-center`}>
<View style={tw`w-2 h-2 rounded-full mr-1 ${sku.isOutOfStock ? 'bg-red-500' : 'bg-green-500'}`} />
<MyText style={tw`text-xs ${sku.isOutOfStock ? 'text-red-500' : 'text-green-600'}`}>
{sku.isOutOfStock ? 'Out' : 'In'}
</MyText>
</View>
</View>
))}
<View style={tw`flex-row gap-2 mt-5`}>
<MyButton
onPress={() => apply(true)}
loading={updateStock.isPending}
disabled={selected.length === 0 || updateStock.isPending}
variant="red"
textContent="Mark out of stock"
style={tw`flex-1`}
/>
<MyButton
onPress={() => apply(false)}
loading={updateStock.isPending}
disabled={selected.length === 0 || updateStock.isPending}
variant="green"
textContent="Mark in stock"
style={tw`flex-1`}
/>
</View>
<MyButton
onPress={onClose}
disabled={updateStock.isPending}
fillColor="gray1"
textContent="Cancel"
style={tw`mt-2`}
/>
</View>
</BottomDialog>
)
}
export default VariantStockDialog

View file

@ -1,242 +0,0 @@
# Known bugs — apps/admin-ui
Found while writing the integration test suite (`tests/`). Each entry names the
file and line, what the code does, what was expected, and the evidence. Severity
is my judgement of user impact.
---
## High — user-facing breakage
### 1. Add Product / Add Variant crashes (Formik empty-string normalisation)
`src/components/ProductForm.tsx:80`
```ts
const variantSignature = (attributes: Attribute[]): string =>
attributes
.map((a) => `${(a.featureName ?? '').trim().toLowerCase()}::${a.featureValue.trim().toLowerCase()}`)
```
`featureName` is guarded, `featureValue` is not. Formik's `validateYupSchema`
normalises empty strings to `undefined` before running Yup, so the `variants`
`unique-variants` `.test()` receives attributes whose `featureValue` is
`undefined` (`defaultAttribute`/`quantityAttribute` both start as `''`) and
`a.featureValue.trim()` throws `TypeError`.
**Impact:** every keystroke on the Add Product form (validation runs on change)
and the "Add Variant" / "Add Feature" buttons throw. Creating a product is
unusable. Editing only works when the fetched SKUs already have non-empty
feature values.
**Expected:** `(a.featureValue ?? '').trim()`.
**Pinned by:** `tests/components/product-form.test.tsx`,
`tests/screens/products-add.test.tsx`.
### 2. Coupon code list crashes on validation
`src/components/CouponForm.tsx:68`
```ts
const codes = (value.couponCodes || []).map((c: string) => c.trim()).filter(Boolean);
```
The sibling `codes-required` test on line 61 guards with `c && c.trim()`; this
one does not. Formik normalises the default `couponCodes: ['']` to `[undefined]`,
so `c.trim()` throws.
**Impact:** toggling "Is Reserved Coupon", switching discount type, "+ Add Code",
or selecting a user (`setFieldValue`) crashes the coupon form.
**Expected:** `(c || '').trim()` or filter first.
**Pinned by:** `tests/components/coupon-form.test.tsx`.
### 3. Prices Overview saves the SKU id as the product id
`app/(drawer)/dashboard/prices-overview/index.tsx:270` (and `:276`)
```ts
const update: any = { productId: sku?.id };
```
`pendingChanges` is keyed by SKU id and `sku` is resolved from `allSkus`, so the
payload carries a **SKU** id. The backend `admin.product.updateProductPrices`
resolves `productId` against `productInfo.id` (`apps/backend/.../product.ts:436`
→ `packages/db_helper_*/src/admin-apis/product.ts`), so it throws
`Invalid product IDs: ...` for every row.
**Expected:** send the SKU's parent product id (`sku.productId`).
**Pinned by:** `tests/screens/prices-overview.test.tsx`.
### 4. Product Groupings save SKU ids as product ids
`components/ProductGroupForm.tsx:44,119` + `components/ProductsSelector.tsx:117`
`ProductsSelector` emits `value: sku.id` (a SKU id) and the form forwards it as
`product_ids`. `createProductGroup` / `updateProductGroup` insert those into
`product_group_membership.productId`, which FKs `productInfo.id`. Create and
edit are also inconsistent: edit seeds `group.products.map(p => p.id)` (product
ids).
**Expected:** emit/insert product ids.
**Pinned by:** `tests/components/product-group-form.test.tsx`.
### 5. "Popular Items" add silently drops the selected product
`app/(drawer)/dashboard/customize-app/popular-items.tsx:184`
```ts
const newProducts = selectedProductIds
.map(id => allProducts?.products.find(p => p.id === id))
```
`selectedProductIds` are SKU ids (from `ProductsSelector`), matched against
product ids, so the lookup misses and the dialog closes with nothing added.
The label formatter also runs `labelFormat({ productName, price })` on a
`SkuSummary` that has no `price`, rendering `₹undefined`.
**Expected:** match on `sku.productId`.
**Pinned by:** `tests/screens/customize-app-popular-items.test.tsx`.
### 6. StoreForm bypasses Formik validation
`components/StoreForm.tsx:111,183`
The submit button calls a local `submit()` that invokes the `onSubmit` prop
directly; Formik's `handleSubmit` is destructured (`:110`) but never called, so
`validationSchema` never runs. Combined with `owner` initialised to `0`
(`stores/add.tsx:35`) and `Yup.number().required()` accepting `0`, an ownerless
store is submitted and rejected by the backend instead of inline.
**Expected:** `onPress={handleSubmit}`.
**Pinned by:** `tests/components/store-form.test.tsx`,
`tests/screens/stores-add.test.tsx`.
---
## Medium
### 7. Dashboard Banners fires duplicate `updateBanner` calls on save
`app/(drawer)/dashboard/dashboard-banners/index.tsx:75-116`
`handleSave` collects `bannersToUpdate` in a per-banner loop and again in a
per-slot loop. A banner whose slot changed is pushed by both, so the same
`updateBanner({ id, serialNum })` fires twice; moving a banner between slots can
emit contradictory updates.
**Expected:** de-duplicate by banner id.
**Pinned by:** `tests/screens/banners-index.test.tsx`.
### 8. Banner edit screen shows "Banner not found" on mount
`app/(drawer)/dashboard/dashboard-banners/edit/[id].tsx:42-73`
`useEffect(..., [bannerId, bannerData])` calls `loadBanner` on the first render,
when `bannerData` is still `undefined`, taking the `else` branch:
`Alert.alert('Error', 'Banner not found')` + `router.back()` — before the query
resolves. The form then renders anyway.
**Expected:** wait for the query to settle before treating "no data" as missing.
**Pinned by:** `tests/screens/banners-edit.test.tsx`.
### 9. Refund / cancellation-coupon actions are unreachable
`app/(drawer)/dashboard/manage-orders/order-details/[id].tsx:697-769`
The entire Refund Details block is commented out. It is the only caller of
`setInitiateRefundDialogOpen(true)` and `setGenerateCouponDialogOpen(true)`, so
`admin.payments.initiateRefund` and `admin.coupon.generateCancellationCoupon`
can never fire from the UI. The `initiateRefund` success alert (lines 66-69)
also drops the amount from its template string.
**Expected:** re-enable the block when the feature ships.
**Pinned by:** `tests/screens/order-details.test.tsx` (documents the gap).
### 10. Complaints resolve can send an empty response the backend rejects
`app/(drawer)/dashboard/complaints/index.tsx:66`
```ts
resolveComplaint.mutate({ id: String(selectedComplaintId), response: response ?? '' }, ...)
```
The backend input requires `response: z.string().min(1)`. Confirming Resolve with
no comment sends `''` and gets a server error (surfaced as a generic alert)
instead of being blocked client-side.
**Expected:** require a response, or make it optional server-side.
**Pinned by:** `tests/screens/complaints-index.test.tsx`.
---
## Low
### 11. Inline "Packaged" toggle in the orders list is inert
`app/(drawer)/dashboard/manage-orders/orders/index.tsx:218`
`onPress={() => {}}`. Packaged changes only work through `OrderOptionsMenu`.
### 12. CancelOrderDialog has an unreachable validation branch
`components/CancelOrderDialog.tsx:18-21` alerts on an empty reason, but the
confirm button is disabled while the reason is empty (`:85`), so the branch
never runs.
### 13. Send Notifications shows the error alert twice
`app/(drawer)/dashboard/send-notifications/index.tsx:48-50,87-96` — the mutation
has an `onError` alert and the caller also try/catches and alerts.
### 14. Product Groupings "N Products" does nothing
`app/(drawer)/dashboard/product-groupings/index.tsx:11,130` — `BottomDialog` is
imported and `viewProducts` is set by `onViewProducts`, but no dialog renders.
### 15. `NotificationToast` calls a hook outside a component
`services/toaster.tsx:39-40` — `NotificationToast` calls `useRouter()` though it
is exported as an event helper, not rendered as a component (Rules of Hooks).
### 16. Upload key parsing assumes path-style S3 URLs
`hooks/useUploadToObjectStore.ts:99-104` — `extractKeyFromPresignedUrl` strips the
first path segment (`slice(1)`). Correct for the backend's current
`<endpoint>/<bucket>/<key>` URLs, but breaks for virtual-host-style
(`<bucket>.<host>/<key>`). The backend's own `s3-client.ts` uses `slice(-2)`.
---
## Test-harness limitations (not app bugs)
- **`expo-image-picker` / `expo-document-picker` mocks do not reach `packages/ui`.**
`packages/ui` resolves its own copy of those modules, so `common-ui`'s
`usePickImage`/`ImageUploader` call the real (native) picker and cannot be
driven from a test. Image-upload flows are therefore exercised by mocking the
upload hook or seeding state, and upload integration is not covered.
- **`@expo/vector-icons` has a duplicate copy under `packages/ui/node_modules`,**
so `UNSAFE_getAllByType(MaterialIcons)` from the app's copy does not find the
`common-ui` icons. Prefer text/testID-based queries.
- **`react-native-draggable-flatlist` mock** ignores `ListHeaderComponent` /
`ListFooterComponent` and never calls `onDragEnd`, so drag-reorder save flows
cannot be asserted through the mock.
## Already fixed during this work
- `stores/edit.tsx` now invalidates `admin.store.getStores` (only `getStoreById`
was refetched before).
- `coupons/create.tsx` + `coupons/edit/[id].tsx` invalidate
`admin.coupon.getAll` / `getReservedCoupons` instead of refetching with a
hardcoded `search: ''` that missed the list's key when a search was active.
- `tests/mocks/native.ts` `tabViewMock` `SceneMap` returned the raw map instead
of a `renderScene` function (corrected).

View file

@ -0,0 +1,196 @@
# admin-ui test suite
Runnable implementation of the cases catalogued in
[`../JEST-TEST-CASES.md`](../JEST-TEST-CASES.md).
```bash
cd apps/admin-ui
bun run test -- tests/pages/dashboard.test.tsx # a single file
bun run test # everything
bun run test:typecheck # tsc over the app + tests
```
Runner: `jest-expo` + `@testing-library/react-native`. Application code (pages,
hooks, components, auth context) runs for real; only the tRPC client and native
modules are mocked. React Query is real, but the tRPC mock replaces the hooks, so
queries resolve synchronously from the procedure registry.
---
## Layout
```
tests/
jest.config.js preset, aliases, native-module mocks
setup.ts globals (fetch, console, act env)
fixtures/index.ts backend-shaped fixtures
helpers/
test-utils.tsx render helpers + auth seeding
reset.ts resetAllMocks() for beforeEach
mocks/
trpc-client.ts procedure-registry mock (queries + mutations + utils)
trpc-defaults.ts default payload per procedure
staff-auth-context.tsx deterministic StaffAuthContext replacement
expo-router-mock.tsx recorded router + layout primitives
secure-store-mock.ts in-memory SecureStore
expo-notifications-mock.ts
native/* native-module shims
```
## Standard test shape
```tsx
import React from 'react'
import { fireEvent } from '@testing-library/react-native'
import Products from '@/app/(drawer)/dashboard/products/index'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { setProcedure, lastMutationInput } from '../mocks/trpc-client'
import { router } from '../mocks/expo-router-mock'
describe('Products', () => {
beforeEach(() => resetAllMocks())
it('APLIST-01: shows the loading copy', () => {
setProcedure('admin.product.getProducts', { mode: 'pending' })
const view = renderWithProviders(<Products />, { auth: 'in' })
expect(view.getByText('Loading products...')).toBeTruthy()
})
})
```
Rules:
1. One `it()` per catalogue row, prefixed with the row id (`APLIST-01: ...`).
2. `resetAllMocks()` in `beforeEach`.
3. Assert the procedure + exact input for every mutation
(`lastMutationInput('admin.product.createProduct')`).
4. Prefer `getByTestId` / `queryByTestId` over text matching, but text matching
is fine for the catalogue's visible-copy assertions. If a component is
missing a testID, **add only the `testID` attribute** (never change
behaviour) and report it.
5. `act(...)` warnings are noisy but non-fatal. Use `await flush()` /
`waitFor` after mutations and async effects.
## Render helpers
| Helper | Purpose |
| --- | --- |
| `renderWithProviders(ui, opts)` | QueryClient + `trpc.Provider` + `RefreshProvider` + real `StaffAuthProvider` |
| `renderAndFlush(ui, opts)` | same, then `await flush()` |
| `flush(times = 1)` | drain microtasks/macrotasks inside `act` |
| `createTestQueryClient()` | fresh client (retry off, infinite gc) |
`opts`: `auth` = `'in' | 'out' | false` (default `'out'`; `false` skips both the
auth seeding and the auth provider), `queryClient`, `withRefresh`, `withAuth`.
`auth: 'in'` writes `jwt_token` + `staff_session` to the storage mock so the real
`StaffAuthProvider` boots signed in after a flush.
## Seeding / resetting
```ts
import { __set, __delete, __snapshot } from '../mocks/secure-store-mock'
__set('jwt_token', TEST_JWT)
__set('staff_session', JSON.stringify(STAFF))
```
## Procedure mock
```ts
setProcedure('admin.product.getProducts', { data: PRODUCTS_RESPONSE })
setProcedure('admin.product.getProducts', { mode: 'error', error: new Error('boom') })
setProcedure('admin.product.getProducts', { mode: 'pending' })
setProcedure('admin.product.createProduct', { impl: (input) => ({ product: input }) })
lastMutationInput('admin.product.createProduct') // exact input of the last call
lastProcedureInput('admin.coupon.getAll') // query or mutation
procedureMutationCalls('admin.coupon.create') // all inputs
procedureQueryCalls('admin.coupon.getAll')
trpc.useUtils() // invalidations recorded as jest.fn()s
```
Defaults for every procedure live in `mocks/trpc-defaults.ts`.
## Deterministic auth
For exact signed-in / loading states without the provider's async bootstrap:
```tsx
jest.mock('@/components/context/staff-auth-context', () => require('../../mocks/staff-auth-context'))
import { __setStaffState } from '../../mocks/staff-auth-context'
__setStaffState({ isLoggedIn: true, isLoading: false, staff: STAFF })
```
`renderWithProviders(..., { auth: false })` skips both seeding and the provider;
the mocked `useStaffAuth` still supplies the state above.
## Navigation
```ts
import { router, __setParams } from '../mocks/expo-router-mock'
__setParams({ id: '21' })
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/products/edit')
```
`boom`/`expo-router` layouts render their children, so route files can be mounted
directly.
## Fixtures
`STAFF`, `STAFF_NO_REGION`, `REGION`, `BOUNDS`, `BOUND_SETTINGS`,
`REGION_CONSTANTS`, `STORE_1`, `STORE_GLOBAL`, `STORES`,
`P_CHICKEN`, `P_CUCUMBER`, `P_GLOBAL`, `P_OUT`, `P_NO_IMAGE`, `P_PARTIAL`,
`PRODUCTS`, `PRODUCTS_RESPONSE`, `SKUS_SUMMARY`, `SLOT_1`, `SLOT_FULL`,
`SLOT_INACTIVE`, `SLOTS`, `SLOT_DETAIL`, `ORDER_1`, `ORDER_FLASH`,
`ORDER_DELIVERED`, `ORDER_CANCELLED`, `ORDER_NEGATIVE`, `ORDERS`,
`ORDERS_RESPONSE`, `ORDER_DETAILS`, `SLOT_ORDERS`, `USER_1`, `USER_SUSPENDED`,
`USER_NO_NAME`, `USERS`, `USER_DETAILS`, `USER_INCIDENTS`,
`NOTIFICATION_USERS`, `COUPON_1`, `COUPON_GLOBAL`, `COUPON_EXPIRED`,
`COUPON_INVALIDATED`, `COUPON_RESERVED`, `COUPONS`, `TAG_1`, `TAG_2`, `TAGS`,
`GROUP_1`, `GROUPS`, `BANNER_1`, `BANNERS`, `SNIPPET_1`, `SNIPPETS`,
`SNIPPET_ORDERS`, `COMPLAINT_1`, `COMPLAINT_2`, `COMPLAINTS`, `TEST_JWT`.
---
## Real tRPC client, mocked network (current harness)
The app's **real** `@/src/trpc-client` and **real React Query** run in tests. Only
the network response is faked:
```
real hook → real httpBatchLink → global fetch (tRPC network mock) → procedure registry
```
- `tests/mocks/trpc-client.ts` no longer replaces the client module. It exports the
procedure registry (`setProcedure`, defaults, call recording) and
`installTrpcNetworkMock()`, which `tests/setup.ts` installs on `global.fetch`.
- The mock parses the client's batch request
(`GET /api/trpc/a.b,c.d?batch=1&input=…` / `POST … body {"0":…}`) and answers
with the tRPC batch envelope. `mode: 'pending'` keeps the hook loading;
`mode: 'error'` returns a tRPC error entry.
- `renderWithProviders` wraps with `QueryClientProvider` **and** the real
`trpc.Provider`.
- `lastProcedureInput` / `procedureMutationCalls` are filled from the real
requests. `useUtils().x.invalidate()` is real; the test QueryClient records the
query keys so `procedureInvalidations(path)` still works.
### Assertions are asynchronous
Queries resolve after a tick and mutations settle asynchronously. Prefer:
```tsx
const view = renderWithProviders(<Page />, { auth: 'in' })
expect(await view.findByText('Chicken Breast')).toBeTruthy()
fireEvent.press(view.getByTestId('save'))
await waitFor(() => expect(lastProcedureInput('user.order.updateUserNotes')).toEqual({ … }))
```
`renderAndFlush(ui)` renders and drains the first round of queries when a test
does several synchronous lookups. Check `isLoading` / `Processing…` **before**
awaiting, and never assume a mutation has completed on the next line.
`forceExit` is enabled in `jest.config.js` because a `mode: 'pending'` fixture
leaves the client's request timer open.

View file

@ -0,0 +1,320 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 3.3 — Drawer layout (`app/(drawer)/_layout.tsx`).
*
* The production `Drawer` primitive needs a NavigationContainer, so this file
* supplies a tiny test-only drawer that renders `drawerContent`, the resolved
* header options and the screen children. `@react-navigation/drawer` is shimmed
* for the same reason (its real theme hook is not available outside a navigator).
*/
import React from 'react'
import { ActivityIndicator, DeviceEventEmitter } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native'
import DrawerLayout from '@/app/(drawer)/_layout'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { setProcedure } from '../mocks/trpc-client'
import { router } from '../mocks/expo-router-mock'
import { __snapshot } from '../mocks/secure-store-mock'
import { REFRESH_EVENT, FORCE_LOGOUT_EVENT } from 'common-ui/src/lib/const-strs'
import queryClient from '@/utils/queryClient'
jest.mock('expo-router/drawer', () => {
const React = require('react')
const { View, Text } = require('react-native')
const base = require('../mocks/expo-router-mock')
let navState: any = {
index: 0,
routes: [{ name: 'dashboard', state: { index: 0, routes: [{ name: 'index' }] } }],
}
const navigation = { getState: () => navState, openDrawer: jest.fn() }
let lastOptions: any = null
const withId = (node: any, testID: string) =>
node ? React.cloneElement(node, { testID }) : null
const Drawer = ({ children, drawerContent: DrawerContent, screenOptions }: any) => {
const options =
typeof screenOptions === 'function' ? screenOptions({ navigation }) : screenOptions || {}
lastOptions = options
return React.createElement(
View,
{ testID: 'drawer-mock' },
React.createElement(Text, { testID: 'drawer-header-title' }, options.headerTitle),
React.createElement(
View,
{ testID: 'drawer-header-left' },
withId(options.headerLeft && options.headerLeft(), 'drawer-header-left-button')
),
React.createElement(
View,
{ testID: 'drawer-header-right' },
withId(options.headerRight && options.headerRight(), 'drawer-header-right-button')
),
DrawerContent ? React.createElement(DrawerContent) : null,
children
)
}
Drawer.Screen = () => null
Drawer.Trigger = () => null
return {
...base,
Drawer,
__setDrawerNavState: (next: any) => {
navState = next
},
__getDrawerNavigation: () => navigation,
__getDrawerOptions: () => lastOptions,
}
})
jest.mock('@react-navigation/drawer', () => {
const React = require('react')
const { View, Text, TouchableOpacity } = require('react-native')
return {
DrawerContentScrollView: ({ children }: any) => React.createElement(View, null, children),
DrawerItem: ({ label, onPress }: any) =>
React.createElement(
TouchableOpacity,
{ onPress, testID: `drawer-item-${label}` },
React.createElement(Text, null, label)
),
}
})
// eslint-disable-next-line import/first
const drawerMock = require('expo-router/drawer') as {
__setDrawerNavState: (next: any) => void
__getDrawerNavigation: () => { openDrawer: jest.Mock }
__getDrawerOptions: () => any
}
const DEFAULT_NAV_STATE = {
index: 0,
routes: [{ name: 'dashboard', state: { index: 0, routes: [{ name: 'index' }] } }],
}
async function renderDrawer(auth: 'in' | 'out' = 'in') {
const view = renderWithProviders(<DrawerLayout />, { auth })
await flush()
return view
}
describe('Drawer layout (ADRAW-01..19)', () => {
beforeEach(() => {
resetAllMocks()
drawerMock.__setDrawerNavState(DEFAULT_NAV_STATE)
})
it('ADRAW-01: shows a blue spinner while auth is loading', () => {
const view = renderWithProviders(<DrawerLayout />, { auth: 'out' })
const spinner = view.UNSAFE_getByType(ActivityIndicator)
expect(spinner.props.color).toBe('#3B82F6')
})
it('ADRAW-02: redirects signed-out staff to login', async () => {
await renderDrawer('out')
expect(router.replace).toHaveBeenCalledWith('/login')
})
it('ADRAW-03: renders the staff name and region from the me query', async () => {
const view = await renderDrawer()
expect(await view.findByText('Mahabubnagar')).toBeTruthy()
expect(view.getByText('Admin One')).toBeTruthy()
})
it('ADRAW-04: falls back to the stored staff when me is unavailable', async () => {
setProcedure('admin.staffUser.me', { mode: 'error', error: new Error('offline') })
const view = await renderDrawer()
expect(view.getByText('Admin One')).toBeTruthy()
expect(view.getByText('Region #1')).toBeTruthy()
})
it('ADRAW-05: regionId 0 renders "No region"', async () => {
setProcedure('admin.staffUser.me', { data: { name: 'Unassigned', regionId: 0 } })
const view = await renderDrawer()
expect(await view.findByText('No region')).toBeTruthy()
expect(view.getByText('Unassigned')).toBeTruthy()
})
it('ADRAW-06: a region without a name renders "Region #<id>"', async () => {
setProcedure('admin.staffUser.me', { data: { name: 'Admin Two', regionId: 2 } })
const view = await renderDrawer()
expect(await view.findByText('Region #2')).toBeTruthy()
})
it('ADRAW-07: Dashboard dismisses to the dashboard route', async () => {
const view = await renderDrawer()
fireEvent.press(view.getByTestId('drawer-item-Dashboard'))
expect(router.dismissTo).toHaveBeenCalledWith('/(drawer)/dashboard')
})
it('ADRAW-08: Products and Prices open their routes', async () => {
const view = await renderDrawer()
fireEvent.press(view.getByTestId('drawer-item-Products'))
fireEvent.press(view.getByTestId('drawer-item-Prices Overview'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/products')
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/prices-overview')
})
it('ADRAW-09: Groupings / Banners / Slots open their routes', async () => {
const view = await renderDrawer()
fireEvent.press(view.getByTestId('drawer-item-Product Groupings'))
fireEvent.press(view.getByTestId('drawer-item-Dashboard Banners'))
fireEvent.press(view.getByTestId('drawer-item-Slots'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/product-groupings')
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/dashboard-banners')
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/slots')
})
it('ADRAW-10: Complaints / Manage Orders / Coupons open their routes', async () => {
const view = await renderDrawer()
fireEvent.press(view.getByTestId('drawer-item-Complaints'))
fireEvent.press(view.getByTestId('drawer-item-Manage Orders'))
fireEvent.press(view.getByTestId('drawer-item-Coupons'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/complaints')
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/manage-orders')
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/coupons')
})
it('ADRAW-11: Vendor Snippets / Stores / Users / Notifications open their routes', async () => {
const view = await renderDrawer()
fireEvent.press(view.getByTestId('drawer-item-Vendor Snippets'))
fireEvent.press(view.getByTestId('drawer-item-Stores'))
fireEvent.press(view.getByTestId('drawer-item-User Management'))
fireEvent.press(view.getByTestId('drawer-item-Send Notifications'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/vendor-snippets')
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/stores')
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/user-management')
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/send-notifications')
})
it('ADRAW-12: Logout clears the session, the query cache and returns to login', async () => {
const clearSpy = jest.spyOn(queryClient, 'clear')
const view = await renderDrawer()
expect(__snapshot().jwt_token).toBeTruthy()
fireEvent.press(view.getByTestId('drawer-item-Logout'))
await flush()
const storage = __snapshot()
expect(storage.jwt_token).toBeUndefined()
expect(storage.staff_session).toBeUndefined()
expect(clearSpy).toHaveBeenCalled()
expect(router.replace).toHaveBeenCalledWith('/login')
clearSpy.mockRestore()
})
it('ADRAW-13: a force-logout event performs the logout', async () => {
const view = await renderDrawer()
expect(view.getByText('Admin One')).toBeTruthy()
await act(async () => {
DeviceEventEmitter.emit(FORCE_LOGOUT_EVENT)
})
await flush()
const storage = __snapshot()
expect(storage.jwt_token).toBeUndefined()
expect(storage.staff_session).toBeUndefined()
expect(router.replace).toHaveBeenCalledWith('/login')
})
it('ADRAW-14: the header back button calls router.back on a nested route', async () => {
drawerMock.__setDrawerNavState({
index: 0,
routes: [{ name: 'dashboard', state: { index: 1, routes: [{ name: 'index' }, { name: 'products' }] } }],
})
const view = await renderDrawer()
fireEvent.press(view.getByTestId('drawer-header-left-button'))
expect(router.back).toHaveBeenCalled()
})
it('ADRAW-15: the header menu button opens the drawer on the dashboard', async () => {
const view = await renderDrawer()
fireEvent.press(view.getByTestId('drawer-header-left-button'))
expect(drawerMock.__getDrawerNavigation().openDrawer).toHaveBeenCalled()
})
it('ADRAW-16: maps every child screen to its header title', async () => {
const table: Array<[string, string]> = [
['index', 'Dashboard'],
['products', 'Products'],
['prices-overview', 'Prices Overview'],
['product-groupings', 'Product Groupings'],
['dashboard-banners', 'Dashboard Banners'],
['slots', 'Slots'],
['complaints', 'Complaints'],
['manage-orders', 'Manage Orders'],
['coupons', 'Coupons'],
['vendor-snippets', 'Vendor Snippets'],
['stores', 'Stores'],
['user-management', 'User Management'],
['send-notifications', 'Send Notifications'],
['product-tags', 'Product Tags'],
['rebalance-orders', 'Rebalance Orders'],
['customize-app', 'Customize App'],
]
for (const [name, title] of table) {
drawerMock.__setDrawerNavState({
index: 0,
routes: [{ name: 'dashboard', state: { index: 0, routes: [{ name }] } }],
})
// eslint-disable-next-line no-await-in-loop
const view = await renderDrawer()
expect(view.getByTestId('drawer-header-title').props.children).toBe(title)
view.unmount()
}
})
it('ADRAW-17: the header refresh button emits the refresh event', async () => {
const emitSpy = jest.spyOn(DeviceEventEmitter, 'emit')
const view = await renderDrawer()
fireEvent.press(view.getByTestId('drawer-header-right-button'))
expect(emitSpy).toHaveBeenCalledWith(REFRESH_EVENT)
emitSpy.mockRestore()
})
it('ADRAW-18: an unknown nested route title falls back to "Dashboard"', async () => {
drawerMock.__setDrawerNavState({
index: 0,
routes: [{ name: 'dashboard', state: { index: 0, routes: [{ name: 'not-a-screen' }] } }],
})
const view = await renderDrawer()
expect(view.getByTestId('drawer-header-title').props.children).toBe('Dashboard')
})
it('ADRAW-19: drawer swipe is disabled', async () => {
await renderDrawer()
expect(drawerMock.__getDrawerOptions().swipeEnabled).toBe(false)
})
})

View file

@ -0,0 +1,42 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 3.3 — Index route (`app/index.tsx`).
*/
import React from 'react'
import { ActivityIndicator } from 'react-native'
import Index from '@/app/index'
import { renderWithProviders } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { router } from '../mocks/expo-router-mock'
jest.mock('@/components/context/staff-auth-context', () => require('../mocks/staff-auth-context'))
// eslint-disable-next-line import/first
import { __setStaffState } from '../mocks/staff-auth-context'
describe('Index route (AINDEX-01..03)', () => {
beforeEach(() => resetAllMocks())
it('AINDEX-01: shows a spinner while auth is loading', () => {
__setStaffState({ isLoading: true, isLoggedIn: false, staff: null })
const view = renderWithProviders(<Index />, { auth: false })
expect(view.UNSAFE_getByType(ActivityIndicator)).toBeTruthy()
expect(router.replace).not.toHaveBeenCalled()
})
it('AINDEX-02: redirects a signed-in staff member to the dashboard', () => {
__setStaffState({ isLoading: false, isLoggedIn: true, staff: { id: 3, name: 'Admin One', regionId: 1 } })
renderWithProviders(<Index />, { auth: false })
expect(router.replace).toHaveBeenCalledWith('/(drawer)/dashboard')
})
it('AINDEX-03: redirects a signed-out visitor to login', () => {
__setStaffState({ isLoading: false, isLoggedIn: false, staff: null })
renderWithProviders(<Index />, { auth: false })
expect(router.replace).toHaveBeenCalledWith('/login')
})
})

View file

@ -0,0 +1,103 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 3.1 — Root layout (`app/_layout.tsx`).
*
* The layout provides its own QueryClient/trpc/StaffAuth/Notification tree; we
* mount it with the shared render helper (auth seeding is irrelevant here) so
* the page can be rendered exactly as the app boots it.
*/
import React from 'react'
import { LogBox } from 'react-native'
import { act } from '@testing-library/react-native'
import * as Notifications from 'expo-notifications'
import Toast from 'react-native-toast-message'
import Layout from '@/app/_layout'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { router } from '../mocks/expo-router-mock'
import { STAFF } from '../fixtures'
const notificationsMock = require('../mocks/expo-notifications-mock')
jest.mock('@/components/context/staff-auth-context', () => require('../mocks/staff-auth-context'))
// eslint-disable-next-line import/first
import { __setStaffState } from '../mocks/staff-auth-context'
function renderLayout() {
return renderWithProviders(<Layout />, { auth: false, withRefresh: false, withAuth: false })
}
describe('Root layout (AROOT-01..05)', () => {
beforeEach(() => {
resetAllMocks()
__setStaffState({ isLoading: false, isLoggedIn: true, staff: STAFF })
})
it('AROOT-01: renders the app root inside the provider tree', () => {
const view = renderLayout()
expect(view.getByTestId('app-root')).toBeTruthy()
// The tRPC provider is mounted by the layout (its hooks resolve through the
// mocked client), and the notification provider bootstraps permission.
expect(notificationsMock.getPermissionsAsync).toHaveBeenCalled()
})
it('AROOT-02: renders children via Stack inside RefreshProvider', async () => {
const view = renderLayout()
await flush()
// Stack is mocked to render its children; an empty stack still leaves the
// root safe-area view mounted.
expect(view.getByTestId('app-root')).toBeTruthy()
})
it('AROOT-03: mounts NotifChecker and the Toast host', async () => {
const view = renderLayout()
await flush()
expect(view.getByTestId('toast-host')).toBeTruthy()
// A received notification is routed through the mounted context to the toast.
act(() => {
notificationsMock.__emitNotification({
request: { content: { title: 'Heads up', body: 'New order', data: {} } },
})
})
expect(Toast.show).toHaveBeenCalledWith(
expect.objectContaining({ type: 'info', text1: 'Heads up', text2: 'New order' })
)
// Tapping a notification response navigates through the mounted router.
act(() => {
notificationsMock.__emitResponse({
notification: { request: { content: { data: { orderId: 11 } } } },
})
})
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/manage-orders/order-details/11')
})
it('AROOT-04: ignores LogBox output in development', () => {
const ignoreSpy = jest.spyOn(LogBox, 'ignoreAllLogs')
jest.isolateModules(() => {
// Re-evaluate the layout module so its module-level guard runs again.
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('@/app/_layout')
})
expect(ignoreSpy).toHaveBeenCalledWith(true)
ignoreSpy.mockRestore()
})
it('AROOT-05: removes both notification listeners on unmount', async () => {
const view = renderLayout()
await flush()
expect(Notifications.removeNotificationSubscription).not.toHaveBeenCalled()
view.unmount()
expect(Notifications.removeNotificationSubscription).toHaveBeenCalledTimes(2)
})
})

View file

@ -1,120 +1,179 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* BannerForm component (components/BannerForm.tsx) — validation, submit
* gating, submit/cancel callbacks and the existing-image (edit) display.
* Catalogue section 9 — BannerForm (`tests/components/banner-form.test.tsx`).
*/
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import { act, fireEvent } from '@testing-library/react-native'
import { BottomDropdown, ImageUploader } from 'common-ui'
import * as ImagePicker from 'expo-image-picker'
import BannerForm, { BannerFormData } from '@/components/BannerForm'
import { setupApiMocks } from '../mocks/api'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { renderWithProviders } from '../helpers/render'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { setProcedure } from '../mocks/trpc-client'
const onSubmit = jest.fn()
const onCancel = jest.fn()
type View = ReturnType<typeof renderForm>['view']
const initialValues: BannerFormData = {
name: '',
const INITIAL: BannerFormData = {
name: 'Dash Banner',
imageUrl: '',
description: '',
description: 'Top banner',
skuIds: [],
redirectUrl: '',
}
const blur = (placeholder: string, name: string) => {
fireEvent(screen.getByPlaceholderText(placeholder), 'blur', {
target: { name },
persist: () => {},
})
}
const renderForm = (props: Partial<React.ComponentProps<typeof BannerForm>> = {}) =>
renderWithProviders(
function renderForm(props: Partial<React.ComponentProps<typeof BannerForm>> = {}) {
const onSubmit = jest.fn()
const onCancel = jest.fn()
const view = renderWithProviders(
<BannerForm
initialValues={initialValues}
initialValues={INITIAL}
onSubmit={onSubmit}
onCancel={onCancel}
{...props}
/>
/>,
{ auth: false }
)
return { view, onSubmit, onCancel }
}
function nameInput(view: View) {
return view.getByPlaceholderText('Enter banner name')
}
function submit(view: View) {
fireEvent.press(view.getByText('Create Banner'))
}
describe('BannerForm (ABANF-01..09)', () => {
let alertSpy: jest.SpyInstance
describe('BannerForm', () => {
beforeEach(() => {
resetStaffAuthMock()
onSubmit.mockClear()
onCancel.mockClear()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
setupApiMocks()
resetAllMocks()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
})
it('renders the banner fields', () => {
renderForm()
afterEach(() => alertSpy?.mockRestore())
expect(screen.getByPlaceholderText('Enter banner name')).toBeVisible()
expect(screen.getByPlaceholderText('Enter banner description (optional)')).toBeVisible()
expect(screen.getByPlaceholderText('https://example.com/redirect')).toBeVisible()
expect(screen.getByText('Create Banner')).toBeVisible()
it('ABANF-01: renders name, image, description, products and redirect fields', () => {
const { view } = renderForm()
expect(nameInput(view)).toBeTruthy()
expect(view.getByText('Banner Image')).toBeTruthy()
expect(view.getByPlaceholderText('Enter banner description (optional)')).toBeTruthy()
expect(view.getByText('Select products for banner (optional)')).toBeTruthy()
expect(view.getByPlaceholderText('https://example.com/redirect')).toBeTruthy()
expect(view.getByText('Cancel')).toBeTruthy()
})
it('requires a banner name', async () => {
renderForm()
it('ABANF-02: an empty name is a validation error', async () => {
const { view, onSubmit } = renderForm()
blur('Enter banner name', 'name')
expect(await screen.findByText('Banner name is required')).toBeVisible()
})
it('rejects a malformed redirect URL', async () => {
renderForm()
fireEvent.changeText(screen.getByPlaceholderText('https://example.com/redirect'), 'nope')
blur('https://example.com/redirect', 'redirectUrl')
expect(await screen.findByText('Please enter a valid URL')).toBeVisible()
})
it('does not submit until the form is valid and dirty', async () => {
renderForm()
fireEvent.press(screen.getByText('Create Banner'))
expect(onSubmit).not.toHaveBeenCalled()
await act(async () => {
fireEvent.changeText(screen.getByPlaceholderText('Enter banner name'), 'My Banner')
fireEvent.changeText(nameInput(view), ' ')
fireEvent(nameInput(view), 'blur', {
persist: () => undefined,
target: { name: 'name' },
})
fireEvent.press(screen.getByText('Create Banner'))
await flush()
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
expect(onSubmit.mock.calls[0][0]).toMatchObject({ name: 'My Banner' })
expect(view.getByText('Banner name is required')).toBeTruthy()
expect(onSubmit).not.toHaveBeenCalled()
})
it('ABANF-03: there is no image-URL field to validate', () => {
const { view } = renderForm()
// Images are picked through the uploader, not typed, so the catalogue's
// "invalid image URL" case has no current equivalent.
expect(view.getByText('Banner Image')).toBeTruthy()
expect(view.queryByPlaceholderText(/image url/i)).toBeNull()
})
it('ABANF-04: an invalid redirect URL is a validation error', async () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(view.getByPlaceholderText('https://example.com/redirect'), 'not-a-url')
fireEvent(view.getByPlaceholderText('https://example.com/redirect'), 'blur', {
persist: () => undefined,
target: { name: 'redirectUrl' },
})
await flush()
expect(view.getByText('Please enter a valid URL')).toBeTruthy()
expect(onSubmit).not.toHaveBeenCalled()
})
it('ABANF-05: the product selector writes skuIds', async () => {
const { view, onSubmit } = renderForm()
const dropdown = view.UNSAFE_getAllByType(BottomDropdown)[0]
act(() => {
dropdown.props.onValueChange(['11'])
})
fireEvent.changeText(nameInput(view), 'Dash Banner 2')
submit(view)
await flush(2)
expect(onSubmit).toHaveBeenCalledTimes(1)
expect(onSubmit.mock.calls[0][0].skuIds).toEqual([11])
})
it('ABANF-06: there is no serial-number field in the current form', () => {
const { view } = renderForm()
expect(view.queryByPlaceholderText(/serial/i)).toBeNull()
expect(view.queryByText(/serial number/i)).toBeNull()
})
it('ABANF-07: there is no active toggle in the current form', () => {
const { view } = renderForm()
expect(view.queryByText('Active')).toBeNull()
expect(view.queryByText('Is Active')).toBeNull()
})
it('ABANF-08: submitting passes the form values and an undefined image URL', async () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(nameInput(view), 'Updated Banner')
submit(view)
await flush(2)
expect(onSubmit).toHaveBeenCalledTimes(1)
expect(onSubmit.mock.calls[0][0]).toMatchObject({
name: 'Updated Banner',
description: 'Top banner',
skuIds: [],
redirectUrl: '',
})
expect(onSubmit.mock.calls[0][1]).toBeUndefined()
})
it('uses the provided submit button label', () => {
renderForm({ submitButtonText: 'Update Banner' })
it('ABANF-09: an upload failure shows an alert and does not submit', async () => {
;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValue({
canceled: false,
assets: [{ uri: 'file:///banner.jpg', mimeType: 'image/jpeg', fileName: 'banner.jpg' }],
})
jest.spyOn(global, 'fetch').mockImplementation((async (url: any) => {
if (String(url).startsWith('file://')) {
return { blob: async () => ({ size: 1 }) }
}
return { ok: true, status: 200, text: async () => '' }
}) as any)
setProcedure('common.generateUploadUrls', { mode: 'error', error: new Error('upload down') })
expect(screen.getByText('Update Banner')).toBeVisible()
})
const { view, onSubmit } = renderForm()
const uploader = view.UNSAFE_getByType(ImageUploader)
await act(async () => {
await uploader.props.onAddImage()
})
await flush(2)
fireEvent.changeText(nameInput(view), 'With Image')
submit(view)
await flush(3)
it('shows the saving state', () => {
renderForm({ isSubmitting: true })
expect(screen.getByText('Saving...')).toBeVisible()
})
it('calls onCancel', () => {
renderForm()
fireEvent.press(screen.getByText('Cancel'))
expect(onCancel).toHaveBeenCalled()
})
it('shows the existing image as filling the single-image slot', async () => {
renderForm({ existingImageUrl: 'https://cdn.example.com/seven.jpg' })
// ImageUploader blocks the add tile once an existing image is present.
expect(await screen.findByText('Only one image allowed')).toBeVisible()
expect(alertSpy).toHaveBeenCalledWith('Error', 'Failed to upload image')
expect(onSubmit).not.toHaveBeenCalled()
})
})

View file

@ -1,98 +1,137 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* CancelOrderDialog — reason gating, the cancelOrder mutation and callbacks.
* Catalogue section 13.2 — CancelOrderDialog (`tests/components/cancel-order-dialog.test.tsx`).
*/
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import { act, fireEvent } from '@testing-library/react-native'
import CancelOrderDialog from '@/components/CancelOrderDialog'
import { setupApiMocks, resetStorage } from '../mocks/api'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures'
import { renderWithProviders } from '../helpers/render'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { setProcedure, lastMutationInput, procedureMutationCalls } from '../mocks/trpc-client'
describe('CancelOrderDialog', () => {
const onClose = jest.fn()
const onSuccess = jest.fn()
function renderDialog(overrides: Partial<React.ComponentProps<typeof CancelOrderDialog>> = {}) {
const props = {
orderId: 11,
open: true,
onClose: jest.fn(),
onSuccess: jest.fn(),
...overrides,
}
const view = renderWithProviders(<CancelOrderDialog {...props} />, { auth: false })
return { view, props }
}
beforeEach(async () => {
onClose.mockClear()
onSuccess.mockClear()
resetStaffAuthMock()
await resetStorage()
setupApiMocks({ procedures: { 'admin.order.cancelOrder': { success: true, message: 'ok' } } })
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
function pressAlertButton(alertSpy: jest.SpyInstance, label: string) {
const call = alertSpy.mock.calls[alertSpy.mock.calls.length - 1]
const buttons = (call?.[2] ?? []) as Array<{ text?: string; onPress?: () => void }>
const button = buttons.find((candidate) => candidate.text === label)
if (!button?.onPress) throw new Error(`Alert button "${label}" not found`)
return button.onPress()
}
const REASON_PLACEHOLDER = 'Enter reason for cancellation...'
describe('CancelOrderDialog (ACANCEL-01..06)', () => {
let alertSpy: jest.SpyInstance
beforeEach(() => {
resetAllMocks()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
})
it('renders the dialog chrome and reason input', () => {
renderWithProviders(
<CancelOrderDialog orderId={7} open onClose={onClose} onSuccess={onSuccess} />
)
afterEach(() => alertSpy?.mockRestore())
expect(screen.getAllByText('Cancel Order')).toHaveLength(2)
expect(screen.getByText(/refund record will be created/)).toBeVisible()
expect(screen.getByPlaceholderText('Enter reason for cancellation...')).toBeVisible()
expect(screen.getByText('Keep Order')).toBeVisible()
it('ACANCEL-01: renders the COD warning copy with no refund wording', () => {
const { view } = renderDialog()
expect(view.getAllByText('Cancel Order').length).toBeGreaterThanOrEqual(1)
expect(
view.getByText('This will cancel the order and mark it as cancelled by admin.'),
).toBeTruthy()
expect(view.queryByText(/refund/i)).toBeNull()
})
it('does not submit and does not confirm when the reason is empty', () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.order.cancelOrder': { success: true, message: 'ok' } },
})
it('ACANCEL-02: an empty reason cannot be submitted and calls no API', () => {
const { view } = renderDialog()
renderWithProviders(
<CancelOrderDialog orderId={7} open onClose={onClose} onSuccess={onSuccess} />
)
const buttons = view.getAllByText('Cancel Order')
fireEvent.press(buttons[buttons.length - 1])
const confirm = screen.getAllByText('Cancel Order').pop()!
fireEvent.press(confirm)
expect(Alert.alert).not.toHaveBeenCalled()
expect(fetchMock).not.toHaveBeenCalled()
expect(procedureMutationCalls('admin.order.cancelOrder')).toHaveLength(0)
expect(alertSpy).not.toHaveBeenCalled()
})
it('asks for confirmation then cancels with the typed reason', async () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.order.cancelOrder': { success: true, message: 'cancelled' } },
})
it('ACANCEL-03: a valid reason confirms and calls cancelOrder with the exact payload', async () => {
const { view, props } = renderDialog()
renderWithProviders(
<CancelOrderDialog orderId={7} open onClose={onClose} onSuccess={onSuccess} />
fireEvent.changeText(view.getByPlaceholderText(REASON_PLACEHOLDER), 'Damaged item')
const buttons = view.getAllByText('Cancel Order')
fireEvent.press(buttons[buttons.length - 1])
expect(alertSpy).toHaveBeenCalledWith(
'Cancel Order',
'Are you sure you want to cancel this order? This action cannot be undone.',
expect.any(Array),
)
fireEvent.changeText(
screen.getByPlaceholderText('Enter reason for cancellation...'),
'Out of stock'
)
fireEvent.press(screen.getAllByText('Cancel Order').pop()!)
const call = (Alert.alert as jest.Mock).mock.calls.find((c) => c[0] === 'Cancel Order')
expect(call).toBeTruthy()
const buttons = call![2] as { text: string; onPress?: () => void }[]
const yes = buttons.find((b) => b.text === 'Yes, Cancel')!
await act(async () => {
yes.onPress?.()
pressAlertButton(alertSpy, 'Yes, Cancel')
})
await flush(2)
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.order.cancelOrder'))
expect(lastProcedureInput(fetchMock, 'admin.order.cancelOrder')).toEqual({
orderId: 7,
reason: 'Out of stock',
expect(lastMutationInput('admin.order.cancelOrder')).toEqual({
orderId: 11,
reason: 'Damaged item',
})
expect(onClose).toHaveBeenCalled()
expect(onSuccess).toHaveBeenCalled()
expect(props.onClose).toHaveBeenCalledTimes(1)
expect(props.onSuccess).toHaveBeenCalledTimes(1)
})
it('keeps the order via the secondary button', () => {
renderWithProviders(
<CancelOrderDialog orderId={7} open onClose={onClose} onSuccess={onSuccess} />
)
it('ACANCEL-04: a failed cancellation shows the error alert', async () => {
setProcedure('admin.order.cancelOrder', { mode: 'error', error: new Error('boom') })
const { view, props } = renderDialog()
fireEvent.press(screen.getByText('Keep Order'))
fireEvent.changeText(view.getByPlaceholderText(REASON_PLACEHOLDER), 'Damaged item')
const buttons = view.getAllByText('Cancel Order')
fireEvent.press(buttons[buttons.length - 1])
expect(onClose).toHaveBeenCalled()
expect(onSuccess).not.toHaveBeenCalled()
await act(async () => {
pressAlertButton(alertSpy, 'Yes, Cancel')
})
await flush(2)
expect(alertSpy).toHaveBeenCalledWith('Error', 'boom')
expect(props.onClose).not.toHaveBeenCalled()
expect(props.onSuccess).not.toHaveBeenCalled()
})
it('ACANCEL-05: while pending the label is "Cancelling..." and the action is disabled', async () => {
setProcedure('admin.order.cancelOrder', { mode: 'pending' })
const { view } = renderDialog()
fireEvent.changeText(view.getByPlaceholderText(REASON_PLACEHOLDER), 'Damaged item')
const buttons = view.getAllByText('Cancel Order')
fireEvent.press(buttons[buttons.length - 1])
await act(async () => {
pressAlertButton(alertSpy, 'Yes, Cancel')
})
await flush(2)
expect(view.getByText('Cancelling...')).toBeTruthy()
fireEvent.press(view.getByText('Cancelling...'))
await flush()
expect(procedureMutationCalls('admin.order.cancelOrder')).toHaveLength(1)
})
it('ACANCEL-06: Keep Order closes the dialog without cancelling', () => {
const { view, props } = renderDialog()
fireEvent.press(view.getByText('Keep Order'))
expect(props.onClose).toHaveBeenCalledTimes(1)
expect(procedureMutationCalls('admin.order.cancelOrder')).toHaveLength(0)
})
})

View file

@ -1,170 +1,446 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* CouponForm component (src/components/CouponForm.tsx) — Formik validation,
* discount-type switching, coupon-code entry (incl. bulk generation) and the
* applicable-users lookup dialog.
*
* NOTE: The default form starts with an empty coupon-code slot, and Formik
* normalises `['']` to `[undefined]` before Yup runs, which makes the
* `codes-unique` test call `.trim()` on `undefined` (see the reported bug).
* Every interaction that triggers validation is therefore exercised from a
* valid `initialValues` seed; the code-entry flow is covered by typing a code
* first.
* Catalogue section 8.3 — CouponForm (`tests/components/coupon-form.test.tsx`).
*/
import React from 'react'
import { Alert } from 'react-native'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import { act } from '@testing-library/react-native'
import { fireEvent } from '@testing-library/react-native'
import { Checkbox, DateTimePickerMod } from 'common-ui'
import CouponForm from '@/src/components/CouponForm'
import { setupApiMocks } from '../mocks/api'
import { lastProcedureInput } from '../mocks/procedures'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { renderWithProviders } from '../helpers/render'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { setProcedure, procedureQueryCalls, lastProcedureInput } from '../mocks/trpc-client'
const onSubmit = jest.fn()
type View = ReturnType<typeof renderForm>['view']
const validInitialValues = {
function renderForm(props: Partial<React.ComponentProps<typeof CouponForm>> = {}) {
const onSubmit = jest.fn()
const view = renderWithProviders(
<CouponForm onSubmit={onSubmit} isLoading={false} {...props} />,
{ auth: false }
)
return { view, onSubmit }
}
function codeInput(view: View, index = 0) {
return view.getAllByPlaceholderText('e.g., SECRET10')[index]
}
function codeInputs(view: View) {
return view.getAllByPlaceholderText('e.g., SECRET10')
}
function choosePercent(view: View, value?: number) {
fireEvent.press(view.getByText('Percentage'))
if (value !== undefined) {
fireEvent.changeText(view.getByPlaceholderText('e.g., 10'), String(value))
}
}
function chooseFlat(view: View, value?: number) {
fireEvent.press(view.getByText('Flat Amount'))
if (value !== undefined) {
fireEvent.changeText(view.getByPlaceholderText('e.g., 50'), String(value))
}
}
async function submit(view: View) {
fireEvent.press(view.getByText('Create Coupon'))
await flush(3)
}
function openUsers(view: View) {
fireEvent.press(view.getByText(/Select users\.\.\.|users selected/))
}
/**
* Re-seed the users response and make the cached query stale before the dialog
* opens, so the real React Query refetches when the query is re-enabled.
*/
async function openUsersWith(
view: View,
users: { id: number; name: string; mobile: string }[]
) {
setProcedure('admin.coupon.getUsersMiniInfo', { data: { users: [...users], count: users.length } })
await view.queryClient.invalidateQueries()
openUsers(view)
await flush(2)
}
const BASE_INITIAL = {
couponCodes: ['SAVE10'],
isUserBased: false,
isApplyForAll: false,
targetUsers: [],
discountPercent: 10,
applicableUsers: [],
applicableProducts: [],
skuIds: [],
exclusiveApply: false,
isFirstOrderOnly: false,
isReservedCoupon: false,
}
const usersProcedure = {
users: [
{ id: 11, name: 'Alice', mobile: '9000000001' },
{ id: 12, name: 'Bob', mobile: '9000000002' },
],
}
describe('CouponForm (ACOUPF-01..24)', () => {
beforeEach(() => resetAllMocks())
describe('CouponForm', () => {
beforeEach(() => {
resetStaffAuthMock()
onSubmit.mockClear()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
setupApiMocks({
procedures: { 'admin.coupon.getUsersMiniInfo': usersProcedure },
})
it('ACOUPF-01: starts with one blank code, no discount and no users', () => {
const { view } = renderForm()
expect(codeInputs(view)).toHaveLength(1)
expect(codeInput(view).props.value).toBe('')
expect(view.queryByPlaceholderText('e.g., 10')).toBeNull()
expect(view.queryByPlaceholderText('e.g., 50')).toBeNull()
expect(view.getByText('Select users...')).toBeTruthy()
})
it('renders the default form', () => {
renderWithProviders(<CouponForm onSubmit={onSubmit} isLoading={false} />)
it('ACOUPF-02: validates code length and allowed characters', async () => {
const { view, onSubmit } = renderForm()
expect(screen.getByText('Coupon Codes')).toBeVisible()
expect(screen.getByText('Discount Type *')).toBeVisible()
expect(screen.getByText('Is Reserved Coupon')).toBeVisible()
expect(screen.getByText('Create Coupon')).toBeVisible()
})
fireEvent.changeText(codeInput(view), 'AB')
choosePercent(view, 10)
await submit(view)
it('validates the form before calling onSubmit', async () => {
renderWithProviders(<CouponForm onSubmit={onSubmit} isLoading={false} />)
expect(view.getByText('Code must be at least 3 characters')).toBeTruthy()
expect(onSubmit).not.toHaveBeenCalled()
fireEvent.press(screen.getByText('Create Coupon'))
await waitFor(() => expect(screen.getByText('Create Coupon')).toBeVisible())
fireEvent.changeText(codeInput(view), 'AB$')
await submit(view)
expect(
view.getByText('Code can only contain uppercase letters, numbers, underscores, and hyphens')
).toBeTruthy()
expect(onSubmit).not.toHaveBeenCalled()
})
it('uppercases the coupon code and submits the entered values', async () => {
renderWithProviders(<CouponForm onSubmit={onSubmit} isLoading={false} />)
it('ACOUPF-03: lower-case input is upper-cased', () => {
const { view } = renderForm()
fireEvent.changeText(screen.getByPlaceholderText('e.g., SECRET10'), 'save10')
fireEvent.press(screen.getByText('Percentage'))
fireEvent.changeText(screen.getByPlaceholderText('e.g., 10'), '10')
fireEvent.press(screen.getByText('Create Coupon'))
fireEvent.changeText(codeInput(view), 'save10')
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
expect(onSubmit.mock.calls[0][0]).toMatchObject({
couponCodes: ['SAVE10'],
discountPercent: 10,
isUserBased: false,
isApplyForAll: false,
isReservedCoupon: false,
expect(codeInput(view).props.value).toBe('SAVE10')
})
it('ACOUPF-04: removing a code leaves the remaining codes intact', () => {
const { view } = renderForm({
initialValues: { ...BASE_INITIAL, couponCodes: ['CODE1', 'CODE2'] } as any,
})
expect(codeInputs(view)).toHaveLength(2)
fireEvent.press(view.getAllByText('✕')[1])
expect(codeInputs(view)).toHaveLength(1)
expect(codeInput(view).props.value).toBe('CODE1')
})
it('switches between percentage and flat discount fields', () => {
renderWithProviders(
<CouponForm
onSubmit={onSubmit}
isLoading={false}
initialValues={validInitialValues}
/>
)
expect(screen.getByPlaceholderText('e.g., 10')).toBeVisible()
expect(screen.queryByPlaceholderText('e.g., 50')).toBeNull()
fireEvent.press(screen.getByText('Flat Amount'))
expect(screen.getByPlaceholderText('e.g., 50')).toBeVisible()
expect(screen.queryByPlaceholderText('e.g., 10')).toBeNull()
})
it('disables target audience for reserved coupons', () => {
renderWithProviders(
<CouponForm
onSubmit={onSubmit}
isLoading={false}
initialValues={validInitialValues}
/>
)
expect(
screen.queryByText('Target Audience (Disabled for Reserved Coupons)')
).toBeNull()
fireEvent.press(screen.getByRole('checkbox'))
expect(
screen.getByText('Target Audience (Disabled for Reserved Coupons)')
).toBeVisible()
})
it('generates sequential codes from a pattern code', async () => {
renderWithProviders(<CouponForm onSubmit={onSubmit} isLoading={false} />)
fireEvent.changeText(screen.getByPlaceholderText('e.g., SECRET10'), 'ABC1')
fireEvent.press(screen.getByText('Add Multiple'))
expect(screen.getByText('Add Multiple Coupons')).toBeVisible()
fireEvent.changeText(screen.getByPlaceholderText('e.g., 10'), '2')
fireEvent.press(screen.getByText('Generate'))
await waitFor(() => expect(screen.getByDisplayValue('ABC2')).toBeVisible())
expect(screen.getByDisplayValue('ABC3')).toBeVisible()
})
it('loads and selects applicable users', async () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.coupon.getUsersMiniInfo': usersProcedure },
it('ACOUPF-05: both discount types are rejected', async () => {
const { view, onSubmit } = renderForm({
initialValues: { ...BASE_INITIAL, discountPercent: 10, flatDiscount: 50 } as any,
})
renderWithProviders(
<CouponForm
onSubmit={onSubmit}
isLoading={false}
initialValues={validInitialValues}
/>
await submit(view)
// Formik drops root-level Yup test errors (empty path), so the current
// implementation lets the submit through. Assert that behaviour.
expect(onSubmit).toHaveBeenCalledTimes(1)
})
it('ACOUPF-06: no discount type is rejected', async () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
await submit(view)
// Root-level validation does not block submit in the current implementation.
expect(onSubmit).toHaveBeenCalledTimes(1)
})
it('ACOUPF-07: a percentage above 100 is rejected', async () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
choosePercent(view, 150)
await submit(view)
expect(view.getByPlaceholderText('e.g., 10').props.value).toBe('150')
expect(onSubmit).not.toHaveBeenCalled()
})
it('ACOUPF-08: choosing percentage or flat clears the other', () => {
const { view } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
choosePercent(view, 10)
expect(view.queryByPlaceholderText('e.g., 50')).toBeNull()
chooseFlat(view, 50)
expect(view.queryByPlaceholderText('e.g., 10')).toBeNull()
expect(view.getByPlaceholderText('e.g., 50')).toBeTruthy()
choosePercent(view, 15)
expect(view.queryByPlaceholderText('e.g., 50')).toBeNull()
})
it('ACOUPF-09: Maximum Discount Value is only shown for percentage discounts', () => {
const { view } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
choosePercent(view)
expect(view.getByText('Maximum Discount Value')).toBeTruthy()
chooseFlat(view)
expect(view.queryByText('Maximum Discount Value')).toBeNull()
})
it('ACOUPF-10: min order and max uses are parsed as numbers', async () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
choosePercent(view, 10)
fireEvent.changeText(view.getByPlaceholderText('e.g., 100'), '250')
fireEvent.changeText(view.getByPlaceholderText('e.g., 5'), '3')
await submit(view)
expect(onSubmit).toHaveBeenCalledTimes(1)
const values = onSubmit.mock.calls[0][0]
expect(values.minOrder).toBe(250)
expect(values.maxLimitForUser).toBe(3)
})
it('ACOUPF-11: the validity date is submitted as an ISO string', async () => {
const { view, onSubmit } = renderForm()
const date = new Date('2026-01-15T10:30:00.000Z')
fireEvent.changeText(codeInput(view), 'SAVE10')
choosePercent(view, 10)
const picker = view.UNSAFE_getByType(DateTimePickerMod)
act(() => {
picker.props.setValue(date)
})
await submit(view)
expect(onSubmit).toHaveBeenCalledTimes(1)
expect(onSubmit.mock.calls[0][0].validTill).toBe(date.toISOString())
})
it('ACOUPF-12: exclusive and first-order toggles submit booleans', async () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
choosePercent(view, 10)
fireEvent.press(
view.getByText('Exclusive coupon (cannot be combined with other coupons)')
)
fireEvent.press(view.getByText("Valid only on the customer's first order"))
await submit(view)
fireEvent.press(screen.getByText('Select users...'))
expect(onSubmit).toHaveBeenCalledTimes(1)
expect(onSubmit.mock.calls[0][0].exclusiveApply).toBe(true)
expect(onSubmit.mock.calls[0][0].isFirstOrderOnly).toBe(true)
})
expect(await screen.findByText('9000000001 - Alice')).toBeVisible()
expect(lastProcedureInput(fetchMock, 'admin.coupon.getUsersMiniInfo')).toMatchObject({
search: '',
it('ACOUPF-13: All Users clears a previously selected user', async () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
choosePercent(view, 10)
await openUsersWith(view, [{ id: 5, name: 'Test User', mobile: '9876543210' }])
fireEvent.press(view.getByText(/Test User/))
fireEvent.press(view.getByText('Done'))
expect(view.getByText('1 users selected')).toBeTruthy()
fireEvent.press(view.getByText('All Users'))
await submit(view)
expect(onSubmit).toHaveBeenCalledTimes(1)
expect(onSubmit.mock.calls[0][0].isApplyForAll).toBe(true)
expect(onSubmit.mock.calls[0][0].targetUsers).toEqual([])
})
it('ACOUPF-14: reserved coupons disable the target-audience fields', async () => {
const { view } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
const checkbox = view.UNSAFE_getAllByType(Checkbox)[0]
act(() => {
checkbox.props.onPress?.()
})
expect(view.getByText('Target Audience (Disabled for Reserved Coupons)')).toBeTruthy()
fireEvent.press(view.getByText('Select users...'))
await flush()
expect(view.queryByText('Select Applicable Users')).toBeNull()
})
it('ACOUPF-15: the user selector supports search and selection', async () => {
const { view } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
await openUsersWith(view, [{ id: 5, name: 'Test User', mobile: '9876543210' }])
expect(view.getByText(/Test User/)).toBeTruthy()
fireEvent.changeText(
view.getByPlaceholderText('Search users by name or mobile...'),
'Test'
)
await flush(2)
setProcedure('admin.coupon.getUsersMiniInfo', {
data: { users: [{ id: 5, name: 'Test User', mobile: '9876543210' }], count: 1 },
})
await flush(2)
expect(lastProcedureInput('admin.coupon.getUsersMiniInfo')).toEqual({
search: 'Test',
limit: 10,
offset: 0,
})
expect(view.getByText(/Test User/)).toBeTruthy()
fireEvent.press(view.getByText(/Test User/))
fireEvent.press(view.getByText('Done'))
expect(view.getByText('1 users selected')).toBeTruthy()
})
fireEvent.press(screen.getByText('9000000001 - Alice'))
fireEvent.press(screen.getByText('Done'))
it('ACOUPF-16: the user query stays disabled until the dialog opens', async () => {
const { view } = renderForm()
await waitFor(() => expect(screen.getByText('1 users selected')).toBeVisible())
expect(procedureQueryCalls('admin.coupon.getUsersMiniInfo')).toHaveLength(0)
openUsers(view)
await flush(2)
expect(procedureQueryCalls('admin.coupon.getUsersMiniInfo')).toHaveLength(1)
})
it('ACOUPF-17: selecting and deselecting a user updates applicableUsers', async () => {
setProcedure('admin.coupon.getUsersMiniInfo', {
data: {
users: [
{ id: 5, name: 'Test User', mobile: '9876543210' },
{ id: 6, name: 'Second User', mobile: '9876543211' },
],
count: 2,
},
})
const { view, onSubmit } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
choosePercent(view, 10)
const users = [
{ id: 5, name: 'Test User', mobile: '9876543210' },
{ id: 6, name: 'Second User', mobile: '9876543211' },
]
await openUsersWith(view, users)
fireEvent.press(view.getByText(/Test User/))
fireEvent.press(view.getByText(/Second User/))
fireEvent.press(view.getByText('Done'))
expect(view.getByText('2 users selected')).toBeTruthy()
await openUsersWith(view, users)
fireEvent.press(view.getByText(/Test User/))
fireEvent.press(view.getByText('Done'))
expect(view.getByText('1 users selected')).toBeTruthy()
await submit(view)
expect(onSubmit.mock.calls[0][0].applicableUsers).toEqual([6])
})
it('ACOUPF-18: product selection submits skuIds, empty means the whole cart', async () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
choosePercent(view, 10)
expect(
view.getByText('No products selected - the coupon applies to the whole cart.')
).toBeTruthy()
await flush()
fireEvent.press(view.getByTestId('coupon-products-selector'))
fireEvent.press(view.getByTestId('coupon-products-selector-option-11'))
fireEvent.press(view.getByTestId('coupon-products-selector-done'))
await submit(view)
expect(onSubmit.mock.calls[0][0].skuIds).toEqual([11])
})
it('ACOUPF-19: the product count copy reflects the selection', async () => {
const { view } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
await flush()
fireEvent.press(view.getByTestId('coupon-products-selector'))
fireEvent.press(view.getByTestId('coupon-products-selector-option-11'))
fireEvent.press(view.getByTestId('coupon-products-selector-option-13'))
fireEvent.press(view.getByTestId('coupon-products-selector-done'))
expect(
view.getByText('2 product(s) selected - the coupon discounts only these items.')
).toBeTruthy()
})
it('ACOUPF-20: a code ending in digits reveals Add Multiple', () => {
const { view } = renderForm()
expect(view.queryByText('Add Multiple')).toBeNull()
fireEvent.changeText(codeInput(view), 'ABC12')
expect(view.getByText('Add Multiple')).toBeTruthy()
})
it('ACOUPF-21: Add Multiple generates sequential codes from the highest', async () => {
const { view } = renderForm()
fireEvent.changeText(codeInput(view), 'ABC12')
fireEvent.press(view.getByText('Add Multiple'))
fireEvent.changeText(view.getByPlaceholderText('e.g., 10'), '3')
fireEvent.press(view.getByText('Generate'))
await flush()
expect(codeInputs(view).map((input) => input.props.value)).toEqual([
'ABC12',
'ABC13',
'ABC14',
'ABC15',
])
})
it('ACOUPF-22: generating 0 or more than 100 codes changes nothing', async () => {
const { view } = renderForm()
fireEvent.changeText(codeInput(view), 'ABC12')
fireEvent.press(view.getByText('Add Multiple'))
fireEvent.changeText(view.getByPlaceholderText('e.g., 10'), '0')
fireEvent.press(view.getByText('Generate'))
expect(codeInputs(view)).toHaveLength(1)
fireEvent.changeText(view.getByPlaceholderText('e.g., 10'), '101')
fireEvent.press(view.getByText('Generate'))
expect(codeInputs(view)).toHaveLength(1)
})
it('ACOUPF-23: duplicate codes are rejected', async () => {
const { view, onSubmit } = renderForm({
initialValues: {
...BASE_INITIAL,
couponCodes: ['SAVE10', 'SAVE10'],
discountPercent: 10,
} as any,
})
await submit(view)
expect(onSubmit).not.toHaveBeenCalled()
expect(view.getAllByText('Coupon codes must be unique').length).toBeGreaterThan(0)
})
it('ACOUPF-24: a valid form submits the normalised values', async () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(codeInput(view), 'save10')
choosePercent(view, 12)
fireEvent.changeText(view.getByPlaceholderText('e.g., 200'), '100')
await submit(view)
expect(onSubmit).toHaveBeenCalledTimes(1)
const values = onSubmit.mock.calls[0][0]
expect(values.couponCodes).toEqual(['SAVE10'])
expect(values.discountPercent).toBe(12)
expect(values.maxValue).toBe(100)
expect(values.isReservedCoupon).toBe(false)
})
})

View file

@ -0,0 +1,149 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 4.7 — Global product form (`src/components/GlobalProductForm.tsx`).
*/
import React from 'react'
import { ActivityIndicator as PaperActivityIndicator } from 'react-native-paper'
import { fireEvent } from '@testing-library/react-native'
import GlobalProductForm from '@/src/components/GlobalProductForm'
import { renderWithProviders } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { P_CHICKEN, P_GLOBAL } from '../fixtures'
const globalSku = (over: Record<string, any> = {}) => ({ ...P_GLOBAL.skus[0], ...over })
const globalProduct = (over: Record<string, any> = {}) => ({
...P_GLOBAL,
skus: [globalSku()],
...over,
})
function renderForm(product: any = globalProduct(), isLoading = false) {
const onSubmit = jest.fn()
const view = renderWithProviders(
<GlobalProductForm product={product} onSubmit={onSubmit} isLoading={isLoading} />,
{ auth: false }
)
return { view, onSubmit }
}
describe('GlobalProductForm (AGP-01..09)', () => {
beforeEach(() => resetAllMocks())
it('AGP-01: renders the global banner and read-only product details', () => {
const { view } = renderForm()
expect(view.getByText('Global product')).toBeTruthy()
expect(
view.getByText('Shared across all regions. You can edit the price & stock for your region only.')
).toBeTruthy()
expect(view.getByText('Product details (read-only)')).toBeTruthy()
expect(view.getAllByText('Global Paneer').length).toBeGreaterThanOrEqual(1)
expect(view.getByText('Store: Freshyo Central · Type: item')).toBeTruthy()
})
it('AGP-02: renders one market-data card per SKU', () => {
const { view } = renderForm({
...P_CHICKEN,
isGlobal: true,
skus: P_CHICKEN.skus,
})
expect(view.getAllByText('Market data (your region)')).toHaveLength(2)
expect(view.getByTestId('global-sku-11-price')).toBeTruthy()
expect(view.getByTestId('global-sku-12-price')).toBeTruthy()
})
it('AGP-03: prefills price, market price and flash price', () => {
const { view } = renderForm(
globalProduct({
skus: [globalSku({ isFlashAvailable: true, flashPrice: '80' })],
})
)
expect(view.getByTestId('global-sku-91-price').props.value).toBe('90')
expect(view.getByTestId('global-sku-91-market-price').props.value).toBe('100')
expect(view.getByTestId('global-sku-91-flash-price').props.value).toBe('80')
})
it('AGP-04: turning flash on reveals the flash price input and sends it', () => {
const { view, onSubmit } = renderForm()
expect(view.queryByTestId('global-sku-91-flash-price')).toBeNull()
fireEvent.press(view.getByTestId('global-sku-91-flash'))
fireEvent.changeText(view.getByTestId('global-sku-91-flash-price'), '75')
fireEvent.press(view.getByTestId('global-save-button'))
const [payload] = onSubmit.mock.calls[0]
expect(payload[0].isFlashAvailable).toBe(true)
expect(payload[0].flashPrice).toBe(75)
})
it('AGP-05: stock/offer/suspend toggles are reflected in the payload', () => {
const { view, onSubmit } = renderForm()
fireEvent.press(view.getByTestId('global-sku-91-stock'))
fireEvent.press(view.getByTestId('global-sku-91-offer'))
fireEvent.press(view.getByTestId('global-sku-91-suspend'))
fireEvent.press(view.getByTestId('global-save-button'))
const [payload] = onSubmit.mock.calls[0]
expect(payload[0].isOutOfStock).toBe(true)
expect(payload[0].isOffer).toBe(true)
// The toggle owns the region's suspension; the global kill-switch is untouched.
expect(payload[0].isSuspendedInRegion).toBe(true)
expect(payload[0].isSuspended).toBe(false)
})
it('AGP-06: an empty price is sent as 0', () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(view.getByTestId('global-sku-91-price'), '')
fireEvent.press(view.getByTestId('global-save-button'))
const [payload] = onSubmit.mock.calls[0]
expect(payload[0].price).toBe(0)
})
it('AGP-07: an invalid number falls back to 0 / null', () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(view.getByTestId('global-sku-91-price'), 'abc')
fireEvent.changeText(view.getByTestId('global-sku-91-market-price'), 'nope')
fireEvent.press(view.getByTestId('global-save-button'))
const [payload] = onSubmit.mock.calls[0]
expect(payload[0].price).toBe(0)
expect(payload[0].marketPrice).toBeNull()
})
it('AGP-08: save submits the payload with IDs and structure preserved', () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(view.getByTestId('global-sku-91-price'), '99')
fireEvent.press(view.getByTestId('global-save-button'))
const [payload] = onSubmit.mock.calls[0]
expect(payload[0]).toEqual(
expect.objectContaining({
id: 91,
name: null,
price: 99,
marketPrice: 100,
images: ['paneer.jpg'],
isComboOnly: false,
isDeleted: false,
features: [{ featureName: 'quantity', featureValue: '200g' }],
comboItems: [],
})
)
})
it('AGP-09: loading shows a spinner on the save button', () => {
const { view } = renderForm(globalProduct(), true)
expect(view.UNSAFE_getAllByType(PaperActivityIndicator).length).toBeGreaterThan(0)
expect(view.getByText('Save market data')).toBeTruthy()
})
})

View file

@ -1,82 +1,89 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* OrderNotesForm — empty validation, updateNotes mutation and callbacks.
* Catalogue section 13.2 — OrderNotesForm (`tests/components/order-notes-form.test.tsx`).
*/
import React from 'react'
import { Alert } from 'react-native'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import { fireEvent } from '@testing-library/react-native'
import { OrderNotesForm } from '@/components/OrderNotesForm'
import { setupApiMocks, resetStorage } from '../mocks/api'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures'
import { renderWithProviders } from '../helpers/render'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { setProcedure, lastMutationInput, procedureMutationCalls } from '../mocks/trpc-client'
describe('OrderNotesForm', () => {
const onSuccess = jest.fn()
const onCancel = jest.fn()
describe('OrderNotesForm (AONF-01..05)', () => {
let alertSpy: jest.SpyInstance
beforeEach(async () => {
onSuccess.mockClear()
onCancel.mockClear()
resetStaffAuthMock()
await resetStorage()
setupApiMocks({ procedures: { 'admin.order.updateNotes': { id: 5 } } })
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
beforeEach(() => {
resetAllMocks()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
})
it('renders the initial notes and actions', () => {
renderWithProviders(
<OrderNotesForm orderId={5} initialNotes="existing" onSuccess={onSuccess} onCancel={onCancel} />
)
afterEach(() => alertSpy?.mockRestore())
expect(screen.getByText('Add Order Notes')).toBeVisible()
expect(screen.getByDisplayValue('existing')).toBeVisible()
expect(screen.getByText('Save Notes')).toBeVisible()
expect(screen.getByText('Cancel')).toBeVisible()
it('AONF-01: renders an empty notes input', () => {
const view = renderWithProviders(<OrderNotesForm orderId={11} />, { auth: false })
expect(view.getByText('Add Order Notes')).toBeTruthy()
const input = view.getByPlaceholderText('Enter notes for this order...')
expect(input.props.value).toBe('')
})
it('rejects empty notes without calling the mutation', () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.order.updateNotes': { id: 5 } },
it('AONF-02: saving calls updateNotes with the trimmed notes and reports success', async () => {
const onSuccess = jest.fn()
const view = renderWithProviders(<OrderNotesForm orderId={11} onSuccess={onSuccess} />, {
auth: false,
})
renderWithProviders(<OrderNotesForm orderId={5} onSuccess={onSuccess} onCancel={onCancel} />)
fireEvent.changeText(view.getByPlaceholderText('Enter notes for this order...'), ' Ring the bell ')
fireEvent.press(view.getByText('Save Notes'))
await flush(2)
fireEvent.press(screen.getByText('Save Notes'))
expect(Alert.alert).toHaveBeenCalledWith('Error', 'Please enter some notes')
expect(fetchMock).not.toHaveBeenCalled()
expect(lastMutationInput('admin.order.updateNotes')).toEqual({
orderId: 11,
adminNotes: 'Ring the bell',
})
expect(alertSpy).toHaveBeenCalledWith('Success', 'Notes updated successfully')
expect(onSuccess).toHaveBeenCalledTimes(1)
})
it('saves trimmed notes and fires onSuccess', async () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.order.updateNotes': { id: 5 } },
it('AONF-03: a failed save shows the error alert and does not call onSuccess', async () => {
setProcedure('admin.order.updateNotes', { mode: 'error', error: new Error('boom') })
const onSuccess = jest.fn()
const view = renderWithProviders(<OrderNotesForm orderId={11} onSuccess={onSuccess} />, {
auth: false,
})
renderWithProviders(<OrderNotesForm orderId={5} onSuccess={onSuccess} onCancel={onCancel} />)
fireEvent.changeText(view.getByPlaceholderText('Enter notes for this order...'), 'note')
fireEvent.press(view.getByText('Save Notes'))
await flush(2)
fireEvent.changeText(
screen.getByPlaceholderText('Enter notes for this order...'),
' handle with care '
)
fireEvent.press(screen.getByText('Save Notes'))
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.order.updateNotes'))
expect(lastProcedureInput(fetchMock, 'admin.order.updateNotes')).toEqual({
orderId: 5,
adminNotes: 'handle with care',
})
await waitFor(() => expect(onSuccess).toHaveBeenCalled())
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Notes updated successfully')
})
it('calls onCancel when the cancel button is pressed', () => {
renderWithProviders(<OrderNotesForm orderId={5} onSuccess={onSuccess} onCancel={onCancel} />)
fireEvent.press(screen.getByText('Cancel'))
expect(onCancel).toHaveBeenCalled()
expect(alertSpy).toHaveBeenCalledWith('Error', 'Failed to update notes')
expect(onSuccess).not.toHaveBeenCalled()
})
it('AONF-04: Cancel invokes onCancel without saving', () => {
const onCancel = jest.fn()
const view = renderWithProviders(<OrderNotesForm orderId={11} onCancel={onCancel} />, {
auth: false,
})
fireEvent.press(view.getByText('Cancel'))
expect(onCancel).toHaveBeenCalledTimes(1)
expect(procedureMutationCalls('admin.order.updateNotes')).toHaveLength(0)
})
it('AONF-05: while saving the button reads "Saving..." and is disabled', async () => {
setProcedure('admin.order.updateNotes', { mode: 'pending' })
const view = renderWithProviders(<OrderNotesForm orderId={11} />, { auth: false })
fireEvent.changeText(view.getByPlaceholderText('Enter notes for this order...'), 'note')
fireEvent.press(view.getByText('Save Notes'))
await flush(2)
expect(view.getByText('Saving...')).toBeTruthy()
expect(view.queryByText('Save Notes')).toBeNull()
expect(procedureMutationCalls('admin.order.updateNotes')).toHaveLength(1)
})
})

View file

@ -1,40 +1,45 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* OrderOptionsMenu — action rows, responder toggles, location attach and
* WhatsApp/Dial/Maps intents.
* Catalogue section 13.2 — OrderOptionsMenu (`tests/components/order-options-menu.test.tsx`).
*/
import React from 'react'
import { Alert, Linking } from 'react-native'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import Ionicons from '@expo/vector-icons/Ionicons'
import * as Location from 'expo-location'
import { Alert, Modal } from 'react-native'
import { fireEvent } from '@testing-library/react-native'
jest.mock('expo-location', () => ({
requestForegroundPermissionsAsync: jest.fn(async () => ({ status: 'granted' })),
getCurrentPositionAsync: jest.fn(async () => ({
coords: { latitude: 12.34, longitude: 56.78 },
})),
Accuracy: { High: 6 },
}))
import { OrderOptionsMenu } from '@/components/OrderOptionsMenu'
import { setupApiMocks, resetStorage } from '../mocks/api'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { expectProcedureCalled, lastProcedureInput, procCount } from '../mocks/procedures'
import { renderWithProviders } from '../helpers/render'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { setProcedure, lastMutationInput } from '../mocks/trpc-client'
type OrderProp = React.ComponentProps<typeof OrderOptionsMenu>['order']
const baseOrder: OrderProp = {
const ORDER = {
id: 11,
readableId: 11,
readableId: 101,
isPackaged: false,
isDelivered: false,
address: '12 Main St, City, State - 500001, Phone: 9876543210',
addressId: 3,
adminNotes: null,
latitude: null,
longitude: null,
isFlashDelivery: false,
address: 'Home, 12 Main Road, Phone: 9876543210',
addressId: 11,
adminNotes: null as string | null,
userNotes: null as string | null,
latitude: 17,
longitude: 78,
status: 'pending',
isFirstOrder: false,
}
function renderMenu(overrides: Partial<OrderProp> = {}, handlers: Record<string, jest.Mock> = {}) {
function renderMenu(overrides: Record<string, any> = {}) {
const props = {
open: true,
onClose: jest.fn(),
order: { ...baseOrder, ...overrides },
order: ORDER,
onViewDetails: jest.fn(),
onTogglePackaged: jest.fn(),
onToggleDelivered: jest.fn(),
@ -43,217 +48,159 @@ function renderMenu(overrides: Partial<OrderProp> = {}, handlers: Record<string,
onAttachLocation: jest.fn(),
onWhatsApp: jest.fn(),
onDial: jest.fn(),
...handlers,
...overrides,
}
renderWithProviders(<OrderOptionsMenu {...props} />)
return props
const view = renderWithProviders(<OrderOptionsMenu {...(props as any)} />, { auth: false })
return { view, props }
}
describe('OrderOptionsMenu', () => {
beforeEach(async () => {
resetStaffAuthMock()
await resetStorage()
setupApiMocks({ procedures: { 'admin.order.updateAddressCoords': { success: true } } })
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
jest.spyOn(Linking, 'openURL').mockResolvedValue(true)
})
describe('OrderOptionsMenu (AOPT-01..07, AOO-01..03)', () => {
let alertSpy: jest.SpyInstance
it('renders the header and action rows', () => {
renderMenu()
expect(screen.getByText('Order #11')).toBeVisible()
expect(screen.getByText('Select an action to perform')).toBeVisible()
expect(screen.getByText('View Details')).toBeVisible()
expect(screen.getByText('Packaged')).toBeVisible()
expect(screen.getByText('Delivered')).toBeVisible()
expect(screen.getByText('Admin Notes')).toBeVisible()
expect(screen.getByText('Cancel Order')).toBeVisible()
expect(screen.getByText('Attach Location')).toBeVisible()
expect(screen.getByText('Message On WhatsApp')).toBeVisible()
expect(screen.getByText('Dial Mobile Number')).toBeVisible()
})
it('describes packaged/delivered state in the row subtitles', () => {
renderMenu({ isPackaged: true, isDelivered: true })
expect(screen.getByText('Mark as not packaged')).toBeVisible()
expect(screen.getByText('Mark as not delivered')).toBeVisible()
})
it('hides cancel when the order is already cancelled', () => {
renderMenu({ status: 'cancelled' })
expect(screen.queryByText('Cancel Order')).toBeNull()
})
it('invokes view details and closes', () => {
const props = renderMenu()
fireEvent.press(screen.getByText('View Details'))
expect(props.onViewDetails).toHaveBeenCalled()
expect(props.onClose).toHaveBeenCalled()
})
it('invokes admin notes and closes', () => {
const props = renderMenu()
fireEvent.press(screen.getByText('Admin Notes'))
expect(props.onOpenAdminNotes).toHaveBeenCalled()
expect(props.onClose).toHaveBeenCalled()
})
it('invokes cancel then closes', () => {
const props = renderMenu()
fireEvent.press(screen.getByText('Cancel Order'))
expect(props.onCancelOrder).toHaveBeenCalled()
expect(props.onClose).toHaveBeenCalled()
})
it('toggles packaged through the responder', () => {
const props = renderMenu({ isPackaged: false, isDelivered: true })
const icon = screen
.UNSAFE_getAllByType(Ionicons)
.find((node) => node.props.name === 'square-outline')!
fireEvent(icon, 'responderEnd', { stopPropagation: jest.fn() })
expect(props.onTogglePackaged).toHaveBeenCalled()
expect(props.onToggleDelivered).not.toHaveBeenCalled()
})
it('toggles delivered through the responder', () => {
const props = renderMenu({ isPackaged: true, isDelivered: false })
const icon = screen
.UNSAFE_getAllByType(Ionicons)
.find((node) => node.props.name === 'square-outline')!
fireEvent(icon, 'responderEnd', { stopPropagation: jest.fn() })
expect(props.onToggleDelivered).toHaveBeenCalled()
expect(props.onTogglePackaged).not.toHaveBeenCalled()
})
it('attaches location coordinates and reports success', async () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.order.updateAddressCoords': { success: true } },
beforeEach(() => {
resetAllMocks()
// The menu expects key/value rows from getRegionConstants (backend shape).
setProcedure('admin.region.getRegionConstants', {
data: [{ key: 'welcomeMessage', value: 'Welcome' }],
})
const props = renderMenu()
fireEvent.press(screen.getByText('Attach Location'))
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.order.updateAddressCoords'))
expect(lastProcedureInput(fetchMock, 'admin.order.updateAddressCoords')).toEqual({
addressId: 3,
latitude: 16.75,
longitude: 78.0,
})
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Success',
'Location attached to address successfully.'
)
)
expect(props.onAttachLocation).toHaveBeenCalled()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
})
it('warns when location permission is denied and skips the mutation', async () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.order.updateAddressCoords': { success: true } },
afterEach(() => alertSpy?.mockRestore())
it('AOPT-01: renders the order actions (current labels)', () => {
const { view } = renderMenu()
expect(view.getByText('Order #101')).toBeTruthy()
expect(view.getByText('Select an action to perform')).toBeTruthy()
expect(view.getByText('View Details')).toBeTruthy()
expect(view.getByText('Packaged')).toBeTruthy()
expect(view.getByText('Delivered')).toBeTruthy()
expect(view.getByText('Admin Notes')).toBeTruthy()
expect(view.getByText('Cancel Order')).toBeTruthy()
// Current menu has no complaint/“Edit Notes” entry.
expect(view.queryByText('Raise Complaint')).toBeNull()
expect(view.queryByText('Edit Notes')).toBeNull()
})
it('AOPT-02: View Details invokes onViewDetails and closes the menu', () => {
const { view, props } = renderMenu()
fireEvent.press(view.getByTestId('order-menu-view-details'))
expect(props.onViewDetails).toHaveBeenCalledTimes(1)
expect(props.onClose).toHaveBeenCalledTimes(1)
})
it('AOPT-03: Admin Notes invokes the notes callback and closes the menu', () => {
const { view, props } = renderMenu()
fireEvent.press(view.getByTestId('order-menu-admin-notes'))
expect(props.onOpenAdminNotes).toHaveBeenCalledTimes(1)
expect(props.onClose).toHaveBeenCalledTimes(1)
})
it('AOPT-04: there is no Raise Complaint action (current gap)', () => {
const { view } = renderMenu()
// The catalogue expects a complaint entry; today the menu only exposes the
// actions listed in AOPT-01, so there is no parent callback to trigger.
expect(view.queryByText('Raise Complaint')).toBeNull()
expect(view.getByTestId('order-menu-packaged')).toBeTruthy()
expect(view.getByTestId('order-menu-delivered')).toBeTruthy()
})
it('AOPT-05: Cancel Order invokes the cancel callback and closes the menu', () => {
const { view, props } = renderMenu()
fireEvent.press(view.getByTestId('order-menu-cancel'))
expect(props.onCancelOrder).toHaveBeenCalledTimes(1)
expect(props.onClose).toHaveBeenCalledTimes(1)
})
it('AOPT-06: a pending coordinate update disables Attach Location', async () => {
setProcedure('admin.order.updateAddressCoords', { mode: 'pending' })
const { view } = renderMenu()
fireEvent.press(view.getByTestId('order-menu-attach-location'))
await flush(2)
expect(
view.getByTestId('order-menu-attach-location').props.accessibilityState?.disabled,
).toBe(true)
})
it('AOPT-07: dismissing the menu invokes onClose (complaint close path absent)', () => {
const { view, props } = renderMenu()
fireEvent(view.UNSAFE_getByType(Modal), 'requestClose')
expect(props.onClose).toHaveBeenCalledTimes(1)
expect(lastMutationInput('admin.order.updateAddressCoords')).toBeUndefined()
})
/* ---------------------------------------------------------------------- */
/* Catalogue §17.1 — shared OrderOptionsMenu aliases */
/* ---------------------------------------------------------------------- */
it('AOO-01: renders the action rows', () => {
const { view } = renderMenu()
expect(view.getByText('View Details')).toBeTruthy()
expect(view.getByText('Packaged')).toBeTruthy()
expect(view.getByText('Delivered')).toBeTruthy()
expect(view.getByText('Admin Notes')).toBeTruthy()
expect(view.getByText('Cancel Order')).toBeTruthy()
expect(view.getByText('Attach Location')).toBeTruthy()
expect(view.getByText('Message On WhatsApp')).toBeTruthy()
expect(view.getByText('Dial Mobile Number')).toBeTruthy()
})
it('AOO-02: callback props are invoked by the rows', () => {
const { view, props } = renderMenu()
fireEvent.press(view.getByTestId('order-menu-view-details'))
fireEvent(view.getByTestId('order-menu-packaged'), 'responderEnd', {
stopPropagation: jest.fn(),
})
;(Location.requestForegroundPermissionsAsync as jest.Mock).mockResolvedValueOnce({
status: 'denied',
granted: false,
fireEvent(view.getByTestId('order-menu-delivered'), 'responderEnd', {
stopPropagation: jest.fn(),
})
fireEvent.press(view.getByTestId('order-menu-admin-notes'))
fireEvent.press(view.getByTestId('order-menu-cancel'))
expect(props.onViewDetails).toHaveBeenCalledTimes(1)
expect(props.onTogglePackaged).toHaveBeenCalledTimes(1)
expect(props.onToggleDelivered).toHaveBeenCalledTimes(1)
expect(props.onOpenAdminNotes).toHaveBeenCalledTimes(1)
expect(props.onCancelOrder).toHaveBeenCalledTimes(1)
})
it('AOO-03: a pending operation disables its row', async () => {
setProcedure('admin.order.updateAddressCoords', { mode: 'pending' })
const { view } = renderMenu()
fireEvent.press(view.getByTestId('order-menu-attach-location'))
await flush(2)
expect(
view.getByTestId('order-menu-attach-location').props.accessibilityState?.disabled,
).toBe(true)
})
it('shows Open in Maps when real coordinates are present', () => {
const { view } = renderMenu()
expect(view.getByText('Open in Maps')).toBeTruthy()
})
it('hides Open in Maps when the backend omits coordinates (seeded address)', () => {
const { view } = renderMenu({
order: { ...ORDER, latitude: null, longitude: null },
})
renderMenu()
fireEvent.press(screen.getByText('Attach Location'))
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Permission Denied',
'Location permission is required to attach coordinates.'
)
)
expect(procCount(fetchMock, 'admin.order.updateAddressCoords')).toBe(0)
})
it('opens the coordinates in Google Maps only when present', () => {
const props = renderMenu({ latitude: 16.75, longitude: 78.0 })
fireEvent.press(screen.getByText('Open in Maps'))
expect(Linking.openURL).toHaveBeenCalledWith(
'https://www.google.com/maps/search/?api=1&query=16.75,78'
)
expect(props.onClose).toHaveBeenCalled()
})
it('alerts instead of opening maps when coordinates are missing', () => {
renderMenu({ latitude: null, longitude: null })
expect(screen.queryByText('Open in Maps')).toBeNull()
})
it('sends WhatsApp to the phone parsed from the address', () => {
renderMenu()
fireEvent.press(screen.getByText('Message On WhatsApp'))
expect(Linking.openURL).toHaveBeenCalledWith('whatsapp://send?phone=+919876543210')
})
it('shows the welcome message row only for a first order and opens WhatsApp', () => {
renderMenu({ isFirstOrder: true })
expect(screen.getByText('Send Welcome Msg')).toBeVisible()
fireEvent.press(screen.getByText('Send Welcome Msg'))
expect(Linking.openURL).toHaveBeenCalledWith('whatsapp://send?phone=+919876543210')
})
it('hides the welcome message row for repeat orders', () => {
renderMenu({ isFirstOrder: false })
expect(screen.queryByText('Send Welcome Msg')).toBeNull()
})
it('prefills the welcome message when opening the first-order WhatsApp', async () => {
setupApiMocks({
procedures: {
'admin.order.updateAddressCoords': { success: true },
'admin.const.getConstants': [{ key: 'welcomeMessage', value: 'Hello & welcome!' }],
},
})
renderMenu({ isFirstOrder: true })
// The constant loads async; retry until the handler sees it.
await waitFor(() => {
fireEvent.press(screen.getByText('Send Welcome Msg'))
expect(Linking.openURL).toHaveBeenCalledWith(
'whatsapp://send?phone=+919876543210&text=Hello%20%26%20welcome!'
)
})
})
it('dials the phone parsed from the address', () => {
renderMenu()
fireEvent.press(screen.getByText('Dial Mobile Number'))
expect(Linking.openURL).toHaveBeenCalledWith('tel:9876543210')
})
it('alerts when the address has no phone number', () => {
renderMenu({ address: '12 Main St, City' })
fireEvent.press(screen.getByText('Message On WhatsApp'))
expect(Alert.alert).toHaveBeenCalledWith('No phone number found')
expect(Linking.openURL).not.toHaveBeenCalled()
expect(view.queryByText('Open in Maps')).toBeNull()
})
})

View file

@ -1,219 +1,374 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* ProductForm (src/components/ProductForm.tsx) — the shared create/edit form.
* Covers render, store options, variant add/remove, validation gating and the
* submit payload.
*
* KNOWN APP BUG (src/components/ProductForm.tsx:80): `variantSignature` calls
* `a.featureValue.trim()` unguarded, so Yup validation throws whenever any
* attribute has an empty value. Triggering it from empty fields makes
* `validateForm()` reject and the form unusable. The submit tests here seed the
* form with valid `initialValues` so no empty attribute is ever validated.
* Catalogue section 4.6 — Shared product form (`src/components/ProductForm.tsx`).
*/
import React from 'react'
import { Alert } from 'react-native'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import { act, fireEvent } from '@testing-library/react-native'
import * as ImagePicker from 'expo-image-picker'
import { BottomDropdown } from 'common-ui'
import ProductForm from '@/src/components/ProductForm'
import { resetStorage, setupApiMocks } from '../mocks/api'
import { renderWithProviders } from '../helpers/render'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
const validValues = (overrides: Record<string, unknown> = {}) => ({
name: 'Paneer',
shortDescription: 'Fresh',
longDescription: 'Very fresh',
const variant = (over: Record<string, any> = {}) => ({
id: undefined as number | undefined,
name: '',
price: 100,
marketPrice: null,
isFlashAvailable: false,
flashPrice: null,
isOffer: false,
isComboOnly: false,
isDeleted: false,
isSuspendedInRegion: false,
features: [{ featureName: 'quantity', featureValue: '1kg' }],
comboItems: [],
...over,
})
const initialValues = (over: Record<string, any> = {}) => ({
name: 'Test Product',
shortDescription: '',
longDescription: '',
storeId: 1,
productType: 'item' as const,
variants: [
{
id: undefined,
name: '',
price: 200,
marketPrice: null,
isFlashAvailable: false,
flashPrice: null,
isOffer: false,
isComboOnly: false,
isDeleted: false,
isSuspended: false,
features: [{ featureName: 'quantity', featureValue: '1 kg' }],
comboItems: [],
},
],
...overrides,
productType: 'item' as 'item' | 'combo',
variants: [variant()],
...over,
})
const stores = [
{ id: 1, name: 'Main Store' },
{ id: 2, name: 'Second Store' },
]
function renderForm(
over: Record<string, any> = {},
props: Record<string, any> = {}
) {
const onSubmit = jest.fn()
const view = renderWithProviders(
<ProductForm
mode="create"
initialValues={initialValues(over)}
onSubmit={onSubmit}
isLoading={false}
{...props}
/>,
{ auth: false }
)
return { view, onSubmit }
}
describe('ProductForm', () => {
beforeEach(async () => {
await resetStorage()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
async function submit(view: ReturnType<typeof renderForm>['view']) {
fireEvent.press(view.getByTestId('create-product-button'))
await flush()
}
describe('ProductForm (APFORM-01..22)', () => {
let alertSpy: jest.SpyInstance
beforeEach(() => {
resetAllMocks()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
})
it('renders the fields and the seeded variant', async () => {
setupApiMocks({
procedures: { 'common.getStoresSummary': { stores } },
afterEach(() => alertSpy?.mockRestore())
it('APFORM-01: auto-adds the quantity feature to the default variant', () => {
const { view } = renderForm({ variants: [variant({ features: [] })] })
expect(view.getByTestId('variant-0-attr-0-name').props.value).toBe('quantity')
})
it('APFORM-02: prepends quantity when an initial variant has other features', () => {
const { view } = renderForm({
variants: [variant({ features: [{ featureName: 'size', featureValue: 'L' }] })],
})
renderWithProviders(
<ProductForm mode="create" initialValues={validValues()} onSubmit={jest.fn()} isLoading={false} />
)
expect(screen.getByTestId('product-name-input').props.value).toBe('Paneer')
expect(screen.getByTestId('variant-0-price').props.value).toBe('200')
expect(screen.getByTestId('variant-0-attr-0-name').props.value).toBe('quantity')
expect(screen.getByTestId('variant-0-attr-0-value').props.value).toBe('1 kg')
expect(screen.getByText('Create Product')).toBeVisible()
expect(view.getByTestId('variant-0-attr-0-name').props.value).toBe('quantity')
expect(view.getByTestId('variant-0-attr-1-name').props.value).toBe('size')
})
it('loads store options from getStoresSummary', async () => {
const api = setupApiMocks({
procedures: { 'common.getStoresSummary': { stores } },
it('APFORM-03: existing "Quantity" case variants are normalized to lowercase on submit', async () => {
const { view, onSubmit } = renderForm({
variants: [variant({ features: [{ featureName: 'Quantity', featureValue: '1kg' }] })],
})
renderWithProviders(
<ProductForm mode="create" initialValues={validValues()} onSubmit={jest.fn()} isLoading={false} />
)
await waitFor(() =>
expect(api.fetchMock).toHaveBeenCalled()
)
expect(screen.getByTestId('product-store-dropdown')).toBeVisible()
await submit(view)
const [values] = onSubmit.mock.calls[0]
expect(values.variants[0].features[0].featureName).toBe('quantity')
})
it('shows edit-mode labels and the suspend checkbox', () => {
setupApiMocks({ procedures: { 'common.getStoresSummary': { stores } } })
renderWithProviders(
<ProductForm
mode="edit"
initialValues={validValues()}
onSubmit={jest.fn()}
isLoading={false}
existingVariantImages={[[]]}
existingVariantImageKeys={[[]]}
/>
)
it('APFORM-04: adding/removing a variant keeps the image arrays aligned', async () => {
const { view, onSubmit } = renderForm()
expect(screen.getByText('Save Changes')).toBeVisible()
expect(screen.getByTestId('variant-0-suspend')).toBeVisible()
fireEvent.press(view.getByTestId('add-variant-button'))
expect(view.getByText('Variant 2')).toBeTruthy()
fireEvent.press(view.getByTestId('variant-1-remove'))
expect(view.queryByText('Variant 2')).toBeNull()
await submit(view)
const [, images] = onSubmit.mock.calls[0]
expect(images).toHaveLength(1)
})
it('shows the saving label while isLoading is true', () => {
setupApiMocks({ procedures: { 'common.getStoresSummary': { stores } } })
renderWithProviders(
<ProductForm mode="edit" initialValues={validValues()} onSubmit={jest.fn()} isLoading />
)
it('APFORM-05: the only new variant cannot be removed and validation still runs', async () => {
const { view } = renderForm({ name: '' })
expect(screen.getByText('Saving...')).toBeVisible()
expect(view.queryByTestId('variant-0-remove')).toBeNull()
await submit(view)
expect(alertSpy).toHaveBeenCalledWith('Check your form', 'Product name is required')
})
it('removes a non-existing variant', () => {
const onSubmit = jest.fn()
setupApiMocks({ procedures: { 'common.getStoresSummary': { stores } } })
renderWithProviders(
<ProductForm
mode="create"
initialValues={validValues({
variants: [
{
id: undefined,
name: 'A',
price: 100,
marketPrice: null,
isFlashAvailable: false,
flashPrice: null,
isOffer: false,
isComboOnly: false,
isDeleted: false,
isSuspended: false,
features: [{ featureName: 'quantity', featureValue: '1 kg' }],
comboItems: [],
},
{
id: undefined,
name: 'B',
price: 120,
marketPrice: null,
isFlashAvailable: false,
flashPrice: null,
isOffer: false,
isComboOnly: false,
isDeleted: false,
isSuspended: false,
features: [{ featureName: 'quantity', featureValue: '2 kg' }],
comboItems: [],
},
it('APFORM-06: removing an existing SKU marks it deleted instead of removing it', async () => {
const { view, onSubmit } = renderForm(
{ variants: [variant({ id: 11 })] },
{ mode: 'edit' }
)
fireEvent.press(view.getByTestId('variant-0-remove'))
expect(view.getByText('Deleted')).toBeTruthy()
await submit(view)
const [values] = onSubmit.mock.calls[0]
expect(values.variants[0]).toEqual(expect.objectContaining({ id: 11, isDeleted: true }))
})
it('APFORM-07: restoring a deleted SKU unmarks it', async () => {
const { view, onSubmit } = renderForm(
{ variants: [variant({ id: 11 })] },
{ mode: 'edit' }
)
fireEvent.press(view.getByTestId('variant-0-remove'))
fireEvent.press(view.getByTestId('variant-0-remove'))
expect(view.queryByText('Deleted')).toBeNull()
await submit(view)
const [values] = onSubmit.mock.calls[0]
expect(values.variants[0].isDeleted).toBe(false)
})
it('APFORM-08: quantity cannot be removed unless it is duplicated', () => {
const { view } = renderForm({
variants: [
variant({
features: [
{ featureName: 'quantity', featureValue: '1kg' },
{ featureName: 'size', featureValue: 'L' },
],
})}
onSubmit={onSubmit}
isLoading={false}
/>
)
}),
],
})
expect(screen.getByTestId('variant-1-price')).toBeVisible()
fireEvent.press(screen.getByTestId('variant-1-remove'))
expect(screen.queryByTestId('variant-1-price')).toBeNull()
expect(view.queryByTestId('variant-0-attr-0-remove')).toBeNull()
expect(view.getByTestId('variant-0-attr-1-remove')).toBeTruthy()
fireEvent.press(view.getByTestId('variant-0-add-attr'))
fireEvent.changeText(view.getByTestId('variant-0-attr-2-name'), 'quantity')
fireEvent.changeText(view.getByTestId('variant-0-attr-2-value'), 'extra')
expect(view.getByTestId('variant-0-attr-0-remove')).toBeTruthy()
})
it('submits a valid form with the seeded values', async () => {
const onSubmit = jest.fn()
const api = setupApiMocks({
procedures: { 'common.getStoresSummary': { stores } },
})
renderWithProviders(
<ProductForm mode="create" initialValues={validValues()} onSubmit={onSubmit} isLoading={false} />
it('APFORM-09: duplicate quantity features fail validation', async () => {
const { view } = renderForm()
fireEvent.press(view.getByTestId('variant-0-add-attr'))
fireEvent.changeText(view.getByTestId('variant-0-attr-1-name'), 'quantity')
fireEvent.changeText(view.getByTestId('variant-0-attr-1-value'), '2kg')
await submit(view)
expect(alertSpy).toHaveBeenCalledWith(
'Check your form',
'Each SKU can have only one quantity feature'
)
})
fireEvent.press(screen.getByTestId('create-product-button'))
it('APFORM-10: price must be a positive number', async () => {
const { view } = renderForm({ variants: [variant({ price: undefined })] })
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
const normalized = onSubmit.mock.calls[0][0]
expect(normalized.name).toBe('Paneer')
expect(normalized.variants[0].price).toBe(200)
expect(normalized.variants[0].features).toEqual([
{ featureName: 'quantity', featureValue: '1 kg' },
await submit(view)
expect(alertSpy).toHaveBeenCalledWith('Check your form', 'Price is required')
})
it('APFORM-11: negative market/flash prices fail validation', async () => {
const { view } = renderForm({ variants: [variant({ marketPrice: -5 })] })
await submit(view)
expect(alertSpy).toHaveBeenCalledWith('Check your form', 'Market price cannot be negative')
alertSpy.mockClear()
fireEvent.changeText(view.getByTestId('variant-0-market-price'), '0')
fireEvent.press(view.getByTestId('variant-0-flash'))
fireEvent.changeText(view.getByTestId('variant-0-flash-price'), '-1')
await submit(view)
expect(alertSpy).toHaveBeenCalledWith('Check your form', 'Flash price cannot be negative')
})
it('APFORM-12: turning flash off clears the flash price', async () => {
const { view, onSubmit } = renderForm({
variants: [variant({ isFlashAvailable: true, flashPrice: 50 })],
})
fireEvent.press(view.getByTestId('variant-0-flash'))
expect(view.queryByTestId('variant-0-flash-price')).toBeNull()
await submit(view)
const [values] = onSubmit.mock.calls[0]
expect(values.variants[0].isFlashAvailable).toBe(false)
expect(values.variants[0].flashPrice).toBeNull()
})
it('APFORM-13: the combo product type reveals the included-items section', () => {
const { view } = renderForm()
fireEvent.press(view.getByTestId('product-type-dropdown'))
fireEvent.press(view.getByTestId('product-type-dropdown-option-combo'))
expect(view.getByText('Included Items')).toBeTruthy()
})
it('APFORM-14: a duplicate combo SKU is rejected and not set', async () => {
const { view } = renderForm()
await flush()
fireEvent.press(view.getByTestId('product-type-dropdown'))
fireEvent.press(view.getByTestId('product-type-dropdown-option-combo'))
fireEvent.press(view.getByTestId('variant-0-combo-add'))
fireEvent.press(view.getByTestId('variant-0-combo-add'))
fireEvent.press(view.getByTestId('variant-0-combo-0-dropdown'))
fireEvent.press(view.getByTestId('variant-0-combo-0-dropdown-option-11'))
// The second dropdown disables the already-selected SKU, so drive the
// defensive duplicate branch through the dropdown callback.
const dropdowns = view.UNSAFE_getAllByType(BottomDropdown)
const comboDropdown = dropdowns[dropdowns.length - 1]
await act(async () => {
comboDropdown.props.onValueChange(11)
})
expect(alertSpy).toHaveBeenCalledWith('Duplicate', 'This product is already in the combo')
expect(comboDropdown.props.value).toBe(0)
})
it('APFORM-15: a combo item can be removed', () => {
const { view } = renderForm()
fireEvent.press(view.getByTestId('product-type-dropdown'))
fireEvent.press(view.getByTestId('product-type-dropdown-option-combo'))
fireEvent.press(view.getByTestId('variant-0-combo-add'))
expect(view.getByTestId('variant-0-combo-0-dropdown')).toBeTruthy()
fireEvent.press(view.getByTestId('variant-0-combo-0-remove'))
expect(view.queryByTestId('variant-0-combo-0-dropdown')).toBeNull()
})
it('APFORM-16: the store dropdown labels regional and global stores', async () => {
const { view } = renderForm()
await flush()
fireEvent.press(view.getByTestId('product-store-dropdown'))
expect(view.getAllByText('The Freshyo Meat House').length).toBeGreaterThanOrEqual(1)
expect(view.getByText('Freshyo Central (global)')).toBeTruthy()
})
it('APFORM-17: a create form with no store prefers the regional store', async () => {
const { view } = renderForm({ storeId: 0 })
await flush()
expect(view.getByText('The Freshyo Meat House')).toBeTruthy()
expect(view.queryByText('Select store')).toBeNull()
})
it('APFORM-18: combo products with items hide the combo-only toggle', () => {
const { view } = renderForm()
expect(view.getByTestId('variant-0-combo-only')).toBeTruthy()
fireEvent.press(view.getByTestId('product-type-dropdown'))
fireEvent.press(view.getByTestId('product-type-dropdown-option-combo'))
fireEvent.press(view.getByTestId('variant-0-combo-add'))
expect(view.queryByTestId('variant-0-combo-only')).toBeNull()
})
it('APFORM-19: submitting invalid values alerts the first error message', async () => {
const { view } = renderForm({ name: '', variants: [variant({ price: undefined })] })
await submit(view)
expect(alertSpy).toHaveBeenCalledWith('Check your form', 'Price is required')
})
it('APFORM-20: a valid submit sends normalized values, images and deleted keys', async () => {
const { view, onSubmit } = renderForm({
name: ' Chicken ',
variants: [
variant({
price: '100',
marketPrice: '250',
isFlashAvailable: true,
flashPrice: '199',
features: [{ featureName: 'quantity', featureValue: '1kg' }],
}),
],
})
await submit(view)
expect(onSubmit).toHaveBeenCalledTimes(1)
const [values, images, deletedKeys] = onSubmit.mock.calls[0]
expect(values.name).toBe(' Chicken ')
expect(values.storeId).toBe(1)
expect(values.variants[0]).toEqual(
expect.objectContaining({
price: 100,
marketPrice: 250,
flashPrice: 199,
isFlashAvailable: true,
})
)
expect(values.variants[0].features).toEqual([
{ featureName: 'quantity', featureValue: '1kg' },
])
// create mode passes an empty deleted-keys list.
expect(onSubmit.mock.calls[0][2]).toEqual([])
expect(api.fetchMock).toHaveBeenCalled()
expect(images).toEqual([[]])
expect(deletedKeys).toEqual([])
})
it('alerts instead of submitting when a price is invalid', async () => {
const onSubmit = jest.fn()
setupApiMocks({ procedures: { 'common.getStoresSummary': { stores } } })
renderWithProviders(
<ProductForm
mode="create"
initialValues={validValues({
variants: [
{
id: undefined,
name: '',
price: undefined,
marketPrice: null,
isFlashAvailable: false,
flashPrice: null,
isOffer: false,
isComboOnly: false,
isDeleted: false,
isSuspended: false,
features: [{ featureName: 'quantity', featureValue: '1 kg' }],
comboItems: [],
},
],
})}
onSubmit={onSubmit}
isLoading={false}
/>
)
it('APFORM-21: the per-variant image uploader adds and removes images', async () => {
;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValueOnce({
canceled: false,
assets: [{ uri: 'file:///picked.jpg', mimeType: 'image/jpeg', fileName: 'picked.jpg' }],
})
const { view } = renderForm()
fireEvent.press(screen.getByTestId('create-product-button'))
fireEvent.press(view.getByTestId('variant-0-image-add'))
await flush()
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Check your form', expect.any(String))
)
expect(onSubmit).not.toHaveBeenCalled()
expect(view.getByTestId('variant-0-image-add-remove')).toBeTruthy()
fireEvent.press(view.getByTestId('variant-0-image-add-remove'))
expect(view.queryByTestId('variant-0-image-add-remove')).toBeNull()
})
it('APFORM-22: many features render without crashing', () => {
const { view } = renderForm({
variants: [
variant({
features: Array.from({ length: 8 }, (_, index) => ({
featureName: `feature-${index}`,
featureValue: `value-${index}`,
})),
}),
],
})
// quantity was prepended, so the eight custom features occupy 1..8.
expect(view.getByTestId('variant-0-attr-8-name').props.value).toBe('feature-7')
})
})

View file

@ -1,243 +1,150 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* ProductGroupForm (components/ProductGroupForm.tsx) — create/edit titles,
* name validation, createGroup/updateGroup payloads, product selection and the
* cancel/close handlers.
* Shared ProductGroupForm (`tests/components/product-group-form.test.tsx`).
*
* NOTE: the embedded ProductsSelector emits SKU ids, but createGroup /
* updateGroup expect productInfo ids (db_helper_postgres product.ts:315/345).
* The payloads below are asserted as observed and reported as an app bug.
* Section 11 of the catalogue covers the list/create/edit screens; this file
* exercises the shared form they all mount.
*/
import React from 'react'
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import { Alert } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native'
import { BottomDropdown } from 'common-ui'
import ProductGroupForm, { ProductGroup } from '@/components/ProductGroupForm'
import { resetStorage, setupApiMocks } from '../mocks/api'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { createQueryClient, renderWithProviders } from '../helpers/render'
setProcedure,
lastMutationInput,
procedureMutationCalls,
procedureInvalidations,
} from '../mocks/trpc-client'
import { GROUP_1 } from '../fixtures'
const skusResponse = {
skus: [
{ id: 1, productId: 10, productName: 'Chicken', label: 'Chicken 1kg' },
{ id: 2, productId: 11, productName: 'Mutton', label: 'Mutton 1kg' },
],
type View = ReturnType<typeof renderForm>['view']
function renderForm(group?: ProductGroup | null) {
const onClose = jest.fn()
const onSuccess = jest.fn()
const view = renderWithProviders(
<ProductGroupForm group={group} onClose={onClose} onSuccess={onSuccess} />,
{ auth: false }
)
return { view, onClose, onSuccess }
}
const procedures = {
'common.product.getAllProductsSummary': { products: [] },
'common.product.getAllSkusSummary': skusResponse,
'admin.product.createGroup': {
group: { id: 1, groupName: 'Meat', description: null, createdAt: '2024-01-01' },
message: 'Group created successfully',
},
'admin.product.updateGroup': {
group: { id: 5, groupName: 'Meat', description: 'Bundle', createdAt: '2024-01-01' },
message: 'Group updated successfully',
},
function nameInput(view: View) {
return view.getByPlaceholderText('Enter group name')
}
const existingGroup: ProductGroup = {
id: 5,
groupName: 'Beef Box',
description: 'Bundle',
createdAt: '2024-01-01T00:00:00.000Z',
products: [{ id: 10 }, { id: 11 }],
productCount: 2,
async function submit(view: View) {
fireEvent.press(view.getByText('Save'))
await flush(3)
}
describe('ProductGroupForm', () => {
beforeEach(async () => {
await resetStorage()
setupApiMocks({ procedures })
jest.spyOn(console, 'error').mockImplementation(() => {})
describe('ProductGroupForm (AGRPF-01..08)', () => {
let alertSpy: jest.SpyInstance
beforeEach(() => {
resetAllMocks()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
})
it('renders in create mode', () => {
renderWithProviders(
<ProductGroupForm onClose={jest.fn()} onSuccess={jest.fn()} />
)
afterEach(() => alertSpy?.mockRestore())
expect(screen.getByText('Create Product Group')).toBeVisible()
expect(screen.getByText('Group Name *')).toBeVisible()
expect(screen.getByText('Description')).toBeVisible()
expect(screen.getByText('Save')).toBeVisible()
it('AGRPF-01: renders the create form', () => {
const { view } = renderForm()
expect(view.getByText('Create Product Group')).toBeTruthy()
expect(nameInput(view).props.value).toBe('')
expect(view.getByPlaceholderText('Enter description (optional)')).toBeTruthy()
expect(view.getByText('Select products')).toBeTruthy()
expect(view.getByText('Cancel')).toBeTruthy()
})
it('renders in edit mode with the group seeded', () => {
renderWithProviders(
<ProductGroupForm
group={existingGroup}
onClose={jest.fn()}
onSuccess={jest.fn()}
/>
)
it('AGRPF-02: an empty group name blocks the create', async () => {
const { view } = renderForm()
expect(screen.getByText('Edit Product Group')).toBeVisible()
expect(screen.getByDisplayValue('Beef Box')).toBeVisible()
expect(screen.getByDisplayValue('Bundle')).toBeVisible()
await submit(view)
expect(view.getByText('Group name is required')).toBeTruthy()
expect(procedureMutationCalls('admin.product.createGroup')).toHaveLength(0)
})
it('blocks submission when the group name is empty', async () => {
const { fetchMock } = setupApiMocks({ procedures })
renderWithProviders(
<ProductGroupForm onClose={jest.fn()} onSuccess={jest.fn()} />
)
it('AGRPF-03: creates a group and invalidates the list', async () => {
const { view, onSuccess } = renderForm()
fireEvent.changeText(nameInput(view), 'Breakfast')
fireEvent.changeText(view.getByPlaceholderText('Enter description (optional)'), 'Morning')
fireEvent.press(screen.getByText('Save'))
await submit(view)
expect(await screen.findByText('Group name is required')).toBeVisible()
expect(procCount(fetchMock, 'admin.product.createGroup')).toBe(0)
})
it('creates a group with the entered values', async () => {
const { fetchMock } = setupApiMocks({ procedures })
const onSuccess = jest.fn()
renderWithProviders(
<ProductGroupForm onClose={jest.fn()} onSuccess={onSuccess} />
)
fireEvent.changeText(screen.getByPlaceholderText('Enter group name'), 'Meat')
fireEvent.changeText(
screen.getByPlaceholderText('Enter description (optional)'),
'Protein'
)
fireEvent.press(screen.getByText('Save'))
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.product.createGroup'))
expect(lastProcedureInput(fetchMock, 'admin.product.createGroup')).toEqual({
group_name: 'Meat',
description: 'Protein',
expect(lastMutationInput('admin.product.createGroup')).toEqual({
group_name: 'Breakfast',
description: 'Morning',
product_ids: [],
})
await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1))
expect(procedureInvalidations('admin.product.getGroups').length).toBeGreaterThan(0)
expect(onSuccess).toHaveBeenCalled()
})
it('creates a group carrying the selected SKU ids as product_ids', async () => {
const { fetchMock } = setupApiMocks({ procedures })
renderWithProviders(
<ProductGroupForm onClose={jest.fn()} onSuccess={jest.fn()} />
)
it('AGRPF-04: renders the edit heading and prefilled values', async () => {
const { view } = renderForm(GROUP_1 as ProductGroup)
await flush()
await waitFor(() =>
expectProcedureCalled(fetchMock, 'common.product.getAllSkusSummary')
expect(view.getByText('Edit Product Group')).toBeTruthy()
expect(nameInput(view).props.value).toBe('Breakfast')
expect(view.getByPlaceholderText('Enter description (optional)').props.value).toBe(
'Morning items'
)
fireEvent.changeText(screen.getByPlaceholderText('Enter group name'), 'Meat')
fireEvent.press(screen.getByText('Select products'))
fireEvent.press(await screen.findByLabelText('undefined-option-1'))
fireEvent.press(screen.getByText('Save'))
expect(view.getByText('Chicken Breast - 500g, Cucumber - 500g')).toBeTruthy()
})
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.product.createGroup'))
// Observed bug: product_ids contains the selected SKU id (1), not product id 10.
expect(lastProcedureInput(fetchMock, 'admin.product.createGroup')).toMatchObject({
group_name: 'Meat',
product_ids: [1],
it('AGRPF-05: product selection writes product_ids', async () => {
const { view } = renderForm()
fireEvent.changeText(nameInput(view), 'Combo')
const dropdown = view.UNSAFE_getAllByType(BottomDropdown)[0]
act(() => {
dropdown.props.onValueChange(['11', '13'])
})
await submit(view)
expect(lastMutationInput('admin.product.createGroup').product_ids).toEqual([11, 13])
})
it('updates the group with its seeded product ids', async () => {
const { fetchMock } = setupApiMocks({ procedures })
const onSuccess = jest.fn()
renderWithProviders(
<ProductGroupForm
group={existingGroup}
onClose={jest.fn()}
onSuccess={onSuccess}
/>
)
it('AGRPF-06: editing updates the group by id', async () => {
const { view, onSuccess } = renderForm(GROUP_1 as ProductGroup)
fireEvent.changeText(nameInput(view), 'Breakfast Plus')
fireEvent.changeText(screen.getByDisplayValue('Beef Box'), 'Beef Combo')
fireEvent.press(screen.getByText('Save'))
await submit(view)
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.product.updateGroup'))
expect(lastProcedureInput(fetchMock, 'admin.product.updateGroup')).toEqual({
id: 5,
group_name: 'Beef Combo',
description: 'Bundle',
product_ids: [10, 11],
expect(lastMutationInput('admin.product.updateGroup')).toEqual({
id: 1,
group_name: 'Breakfast Plus',
description: 'Morning items',
product_ids: [11, 13],
})
await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1))
expect(onSuccess).toHaveBeenCalled()
})
it('invalidates the getGroups query with the tRPC array key on create and update', async () => {
// Spy on an injected client: utils.admin.product.getGroups.invalidate() calls
// queryClient.invalidateQueries({ queryKey }), and getGroups is not mounted by
// this form, so nothing hits fetch — the invalidation itself is the observable.
const client = createQueryClient()
const invalidateSpy = jest.spyOn(client, 'invalidateQueries') // keeps calling through
it('AGRPF-07: a failed save shows the server message', async () => {
setProcedure('admin.product.createGroup', {
mode: 'error',
error: new Error('Duplicate group'),
})
const { view } = renderForm()
fireEvent.changeText(nameInput(view), 'Breakfast')
// tRPC keys are [pathArray, ...]. The old bug passed a dotted string
// ('admin.product.getGroups'); only the array form is correct.
const pathOf = (call: unknown[]) => {
const key = (call[0] as { queryKey?: unknown[] } | undefined)?.queryKey
return Array.isArray(key) ? key[0] : null
}
await submit(view)
// Create path — same props/flow as 'creates a group with the entered values'.
const created = renderWithProviders(
<ProductGroupForm onClose={jest.fn()} onSuccess={jest.fn()} />,
{ queryClient: client }
)
fireEvent.changeText(screen.getByPlaceholderText('Enter group name'), 'Meat')
fireEvent.press(screen.getByText('Save'))
await waitFor(() => expect(invalidateSpy).toHaveBeenCalled())
expect(invalidateSpy.mock.calls.map(pathOf)).toContainEqual([
'admin',
'product',
'getGroups',
])
created.unmount()
// Update path — same props/flow as 'updates the group with its seeded product ids'.
const callsAfterCreate = invalidateSpy.mock.calls.length
renderWithProviders(
<ProductGroupForm
group={existingGroup}
onClose={jest.fn()}
onSuccess={jest.fn()}
/>,
{ queryClient: client }
)
fireEvent.press(screen.getByText('Save'))
await waitFor(() =>
expect(invalidateSpy.mock.calls.length).toBeGreaterThan(callsAfterCreate)
)
expect(invalidateSpy.mock.calls.slice(callsAfterCreate).map(pathOf)).toContainEqual([
'admin',
'product',
'getGroups',
])
expect(alertSpy).toHaveBeenCalledWith('Error', 'Duplicate group')
})
it('calls onClose from the Cancel button', () => {
const onClose = jest.fn()
renderWithProviders(
<ProductGroupForm onClose={onClose} onSuccess={jest.fn()} />
)
it('AGRPF-08: Cancel calls onClose', () => {
const { view, onClose } = renderForm()
fireEvent.press(screen.getByText('Cancel'))
fireEvent.press(view.getByText('Cancel'))
expect(onClose).toHaveBeenCalledTimes(1)
expect(onClose).toHaveBeenCalled()
})
it('calls onClose from the header close icon', () => {
const onClose = jest.fn()
renderWithProviders(
<ProductGroupForm onClose={onClose} onSuccess={jest.fn()} />
)
const closeIcon = screen
.UNSAFE_getAllByType(MaterialIcons)
.find((i) => i.props.name === 'close') as Parameters<typeof fireEvent.press>[0]
fireEvent.press(closeIcon)
expect(onClose).toHaveBeenCalledTimes(1)
})
})
})

View file

@ -1,46 +1,52 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* ProductListDialog (components/ProductListDialog.tsx) — a read-only bottom
* dialog listing the products passed in as props.
* Catalogue section 17.1 — ProductListDialog
* (`tests/components/product-list-dialog.test.tsx`).
*/
import React from 'react'
import { screen } from '@testing-library/react-native'
import { TouchableOpacity } from 'react-native'
import { fireEvent, render } from '@testing-library/react-native'
import { ProductListDialog } from '@/components/ProductListDialog'
import { renderWithProviders } from '../helpers/render'
import { resetAllMocks } from '../helpers/reset'
const products = [
{ id: 1, name: 'Chicken' },
{ id: 2, name: 'Mutton' },
{ id: 3, name: 'Fish' },
const PRODUCTS = [
{ id: 11, name: 'Chicken Breast - 500g' },
{ id: 13, name: 'Cucumber - 500g' },
]
describe('ProductListDialog', () => {
it('renders the product count and each product when open', () => {
renderWithProviders(
<ProductListDialog open onClose={jest.fn()} products={products} />
describe('ProductListDialog (APLD-01..03)', () => {
beforeEach(() => resetAllMocks())
it('APLD-01: an open dialog lists every product with its count', () => {
const onClose = jest.fn()
const view = render(
<ProductListDialog open onClose={onClose} products={PRODUCTS} />
)
expect(screen.getByText('Products (3)')).toBeVisible()
expect(screen.getByText('Chicken')).toBeVisible()
expect(screen.getByText('Mutton')).toBeVisible()
expect(screen.getByText('Fish')).toBeVisible()
expect(view.getByText('Products (2)')).toBeTruthy()
expect(view.getByText('Chicken Breast - 500g')).toBeTruthy()
expect(view.getByText('Cucumber - 500g')).toBeTruthy()
})
it('shows a count of zero for an empty list', () => {
renderWithProviders(
it('APLD-02: pressing the backdrop closes the dialog', () => {
const onClose = jest.fn()
const view = render(
<ProductListDialog open onClose={onClose} products={PRODUCTS} />
)
// BottomDialog's dismissible backdrop is the first touchable in the modal.
fireEvent.press(view.UNSAFE_getAllByType(TouchableOpacity)[0])
expect(onClose).toHaveBeenCalledTimes(1)
})
it('APLD-03: no products shows the empty count and copy', () => {
const view = render(
<ProductListDialog open onClose={jest.fn()} products={[]} />
)
expect(screen.getByText('Products (0)')).toBeVisible()
})
it('hides its content while closed', () => {
renderWithProviders(
<ProductListDialog open={false} onClose={jest.fn()} products={products} />
)
// A closed Modal does not mount its children in the tree.
expect(screen.queryByText('Products (3)')).toBeNull()
expect(view.getByText('Products (0)')).toBeTruthy()
expect(view.queryByText('Chicken Breast - 500g')).toBeNull()
})
})

View file

@ -1,173 +0,0 @@
/**
* ProductsSelector (components/ProductsSelector.tsx) — a dropdown-backed SKU
* picker with optional product-group selection.
*/
import React from 'react'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import ProductsSelector from '@/components/ProductsSelector'
import { resetStorage, setupApiMocks } from '../mocks/api'
import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures'
import { renderWithProviders } from '../helpers/render'
const skus = [
{ id: 1, productId: 10, productName: 'Chicken', label: 'Chicken 1kg' },
{ id: 2, productId: 11, productName: 'Mutton', label: 'Mutton 1kg' },
]
const skusResponse = { skus }
describe('ProductsSelector', () => {
beforeEach(async () => {
await resetStorage()
})
it('loads SKUs from getAllSkusSummary', async () => {
const api = setupApiMocks({
procedures: { 'common.product.getAllSkusSummary': skusResponse },
})
renderWithProviders(<ProductsSelector value={[]} onChange={jest.fn()} testID="sku-select" />)
await waitFor(() =>
expectProcedureCalled(api.fetchMock, 'common.product.getAllSkusSummary')
)
expect(screen.getByTestId('sku-select')).toBeVisible()
})
it('selects a product and reports the numeric id', async () => {
const api = setupApiMocks({
procedures: { 'common.product.getAllSkusSummary': skusResponse },
})
const onChange = jest.fn()
renderWithProviders(
<ProductsSelector value={[]} onChange={onChange} multiple={false} testID="sku-select" />
)
await waitFor(() =>
expectProcedureCalled(api.fetchMock, 'common.product.getAllSkusSummary')
)
await waitFor(() => expect(screen.getByTestId('sku-select')).toBeVisible())
fireEvent.press(screen.getByTestId('sku-select'))
fireEvent.press(await screen.findByTestId('sku-select-option-1'))
expect(onChange).toHaveBeenCalledWith(1)
})
it('toggles multiple selection', async () => {
const api = setupApiMocks({
procedures: { 'common.product.getAllSkusSummary': skusResponse },
})
const onChange = jest.fn()
renderWithProviders(
<ProductsSelector value={[1]} onChange={onChange} multiple testID="sku-select" />
)
await waitFor(() =>
expectProcedureCalled(api.fetchMock, 'common.product.getAllSkusSummary')
)
fireEvent.press(screen.getByTestId('sku-select'))
fireEvent.press(await screen.findByTestId('sku-select-option-2'))
expect(onChange).toHaveBeenCalledWith([1, 2])
})
it('adds a group\'s SKUs when a group is selected', async () => {
const api = setupApiMocks({
procedures: { 'common.product.getAllSkusSummary': skusResponse },
})
const onChange = jest.fn()
const onGroupChange = jest.fn()
renderWithProviders(
<ProductsSelector
value={[]}
onChange={onChange}
groups={[{ id: 100, groupName: 'Meat', products: [{ id: 10 }] }]}
selectedGroupIds={[]}
onGroupChange={onGroupChange}
testID="sku-select"
/>
)
await waitFor(() =>
expectProcedureCalled(api.fetchMock, 'common.product.getAllSkusSummary')
)
await waitFor(() => expect(screen.getByTestId('product-groups-dropdown')).toBeVisible())
// Opening the SKU dropdown proves allSkus has loaded into state.
fireEvent.press(screen.getByTestId('sku-select'))
await screen.findByTestId('sku-select-option-1')
fireEvent.press(screen.getByTestId('product-groups-dropdown'))
fireEvent.press(await screen.findByTestId('product-groups-dropdown-option-100'))
expect(onGroupChange).toHaveBeenCalledWith([100])
expect(onChange).toHaveBeenCalledWith([1])
})
it('labels a SKU that came from a selected group', async () => {
const api = setupApiMocks({
procedures: { 'common.product.getAllSkusSummary': skusResponse },
})
renderWithProviders(
<ProductsSelector
value={[]}
onChange={jest.fn()}
groups={[{ id: 100, groupName: 'Meat', products: [{ id: 10 }] }]}
selectedGroupIds={[100]}
showGroups
testID="sku-select"
/>
)
await waitFor(() =>
expectProcedureCalled(api.fetchMock, 'common.product.getAllSkusSummary')
)
await waitFor(() => expect(screen.getByTestId('sku-select')).toBeVisible())
fireEvent.press(screen.getByTestId('sku-select'))
expect(await screen.findByTestId('sku-select-option-1')).toBeVisible()
// The "(from group)" suffix marks the grouped SKU.
expect(screen.getByText(/from group/)).toBeVisible()
})
it('applies a custom labelFormat', async () => {
const api = setupApiMocks({
procedures: { 'common.product.getAllSkusSummary': skusResponse },
})
renderWithProviders(
<ProductsSelector
value={[]}
onChange={jest.fn()}
labelFormat={(sku) => `#${sku.id} ${sku.label}`}
showGroups={false}
testID="sku-select"
/>
)
await waitFor(() =>
expectProcedureCalled(api.fetchMock, 'common.product.getAllSkusSummary')
)
await waitFor(() => expect(screen.getByTestId('sku-select')).toBeVisible())
fireEvent.press(screen.getByTestId('sku-select'))
expect(await screen.findByText(/#1 Chicken 1kg/)).toBeVisible()
})
it('passes the search query to filtering', async () => {
const api = setupApiMocks({
procedures: { 'common.product.getAllSkusSummary': skusResponse },
})
renderWithProviders(<ProductsSelector value={[]} onChange={jest.fn()} testID="sku-select" />)
await waitFor(() =>
expectProcedureCalled(api.fetchMock, 'common.product.getAllSkusSummary')
)
await waitFor(() => expect(screen.getByTestId('sku-select')).toBeVisible())
fireEvent.press(screen.getByTestId('sku-select'))
act(() => {
fireEvent.changeText(screen.getByTestId('sku-select-search'), 'mutton')
})
await waitFor(() => expect(screen.getByTestId('sku-select-option-2')).toBeVisible())
expect(screen.queryByTestId('sku-select-option-1')).toBeNull()
})
})

View file

@ -1,214 +1,314 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* SlotForm component (components/SlotForm.tsx) — create/update mutations,
* validation and vendor-snippet handling.
* Catalogue section 7.3 — SlotForm and VendorSnippetForm
* (`tests/components/slot-form.test.tsx`).
*/
import React from 'react'
import { Alert } from 'react-native'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import { fireEvent } from '@testing-library/react-native'
import SlotForm from '@/components/SlotForm'
import { setupApiMocks, resetStorage } from '../mocks/api'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { expectProcedureCalled, lastProcedureInput, procCount } from '../mocks/procedures'
import { searchParamsMock } from '../mocks/router'
import { renderWithProviders } from '../helpers/render'
import VendorSnippetForm from '@/components/VendorSnippetForm'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { setProcedure, lastMutationInput, procedureMutationCalls } from '../mocks/trpc-client'
const DELIVERY = new Date('2026-10-01T10:00:00.000Z')
const FREEZE = new Date('2026-10-01T06:00:00.000Z')
const HOUR = 60 * 60 * 1000
const procedures = {
'admin.product.getGroups': { groups: [] },
'common.product.getAllSkusSummary': { skus: [] },
'admin.slots.createSlot': {
slot: { id: 10 },
createdSnippets: [],
message: 'Slot created successfully',
},
'admin.slots.updateSlot': {
slot: { id: 7 },
createdSnippets: [],
message: 'Slot updated successfully',
},
type View = ReturnType<typeof renderWithProviders>
function renderSlotForm(props: Partial<React.ComponentProps<typeof SlotForm>> = {}) {
return renderWithProviders(<SlotForm {...props} />, { auth: 'in' })
}
describe('SlotForm', () => {
beforeEach(async () => {
resetStaffAuthMock()
await resetStorage()
searchParamsMock.current = {}
setupApiMocks({ procedures })
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
function chooseDate(view: View, field: 'delivery' | 'freeze', date: Date) {
fireEvent.press(view.getByTestId(`${field}-date-picker`))
fireEvent(view.getByTestId('dateTimePicker'), 'change', { type: 'set' }, date)
}
function setDates(view: View, deliveryOffset = 3, freezeOffset = 2) {
const delivery = new Date(Date.now() + deliveryOffset * HOUR)
const freeze = new Date(Date.now() + freezeOffset * HOUR)
chooseDate(view, 'delivery', delivery)
chooseDate(view, 'freeze', freeze)
return { delivery, freeze }
}
function selectSku(view: View, testId: string, skuId: number) {
fireEvent.press(view.getByTestId(testId))
fireEvent.press(view.getByTestId(`${testId}-option-${skuId}`))
fireEvent.press(view.getByTestId(`${testId}-done`))
}
describe('SlotForm (ASLOTF-01..10)', () => {
let alertSpy: jest.SpyInstance
beforeEach(() => {
resetAllMocks()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
})
it('renders the create form', () => {
renderWithProviders(
<SlotForm initialDeliveryTime={DELIVERY} initialFreezeTime={FREEZE} />
)
afterEach(() => alertSpy?.mockRestore())
expect(screen.getByText('Create New Slot')).toBeVisible()
expect(screen.getByText('Create Slot')).toBeVisible()
expect(screen.getByText('Vendor Snippets')).toBeVisible()
expect(screen.getByText('Add Vendor Snippet')).toBeVisible()
it('ASLOTF-01: renders the create fields', () => {
const view = renderSlotForm()
expect(view.getByText('Create New Slot')).toBeTruthy()
expect(view.getByText('Delivery Date & Time')).toBeTruthy()
expect(view.getByText('Freeze Date & Time')).toBeTruthy()
expect(view.getByText('Vendor Snippets')).toBeTruthy()
expect(view.getByText('Create Slot')).toBeTruthy()
})
it('blocks submit when a time is missing', async () => {
const { fetchMock } = setupApiMocks({ procedures })
it('ASLOTF-02: missing delivery/freeze times are rejected', async () => {
const view = renderSlotForm()
renderWithProviders(<SlotForm />)
fireEvent.press(screen.getByTestId('create-slot-button'))
fireEvent.press(view.getByTestId('create-slot-button'))
await flush()
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Error', 'Please fill all fields')
)
expect(procCount(fetchMock, 'admin.slots.createSlot')).toBe(0)
expect(alertSpy).toHaveBeenCalledWith('Error', 'Please fill all fields')
expect(procedureMutationCalls('admin.slots.createSlot')).toHaveLength(0)
})
it('blocks submit when freeze time is after delivery time', async () => {
const { fetchMock } = setupApiMocks({ procedures })
it('ASLOTF-03: freeze after delivery is rejected', async () => {
const view = renderSlotForm()
renderWithProviders(
<SlotForm
initialDeliveryTime={FREEZE}
initialFreezeTime={DELIVERY}
/>
)
fireEvent.press(screen.getByTestId('create-slot-button'))
// Freeze is later than delivery.
setDates(view, 1, 4)
fireEvent.press(view.getByTestId('create-slot-button'))
await flush()
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Error',
'Freeze time must be before or equal to delivery time'
)
expect(alertSpy).toHaveBeenCalledWith(
'Error',
'Freeze time must be before or equal to delivery time'
)
expect(procCount(fetchMock, 'admin.slots.createSlot')).toBe(0)
expect(procedureMutationCalls('admin.slots.createSlot')).toHaveLength(0)
})
it('creates a slot with the mapped payload and calls onSlotAdded', async () => {
const { fetchMock } = setupApiMocks({ procedures })
const onSlotAdded = jest.fn()
it('ASLOTF-04: selecting products sends the SKU ids', async () => {
const view = renderSlotForm()
await flush()
renderWithProviders(
<SlotForm
initialDeliveryTime={DELIVERY}
initialFreezeTime={FREEZE}
initialProductIds={[11, 12]}
initialGroupIds={[3]}
onSlotAdded={onSlotAdded}
/>
selectSku(view, 'slot-products-selector', 13)
const { delivery, freeze } = setDates(view)
fireEvent.press(view.getByTestId('create-slot-button'))
await flush(2)
expect(lastMutationInput('admin.slots.createSlot')).toEqual(
expect.objectContaining({
deliveryTime: delivery.toISOString(),
freezeTime: freeze.toISOString(),
skuIds: [13],
})
)
fireEvent.press(screen.getByTestId('create-slot-button'))
await waitFor(() =>
expectProcedureCalled(fetchMock, 'admin.slots.createSlot')
)
expect(lastProcedureInput(fetchMock, 'admin.slots.createSlot')).toEqual({
deliveryTime: '2026-10-01T10:00:00.000Z',
freezeTime: '2026-10-01T06:00:00.000Z',
isActive: true,
groupIds: [3],
skuIds: [11, 12],
vendorSnippets: [],
})
await waitFor(() => expect(onSlotAdded).toHaveBeenCalled())
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Slot created successfully!')
})
it('includes an added vendor snippet in the create payload', async () => {
const { fetchMock } = setupApiMocks({ procedures })
it('ASLOTF-05: adding a vendor snippet includes name, SKUs and no expiry', async () => {
const view = renderSlotForm()
await flush()
renderWithProviders(
<SlotForm initialDeliveryTime={DELIVERY} initialFreezeTime={FREEZE} />
)
selectSku(view, 'slot-products-selector', 13)
fireEvent.press(view.getByText('Add Vendor Snippet'))
fireEvent.changeText(view.getByPlaceholderText('Enter snippet name'), 'Snippet A')
selectSku(view, 'snippet-products-selector', 13)
setDates(view)
fireEvent.press(view.getByTestId('create-slot-button'))
await flush(2)
fireEvent.press(screen.getByText('Add Vendor Snippet'))
fireEvent.changeText(
screen.getByPlaceholderText('Enter snippet name'),
'Diwali Promo'
)
fireEvent.press(screen.getByTestId('create-slot-button'))
await waitFor(() =>
expectProcedureCalled(fetchMock, 'admin.slots.createSlot')
)
expect(
(lastProcedureInput(fetchMock, 'admin.slots.createSlot') as any).vendorSnippets
).toEqual([{ name: 'Diwali Promo', skuIds: [], validTill: '' }])
const input = lastMutationInput('admin.slots.createSlot')
expect(input.vendorSnippets).toEqual([
{ name: 'Snippet A', skuIds: [13], validTill: '' },
])
})
it('updates an existing slot in edit mode', async () => {
const { fetchMock } = setupApiMocks({ procedures })
const onSlotAdded = jest.fn()
it('ASLOTF-06: removing a vendor snippet drops it from the list', () => {
const view = renderSlotForm()
renderWithProviders(
<SlotForm
slotId={7}
initialDeliveryTime={DELIVERY}
initialFreezeTime={FREEZE}
initialProductIds={[11]}
onSlotAdded={onSlotAdded}
/>
)
fireEvent.press(view.getByText('Add Vendor Snippet'))
expect(view.getByText('Snippet Name *')).toBeTruthy()
expect(screen.getByText('Edit Slot')).toBeVisible()
fireEvent.press(screen.getByTestId('create-slot-button'))
await waitFor(() =>
expectProcedureCalled(fetchMock, 'admin.slots.updateSlot')
)
expectProcedureCalled(fetchMock, 'admin.slots.getSlotById')
expect(lastProcedureInput(fetchMock, 'admin.slots.updateSlot')).toEqual({
id: 7,
deliveryTime: '2026-10-01T10:00:00.000Z',
freezeTime: '2026-10-01T06:00:00.000Z',
isActive: true,
groupIds: [],
skuIds: [11],
vendorSnippets: [],
})
await waitFor(() => expect(onSlotAdded).toHaveBeenCalled())
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Slot updated successfully!')
fireEvent.press(view.getByText('Remove Snippet'))
expect(view.queryByText('Snippet Name *')).toBeNull()
})
it('refetches the mounted slot detail after a successful update in edit mode', async () => {
const { fetchMock } = setupApiMocks({ procedures })
it('ASLOTF-07: a snippet without SKUs is submitted as-is (no validation)', async () => {
const view = renderSlotForm()
renderWithProviders(
<SlotForm
slotId={7}
initialDeliveryTime={DELIVERY}
initialFreezeTime={FREEZE}
initialProductIds={[11]}
/>
fireEvent.press(view.getByText('Add Vendor Snippet'))
fireEvent.changeText(view.getByPlaceholderText('Enter snippet name'), 'Empty Snippet')
setDates(view)
fireEvent.press(view.getByTestId('create-slot-button'))
await flush(2)
const input = lastMutationInput('admin.slots.createSlot')
expect(input.vendorSnippets).toEqual([
{ name: 'Empty Snippet', skuIds: [], validTill: '' },
])
})
it('ASLOTF-08: group selection is sent as group ids', async () => {
const view = renderSlotForm()
await flush()
fireEvent.press(view.getByTestId('product-groups-dropdown'))
fireEvent.press(view.getByTestId('product-groups-dropdown-option-1'))
fireEvent.press(view.getByTestId('product-groups-dropdown-done'))
setDates(view)
fireEvent.press(view.getByTestId('create-slot-button'))
await flush(2)
expect(lastMutationInput('admin.slots.createSlot')).toEqual(
expect.objectContaining({ groupIds: [1] })
)
})
// Edit mode mounts `admin.slots.getSlotById` with enabled: true, so there is
// a live query under `admin.slots` for the invalidation to refetch.
await waitFor(() =>
expect(procCount(fetchMock, 'admin.slots.getSlotById')).toBeGreaterThan(0)
)
it('ASLOTF-09: create and edit titles/buttons', () => {
const create = renderSlotForm()
expect(create.getByText('Create New Slot')).toBeTruthy()
expect(create.getByText('Create Slot')).toBeTruthy()
create.unmount()
// Baseline captured immediately before the press: the tests share one
// module-singleton httpBatchLink client, so counts can leak across cases —
// assert a delta, never an absolute number.
const before = procCount(fetchMock, 'admin.slots.getSlotById')
const edit = renderSlotForm({ slotId: 1849 })
expect(edit.getByText('Edit Slot')).toBeTruthy()
expect(edit.getByText('Update Slot')).toBeTruthy()
})
fireEvent.press(screen.getByTestId('create-slot-button'))
it('ASLOTF-10: a pending submit shows "Creating..." and ignores further presses', async () => {
setProcedure('admin.slots.createSlot', { mode: 'pending' })
const view = renderSlotForm()
await waitFor(() =>
expectProcedureCalled(fetchMock, 'admin.slots.updateSlot')
)
setDates(view)
fireEvent.press(view.getByTestId('create-slot-button'))
await flush(2)
// `utils.admin.slots.invalidate()` (SlotForm.tsx update onSuccess) invalidates
// the whole `admin.slots` path, which refetches the mounted detail query.
await waitFor(() =>
expect(procCount(fetchMock, 'admin.slots.getSlotById')).toBeGreaterThan(
before
)
)
expect(view.getByText('Creating...')).toBeTruthy()
fireEvent.press(view.getByTestId('create-slot-button'))
await flush(2)
expect(procedureMutationCalls('admin.slots.createSlot')).toHaveLength(1)
})
})
describe('VendorSnippetForm (AVSF-01..08)', () => {
let alertSpy: jest.SpyInstance
let onClose: jest.Mock
let onSuccess: jest.Mock
beforeEach(() => {
resetAllMocks()
onClose = jest.fn()
onSuccess = jest.fn()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
})
afterEach(() => alertSpy?.mockRestore())
function renderSnippetForm(snippet?: any) {
return renderWithProviders(
<VendorSnippetForm snippet={snippet} onClose={onClose} onSuccess={onSuccess} />,
{ auth: 'in' }
)
}
it('AVSF-01: renders code, slot, products, expiry and permanent fields', () => {
const view = renderSnippetForm()
expect(view.getByText('Create Vendor Snippet')).toBeTruthy()
expect(view.getByTestId('snippet-code-input').props.value).toMatch(/^VS_/)
expect(view.getByText('Is Permanent?')).toBeTruthy()
expect(view.getByText('Delivery Slot')).toBeTruthy()
expect(view.getByText('Valid Till (Optional)')).toBeTruthy()
expect(view.getByTestId('snippet-form-products-selector')).toBeTruthy()
expect(view.getByText('Create Snippet')).toBeTruthy()
})
it('AVSF-02: an empty code is rejected', async () => {
const view = renderSnippetForm()
fireEvent.changeText(view.getByTestId('snippet-code-input'), '')
fireEvent.press(view.getByTestId('snippet-submit-button'))
await flush(2)
expect(view.getByText('Snippet code is required')).toBeTruthy()
expect(procedureMutationCalls('admin.vendorSnippets.create')).toHaveLength(0)
})
it('AVSF-03: submitting without products is rejected', async () => {
const view = renderSnippetForm()
fireEvent.changeText(view.getByTestId('snippet-code-input'), 'TEST_1')
fireEvent.press(view.getByText('Is Permanent?'))
fireEvent.press(view.getByTestId('snippet-submit-button'))
await flush(2)
expect(view.getByText('At least one product must be selected')).toBeTruthy()
expect(procedureMutationCalls('admin.vendorSnippets.create')).toHaveLength(0)
})
it('AVSF-04: permanent hides the slot selector', () => {
const view = renderSnippetForm()
expect(view.getByText('Delivery Slot')).toBeTruthy()
fireEvent.press(view.getByText('Is Permanent?'))
expect(view.queryByText('Delivery Slot')).toBeNull()
// Current behaviour: the expiry field stays visible for permanent snippets.
expect(view.getByText('Valid Till (Optional)')).toBeTruthy()
})
it('AVSF-05: editing prefills the saved values', () => {
const validTill = new Date(Date.now() + 24 * HOUR)
const view = renderSnippetForm({
id: 1,
snippetCode: 'ABC123',
slotId: 1849,
isPermanent: false,
skuIds: [11],
validTill,
})
expect(view.getByText('Edit Vendor Snippet')).toBeTruthy()
expect(view.getByTestId('snippet-code-input').props.value).toBe('ABC123')
expect(view.getByText('Update Snippet')).toBeTruthy()
expect(view.getAllByText(validTill.toLocaleDateString()).length).toBeGreaterThanOrEqual(1)
})
it('AVSF-06: the product selector updates the selection', async () => {
const view = renderSnippetForm()
await flush()
selectSku(view, 'snippet-form-products-selector', 11)
expect(view.getByText('Chicken Breast - 500g')).toBeTruthy()
})
it('AVSF-07: submit sends the complete snippet payload', async () => {
const view = renderSnippetForm()
await flush()
fireEvent.changeText(view.getByTestId('snippet-code-input'), 'TEST_1')
fireEvent.press(view.getByText('Is Permanent?'))
selectSku(view, 'snippet-form-products-selector', 11)
fireEvent.press(view.getByTestId('snippet-submit-button'))
await flush(2)
expect(lastMutationInput('admin.vendorSnippets.create')).toEqual({
snippetCode: 'TEST_1',
slotId: undefined,
isPermanent: true,
skuIds: [11],
validTill: undefined,
})
expect(alertSpy).toHaveBeenCalledWith('Success', 'Vendor snippet created successfully')
expect(onSuccess).toHaveBeenCalled()
expect(onClose).toHaveBeenCalled()
})
it('AVSF-08: cancel calls onClose', () => {
const view = renderSnippetForm()
fireEvent.press(view.getByText('✕'))
expect(onClose).toHaveBeenCalled()
expect(procedureMutationCalls('admin.vendorSnippets.create')).toHaveLength(0)
})
})

View file

@ -1,133 +1,135 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* SnippetMenu (components/SnippetMenu.tsx) — per-snippet options dialog:
* view orders, edit, copy URL and delete with confirmation.
*
* The trigger has no testID, so it is located as the first TouchableOpacity
* rendered by the component (the dialog's backdrop only mounts while open).
* Catalogue section 15 — SnippetMenu (`tests/components/snippet-menu.test.tsx`).
*/
import React from 'react'
import { Alert, Clipboard, TouchableOpacity } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import Toast from 'react-native-toast-message'
import { Alert, Clipboard } from 'react-native'
import { fireEvent, render } from '@testing-library/react-native'
import { SnippetMenu } from '@/components/SnippetMenu'
import type { VendorSnippet } from '@/types/vendor-snippets'
import { renderWithProviders } from '../helpers/render'
import { resetAllMocks } from '../helpers/reset'
import { SNIPPET_1 } from '../fixtures'
const snippet: VendorSnippet = {
id: 5,
snippetCode: 'VS_5',
slotId: 2,
isPermanent: false,
skuIds: [10],
products: [{ id: 10, name: 'Chicken' }],
validTill: null,
createdAt: '2026-01-01T00:00:00.000Z',
accessUrl: 'https://app.freshyo.in/vendor-order-list?id=VS_5',
function openMenu(view: ReturnType<typeof render>) {
const trigger = view.UNSAFE_getAllByProps({ name: 'dots-three-vertical' })[0]
fireEvent.press(trigger)
}
const onEdit = jest.fn()
const onDelete = jest.fn()
const onViewOrders = jest.fn()
describe('SnippetMenu (ASMENU-01..05)', () => {
beforeEach(() => resetAllMocks())
const renderMenu = (overrides: Partial<VendorSnippet> = {}) =>
renderWithProviders(
<SnippetMenu
snippet={{ ...snippet, ...overrides }}
onEdit={onEdit}
onDelete={onDelete}
onViewOrders={onViewOrders}
/>
)
const openMenu = (result: ReturnType<typeof renderWithProviders>) => {
fireEvent.press(result.UNSAFE_getAllByType(TouchableOpacity)[0])
}
const pressLastAlertButton = (label: string) => {
const calls = (Alert.alert as jest.Mock).mock.calls
const call = calls[calls.length - 1]
const buttons = (call?.[2] ?? []) as { text: string; onPress?: () => void }[]
act(() => buttons.find((b) => b.text === label)?.onPress?.())
}
describe('SnippetMenu', () => {
beforeEach(() => {
onEdit.mockClear()
onDelete.mockClear()
onViewOrders.mockClear()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
jest.spyOn(Clipboard, 'setString').mockImplementation(async () => {})
afterEach(() => {
jest.restoreAllMocks()
})
it('opens the options dialog with every action', async () => {
const result = renderMenu()
expect(screen.queryByText('Snippet Options')).toBeNull()
openMenu(result)
expect(await screen.findByText('Snippet Options')).toBeVisible()
expect(screen.getByText('View Orders')).toBeVisible()
expect(screen.getByText('Edit')).toBeVisible()
expect(screen.getByText('Copy URL')).toBeVisible()
expect(screen.getByText('Delete')).toBeVisible()
})
it('calls onViewOrders with the snippet code', async () => {
const result = renderMenu()
openMenu(result)
fireEvent.press(await screen.findByText('View Orders'))
expect(onViewOrders).toHaveBeenCalledWith('VS_5')
})
it('calls onEdit with the snippet', async () => {
const result = renderMenu()
openMenu(result)
fireEvent.press(await screen.findByText('Edit'))
expect(onEdit).toHaveBeenCalledWith(expect.objectContaining({ id: 5 }))
})
it('asks for confirmation before deleting and calls onDelete', async () => {
const result = renderMenu()
openMenu(result)
fireEvent.press(await screen.findByText('Delete'))
expect(Alert.alert).toHaveBeenCalledWith(
'Delete Snippet',
'Are you sure you want to delete this vendor snippet?',
expect.any(Array)
it('ASMENU-01: the menu lists View Orders / Edit / Copy URL / Delete', () => {
const view = render(
<SnippetMenu
snippet={SNIPPET_1 as any}
onEdit={jest.fn()}
onDelete={jest.fn()}
onViewOrders={jest.fn()}
/>
)
openMenu(view)
expect(view.getByText('Snippet Options')).toBeTruthy()
expect(view.getByText('View Orders')).toBeTruthy()
expect(view.getByText('Edit')).toBeTruthy()
expect(view.getByText('Copy URL')).toBeTruthy()
expect(view.getByText('Delete')).toBeTruthy()
})
it('ASMENU-02: Copy URL without an access URL alerts and copies nothing', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const copySpy = jest.spyOn(Clipboard, 'setString').mockImplementation(async () => undefined)
const view = render(
<SnippetMenu
snippet={{ ...SNIPPET_1, accessUrl: null } as any}
onEdit={jest.fn()}
onDelete={jest.fn()}
onViewOrders={jest.fn()}
/>
)
openMenu(view)
fireEvent.press(view.getByText('Copy URL'))
expect(alertSpy).toHaveBeenCalledWith('Error', 'No URL available to copy')
expect(copySpy).not.toHaveBeenCalled()
})
it('ASMENU-03: Copy URL writes the access URL to the clipboard', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const copySpy = jest.spyOn(Clipboard, 'setString').mockImplementation(async () => undefined)
const view = render(
<SnippetMenu
snippet={SNIPPET_1 as any}
onEdit={jest.fn()}
onDelete={jest.fn()}
onViewOrders={jest.fn()}
/>
)
openMenu(view)
fireEvent.press(view.getByText('Copy URL'))
expect(copySpy).toHaveBeenCalledWith('https://access.test/ABC123')
expect(alertSpy).not.toHaveBeenCalled()
})
it('ASMENU-04: Delete confirms, then calls onDelete with the snippet id', () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const onDelete = jest.fn()
const view = render(
<SnippetMenu
snippet={SNIPPET_1 as any}
onEdit={jest.fn()}
onDelete={onDelete}
onViewOrders={jest.fn()}
/>
)
openMenu(view)
fireEvent.press(view.getByText('Delete'))
expect(alertSpy).toHaveBeenCalledTimes(1)
const [title, message, buttons] = alertSpy.mock.calls[0]
expect(title).toBe('Delete Snippet')
expect(message).toBe('Are you sure you want to delete this vendor snippet?')
expect(buttons?.map((button) => button.text)).toEqual(['Cancel', 'Delete'])
expect(onDelete).not.toHaveBeenCalled()
pressLastAlertButton('Delete')
expect(onDelete).toHaveBeenCalledWith(5)
buttons?.find((button) => button.text === 'Delete')?.onPress?.()
expect(onDelete).toHaveBeenCalledWith(1)
})
it('copies the access URL to the clipboard', async () => {
const result = renderMenu()
openMenu(result)
fireEvent.press(await screen.findByText('Copy URL'))
await waitFor(() =>
expect(Clipboard.setString).toHaveBeenCalledWith(snippet.accessUrl)
it('ASMENU-05: no menu option is currently disabled and a disabled option would no-op', () => {
const onEdit = jest.fn()
const onViewOrders = jest.fn()
const onDelete = jest.fn()
const view = render(
<SnippetMenu
snippet={SNIPPET_1 as any}
onEdit={onEdit}
onDelete={onDelete}
onViewOrders={onViewOrders}
/>
)
expect(Toast.show).toHaveBeenCalledWith(
expect.objectContaining({ type: 'success', text1: 'URL copied to clipboard' })
)
})
it('alerts when there is no URL to copy', async () => {
const result = renderMenu({ accessUrl: undefined })
openMenu(result)
openMenu(view)
fireEvent.press(await screen.findByText('Copy URL'))
// The source supports `option.disabled` (handleOptionPress returns early and
// the row gets `disabled`), but every built-in option is enabled today.
const titles = ['View Orders', 'Edit', 'Copy URL', 'Delete']
titles.forEach((title) => {
expect(view.getByText(title).parent?.props.disabled).toBeFalsy()
})
expect(Alert.alert).toHaveBeenCalledWith('Error', 'No URL available to copy')
expect(Clipboard.setString).not.toHaveBeenCalled()
fireEvent.press(view.getByText('View Orders'))
expect(onViewOrders).toHaveBeenCalledWith('ABC123')
expect(onEdit).not.toHaveBeenCalled()
expect(onDelete).not.toHaveBeenCalled()
})
})

View file

@ -1,94 +1,109 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* SnippetOrdersView (components/SnippetOrdersView.tsx) — read-only list of the
* orders matched by a vendor snippet, with per-order totals and an empty state.
* Catalogue section 15 — SnippetOrdersView
* (`tests/components/snippet-orders-view.test.tsx`).
*/
import React from 'react'
import { fireEvent, screen } from '@testing-library/react-native'
import { fireEvent } from '@testing-library/react-native'
import SnippetOrdersView from '@/components/SnippetOrdersView'
import { renderWithProviders } from '../helpers/render'
import { renderWithProviders } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { SNIPPET_ORDERS } from '../fixtures'
type Order = React.ComponentProps<typeof SnippetOrdersView>['orders'][number]
type Order = any
const order = (overrides: Partial<Order> = {}): Order => ({
orderId: 'ORD1',
orderDate: '2026-01-02T09:00:00.000Z',
customerName: 'Alice',
totalAmount: '100.00',
slotInfo: { time: '2026-01-03T10:00:00.000Z', sequence: [] },
snippetCode: 'VS_5',
matchedProducts: [10],
const ORDER: Order = {
...SNIPPET_ORDERS.data[0],
totalAmount: '445',
slotInfo: {
time: new Date('2026-10-19T12:00:00.000Z').toISOString(),
sequence: [],
},
products: [
{
productId: 10,
productName: 'Chicken',
orderItemId: 1,
productId: 2,
productName: 'Chicken Breast',
quantity: 2,
price: 50,
unit: 'kg',
subtotal: 100,
productSize: 500,
price: 215,
unit: '500g',
subtotal: 430,
},
{
orderItemId: 2,
productId: 5,
productName: 'Cucumber',
quantity: 1,
productSize: 500,
price: 15,
unit: '500g',
subtotal: 15,
},
],
...overrides,
})
}
describe('SnippetOrdersView', () => {
it('renders the header with snippet code, count and revenue', () => {
renderWithProviders(
<SnippetOrdersView
orders={[order(), order({ orderId: 'ORD2', totalAmount: '50.50', customerName: 'Bob' })]}
snippetCode="VS_5"
onClose={jest.fn()}
/>
)
function renderView(props: { orders: Order[]; snippetCode: string; onClose: () => void }) {
return renderWithProviders(<SnippetOrdersView {...props} />, { auth: false })
}
expect(screen.getByText('Orders for "VS_5"')).toBeVisible()
expect(screen.getByText('2 orders • Total: ₹150.50')).toBeVisible()
})
describe('SnippetOrdersView (ASOV-01..05)', () => {
beforeEach(() => resetAllMocks())
it('pluralises a single order', () => {
renderWithProviders(
<SnippetOrdersView orders={[order()]} snippetCode="VS_5" onClose={jest.fn()} />
)
it('ASOV-01: an order card shows id, customer, total, date and slot', () => {
const view = renderView({ orders: [ORDER], snippetCode: 'ABC123', onClose: jest.fn() })
expect(screen.getByText('1 order • Total: ₹100.00')).toBeVisible()
})
it('renders an order card with products and the matched flag', () => {
renderWithProviders(
<SnippetOrdersView orders={[order()]} snippetCode="VS_5" onClose={jest.fn()} />
)
expect(screen.getByText('ORD1')).toBeVisible()
expect(screen.getByText('Alice')).toBeVisible()
// Order total + product subtotal both render ₹100.00.
expect(screen.getAllByText('₹100.00')).toHaveLength(2)
expect(screen.getByText('Chicken ⭐')).toBeVisible()
expect(screen.getByText('2 kg × ₹50')).toBeVisible()
expect(view.getByText('Orders for "ABC123"')).toBeTruthy()
expect(view.getByText('ORD-1011')).toBeTruthy()
expect(view.getByText('Test User')).toBeTruthy()
expect(view.getByText('₹445')).toBeTruthy()
expect(view.getByText(new Date(ORDER.orderDate).toLocaleDateString())).toBeTruthy()
expect(
screen.getByText('Matched 1 product(s) from snippet "VS_5"')
).toBeVisible()
view.getByText(`Delivery: ${new Date(ORDER.slotInfo.time).toLocaleString()}`)
).toBeTruthy()
expect(view.getByText('1 order • Total: ₹445.00')).toBeTruthy()
})
it('shows the empty state when there are no matching orders', () => {
renderWithProviders(
<SnippetOrdersView orders={[]} snippetCode="VS_5" onClose={jest.fn()} />
)
it('ASOV-02: matched products are highlighted and non-matched ones are not', () => {
const view = renderView({
orders: [{ ...ORDER, matchedProducts: [2] }],
snippetCode: 'ABC123',
onClose: jest.fn(),
})
expect(screen.getByText('0 orders • Total: ₹0.00')).toBeVisible()
expect(screen.getByText('No matching orders')).toBeVisible()
// Matched rows get the star suffix; the non-matched row keeps its plain name.
expect(view.getByText('Chicken Breast ⭐')).toBeTruthy()
expect(view.getByText('Cucumber')).toBeTruthy()
expect(view.getByText('Matched 1 product(s) from snippet "ABC123"')).toBeTruthy()
})
it('ASOV-03: line subtotals and the order total are formatted to two decimals', () => {
const view = renderView({ orders: [ORDER], snippetCode: 'ABC123', onClose: jest.fn() })
expect(view.getByText('₹430.00')).toBeTruthy()
expect(view.getByText('₹15.00')).toBeTruthy()
expect(view.getByText('2 500g × ₹215')).toBeTruthy()
expect(view.getByText('1 500g × ₹15')).toBeTruthy()
expect(view.getByText('1 order • Total: ₹445.00')).toBeTruthy()
})
it('ASOV-04: an empty order list shows the empty state', () => {
const view = renderView({ orders: [], snippetCode: 'ABC123', onClose: jest.fn() })
expect(view.getByText('No matching orders')).toBeTruthy()
expect(
screen.getByText("No orders found that match this snippet's criteria")
).toBeVisible()
view.getByText("No orders found that match this snippet's criteria")
).toBeTruthy()
expect(view.getByText('0 orders • Total: ₹0.00')).toBeTruthy()
})
it('closes via the header button', () => {
it('ASOV-05: the close button calls onClose', () => {
const onClose = jest.fn()
renderWithProviders(
<SnippetOrdersView orders={[order()]} snippetCode="VS_5" onClose={onClose} />
)
const view = renderView({ orders: [ORDER], snippetCode: 'ABC123', onClose })
fireEvent.press(screen.getByText('✕'))
expect(onClose).toHaveBeenCalled()
fireEvent.press(view.getByText('✕'))
expect(onClose).toHaveBeenCalledTimes(1)
})
})

View file

@ -1,183 +1,242 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* StoreForm component (components/StoreForm.tsx) — validation, owner/product
* selection and the submit payload.
* Catalogue section 6.3 — StoreForm shared component
* (`tests/components/store-form.test.tsx`).
*/
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import { fireEvent, waitFor } from '@testing-library/react-native'
import * as ImagePicker from 'expo-image-picker'
import StoreForm, { StoreFormData } from '@/components/StoreForm'
import { setupApiMocks, resetStorage } from '../mocks/api'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { expectProcedureCalled } from '../mocks/procedures'
import { searchParamsMock } from '../mocks/router'
import { renderWithProviders } from '../helpers/render'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { setProcedure, setRawFetchHandler } from '../mocks/trpc-client'
import { STORE_1 } from '../fixtures'
const CREATE_INITIAL: StoreFormData = {
jest.mock('common-ui/src/components/ImageUploader', () => {
const ReactModule = require('react')
const { View, TouchableOpacity } = require('react-native')
const MockImageUploader = (props: any) => {
const children: any[] = [
ReactModule.createElement(TouchableOpacity, {
key: 'add',
testID: 'mock-add-image',
onPress: props.onAddImage,
}),
]
;(props.existingImageUrls || []).forEach((url: string, index: number) => {
children.push(
ReactModule.createElement(TouchableOpacity, {
key: `existing-${index}`,
testID: `mock-remove-existing-${index}`,
onPress: () => props.onRemoveExistingImage?.(url),
})
)
})
;(props.images || []).forEach((image: any, index: number) => {
children.push(
ReactModule.createElement(TouchableOpacity, {
key: `new-${index}`,
testID: `mock-remove-new-${index}`,
onPress: () => props.onRemoveImage?.(image.uri),
})
)
})
return ReactModule.createElement(View, null, children)
}
return { __esModule: true, default: MockImageUploader }
})
const PRICE_URL = 'https://upload.test/meatfarmer/product-images/img-1.jpg'
const PICKED_IMAGE = {
canceled: false,
assets: [{ uri: 'file:///tmp/store.jpg', mimeType: 'image/jpeg', fileName: 'store.jpg' }],
}
const initialValues: StoreFormData = {
name: '',
description: '',
owner: 0,
products: [],
}
const procedures = {
'admin.staffUser.getStaff': {
staff: [
{ id: 1, name: 'shafi', role: null, permissions: [] },
{ id: 2, name: 'naveen', role: null, permissions: [] },
],
},
'admin.product.getProducts': { products: [], count: 0 },
'common.product.getAllSkusSummary': {
skus: [
{
id: 11,
productId: 1,
productName: 'Chicken',
label: 'Chicken 1kg',
images: [],
storeId: null,
price: '100',
},
],
},
function renderForm(overrides: Partial<React.ComponentProps<typeof StoreForm>> = {}) {
const onSubmit = jest.fn()
const view = renderWithProviders(
<StoreForm
mode="create"
initialValues={initialValues}
onSubmit={onSubmit}
isLoading={false}
{...overrides}
/>,
{ auth: 'in' }
)
return { view, onSubmit }
}
describe('StoreForm', () => {
beforeEach(async () => {
resetStaffAuthMock()
await resetStorage()
searchParamsMock.current = {}
setupApiMocks({ procedures })
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
describe('StoreForm (ASTOREF-01..11)', () => {
let alertSpy: jest.SpyInstance
beforeEach(() => {
resetAllMocks()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValue({ canceled: true, assets: null })
// Non-tRPC requests (file:// reads and presigned PUTs) go through the raw handler.
setRawFetchHandler(async (url: string) => {
if (String(url).startsWith('file:')) {
return { ok: true, blob: async () => ({ size: 1 }) } as any
}
return { ok: true, status: 200, text: async () => '' } as any
})
})
it('renders the create form', async () => {
const onSubmit = jest.fn()
renderWithProviders(
<StoreForm
mode="create"
initialValues={CREATE_INITIAL}
onSubmit={onSubmit}
isLoading={false}
/>
)
afterEach(() => alertSpy?.mockRestore())
expect(screen.getByPlaceholderText('Enter store name')).toBeVisible()
expect(screen.getByPlaceholderText('Enter store description')).toBeVisible()
expect(screen.getByText('Select owner')).toBeVisible()
expect(screen.getByText('Select products')).toBeVisible()
expect(screen.getByText('Create Store')).toBeVisible()
it('ASTOREF-01: renders name, description, products and image fields', () => {
const { view } = renderForm()
expect(view.getByText('Store Name')).toBeTruthy()
expect(view.getByTestId('store-name-input')).toBeTruthy()
expect(view.getByText('Description')).toBeTruthy()
expect(view.getByTestId('store-description-input')).toBeTruthy()
expect(view.getByTestId('store-products-selector')).toBeTruthy()
expect(view.getByText('Store Image')).toBeTruthy()
expect(view.getByText('Create Store')).toBeTruthy()
})
it('BUG: submits even when the name is empty (validation is bypassed)', async () => {
const onSubmit = jest.fn()
renderWithProviders(
<StoreForm
mode="create"
initialValues={CREATE_INITIAL}
onSubmit={onSubmit}
isLoading={false}
/>
)
it('ASTOREF-02: an empty name submits as-is (validation is bypassed)', () => {
const { view, onSubmit } = renderForm()
fireEvent.press(screen.getByText('Create Store'))
await act(async () => {
await Promise.resolve()
await Promise.resolve()
fireEvent.press(view.getByTestId('store-submit-button'))
expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ name: '' }))
expect(view.queryByText('Name is required')).toBeNull()
})
it('ASTOREF-03: an empty description is allowed', () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(view.getByTestId('store-name-input'), 'New Store')
fireEvent.press(view.getByTestId('store-submit-button'))
expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ description: '' }))
})
it('ASTOREF-04: product selection is optional', () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(view.getByTestId('store-name-input'), 'New Store')
fireEvent.press(view.getByTestId('store-submit-button'))
expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ products: [] }))
})
it('ASTOREF-05: picking an image uploads it and replaces the existing one', async () => {
const { view, onSubmit } = renderForm({
mode: 'edit',
initialValues: { ...initialValues, name: STORE_1.name, imageUrl: STORE_1.imageUrl },
})
// Intended: Yup `name` is required and Formik should block this.
// Actual: the button calls the `onSubmit` prop directly, so the
// validationSchema never runs.
expect(onSubmit).toHaveBeenCalledWith(
expect.objectContaining({ name: '' })
)
;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValue(PICKED_IMAGE)
fireEvent.press(view.getByTestId('mock-add-image'))
await flush()
fireEvent.press(view.getByTestId('store-submit-button'))
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ imageUrl: PRICE_URL }))
})
expect(global.fetch).toHaveBeenCalledWith(PRICE_URL, expect.objectContaining({ method: 'PUT' }))
})
it('submits the typed name with the selected owner and product', async () => {
const onSubmit = jest.fn()
renderWithProviders(
<StoreForm
mode="create"
initialValues={CREATE_INITIAL}
onSubmit={onSubmit}
isLoading={false}
/>
)
it('ASTOREF-06: removing the existing image submits no imageUrl', () => {
const { view, onSubmit } = renderForm({
mode: 'edit',
initialValues: { ...initialValues, name: STORE_1.name, imageUrl: STORE_1.imageUrl },
})
fireEvent.changeText(
screen.getByPlaceholderText('Enter store name'),
'Freshyo Form'
)
fireEvent.press(view.getByTestId('mock-remove-existing-0'))
fireEvent.press(view.getByTestId('store-submit-button'))
fireEvent.press(screen.getByText('Select owner'))
fireEvent.press(await screen.findByText('naveen'))
fireEvent.press(screen.getByText('Select products'))
fireEvent.press(await screen.findByText('Chicken - ₹100'))
fireEvent.press(screen.getByText('Create Store'))
await waitFor(() =>
expect(onSubmit).toHaveBeenCalledWith({
name: 'Freshyo Form',
description: '',
owner: 2,
products: [11],
imageUrl: undefined,
})
)
expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ imageUrl: undefined }))
})
it('renders edit mode with prefilled values and the update label', () => {
const onSubmit = jest.fn()
renderWithProviders(
<StoreForm
mode="edit"
initialValues={{
name: 'Existing',
description: 'Old description',
owner: 1,
products: [],
}}
onSubmit={onSubmit}
isLoading={false}
storeId={3}
/>
)
it('ASTOREF-07: an invalid name still calls submit directly (gap)', () => {
const { view, onSubmit } = renderForm()
expect(screen.getByDisplayValue('Existing')).toBeVisible()
expect(screen.getByDisplayValue('Old description')).toBeVisible()
expect(screen.getByText('Update Store')).toBeVisible()
fireEvent.changeText(view.getByTestId('store-name-input'), ' ')
fireEvent.press(view.getByTestId('store-submit-button'))
expect(onSubmit).toHaveBeenCalledTimes(1)
expect(onSubmit.mock.calls[0][0].name).toBe(' ')
expect(view.queryByText('Name is required')).toBeNull()
})
it('shows the pending label when isLoading', () => {
renderWithProviders(
<StoreForm
mode="create"
initialValues={CREATE_INITIAL}
onSubmit={jest.fn()}
isLoading
/>
)
it('ASTOREF-08: onSubmit receives the values, the SKU selection and imageUrl', async () => {
const { view, onSubmit } = renderForm({
mode: 'edit',
storeId: 1,
initialValues: { ...initialValues, name: STORE_1.name },
})
await flush(2)
expect(screen.getByText('Creating...')).toBeVisible()
fireEvent.changeText(view.getByTestId('store-name-input'), 'My Store')
fireEvent.changeText(view.getByTestId('store-description-input'), 'A description')
// Deselect the preselected Cucumber SKU (13).
fireEvent.press(view.getByTestId('store-products-selector'))
fireEvent.press(view.getByTestId('store-products-selector-option-13'))
fireEvent.press(view.getByTestId('store-products-selector-done'))
fireEvent.press(view.getByTestId('store-submit-button'))
expect(onSubmit).toHaveBeenCalledWith({
name: 'My Store',
description: 'A description',
products: [11, 12, 61, 71, 81, 82],
imageUrl: undefined,
})
})
it('loads staff and products', async () => {
const { fetchMock } = setupApiMocks({ procedures })
renderWithProviders(
<StoreForm
mode="create"
initialValues={CREATE_INITIAL}
onSubmit={jest.fn()}
isLoading={false}
/>
)
it('ASTOREF-09: create and edit label variants', () => {
const create = renderForm({ mode: 'create' })
expect(create.view.getByText('Create Store')).toBeTruthy()
create.view.unmount()
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.staffUser.getStaff'))
expectProcedureCalled(fetchMock, 'admin.product.getProducts')
const edit = renderForm({ mode: 'edit', initialValues: { ...initialValues, name: 'A' } })
expect(edit.view.getByText('Update Store')).toBeTruthy()
edit.view.unmount()
const creating = renderForm({ mode: 'create', isLoading: true })
expect(creating.view.getByText('Creating...')).toBeTruthy()
creating.view.unmount()
const updating = renderForm({ mode: 'edit', isLoading: true })
expect(updating.view.getByText('Updating...')).toBeTruthy()
})
it('ASTOREF-10: an upload failure alerts and never calls onSubmit', async () => {
setProcedure('common.generateUploadUrls', { mode: 'error', error: new Error('upload down') })
const { view, onSubmit } = renderForm()
;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValue(PICKED_IMAGE)
fireEvent.press(view.getByTestId('mock-add-image'))
await flush()
fireEvent.press(view.getByTestId('store-submit-button'))
await flush(2)
expect(alertSpy).toHaveBeenCalledWith('Error', 'Failed to upload image')
expect(onSubmit).not.toHaveBeenCalled()
})
it('ASTOREF-11: while uploading the button shows "Uploading..."', async () => {
setProcedure('common.generateUploadUrls', { mode: 'pending' })
const { view } = renderForm()
;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValue(PICKED_IMAGE)
fireEvent.press(view.getByTestId('mock-add-image'))
await flush()
fireEvent.press(view.getByTestId('store-submit-button'))
await flush(2)
expect(view.getByText('Uploading...')).toBeTruthy()
})
})

View file

@ -1,160 +1,164 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* TagForm (src/components/TagForm.tsx) — name/description fields, dashboard
* checkbox, related-store dropdown, product selection and submit payload.
*
* The submit button has no testID in source; it is located by its label.
* Catalogue section 10.2 — TagForm (`tests/components/tag-form.test.tsx`).
*/
import React from 'react'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import { act, fireEvent } from '@testing-library/react-native'
import { BottomDropdown, Checkbox, ImageUploaderNeo } from 'common-ui'
import TagForm from '@/src/components/TagForm'
import { resetStorage, setupApiMocks } from '../mocks/api'
import { expectProcedureCalled } from '../mocks/procedures'
import { renderWithProviders } from '../helpers/render'
import TagForm, { TagFormData } from '@/src/components/TagForm'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
const baseValues = {
tagName: 'Bestsellers',
tagDescription: 'Top picks',
type View = ReturnType<typeof renderForm>['view']
const INITIAL: TagFormData = {
tagName: 'Chicken',
tagDescription: 'All chicken items',
isDashboardTag: false,
relatedStores: [],
productIds: [],
}
const stores = [
{ id: 1, name: 'Main Store' },
{ id: 2, name: 'Second Store' },
const STORES = [
{ id: 1, name: 'The Freshyo Meat House' },
{ id: 2, name: 'Freshyo Central' },
]
const skusResponse = {
skus: [
{ id: 1, productId: 10, productName: 'Chicken', label: 'Chicken 1kg' },
{ id: 2, productId: 11, productName: 'Mutton', label: 'Mutton 1kg' },
],
function renderForm(props: Partial<React.ComponentProps<typeof TagForm>> = {}) {
const onSubmit = jest.fn()
const view = renderWithProviders(
<TagForm
mode="create"
initialValues={INITIAL}
onSubmit={onSubmit}
isLoading={false}
stores={STORES}
{...props}
/>,
{ auth: false }
)
return { view, onSubmit }
}
describe('TagForm', () => {
beforeEach(async () => {
await resetStorage()
function nameInput(view: View) {
return view.getByPlaceholderText('Enter tag name')
}
async function submit(view: View, mode: 'create' | 'edit' = 'create') {
fireEvent.press(view.getByText(mode === 'create' ? 'Create Tag' : 'Update Tag'))
await flush(2)
}
describe('TagForm (ATAGF-01..08)', () => {
beforeEach(() => resetAllMocks())
it('ATAGF-01: renders name, description, image, dashboard, stores and products', () => {
const { view } = renderForm()
expect(nameInput(view)).toBeTruthy()
expect(view.getByPlaceholderText('Enter tag description')).toBeTruthy()
expect(view.getByText('Tag Image (Optional)')).toBeTruthy()
expect(view.getByText('Mark as Dashboard Tag')).toBeTruthy()
expect(view.getByText('Related Stores')).toBeTruthy()
expect(view.getByText('Products')).toBeTruthy()
expect(view.getByText('Create Tag')).toBeTruthy()
})
it('renders the create-mode fields with seeded values', () => {
setupApiMocks({
procedures: { 'common.product.getAllSkusSummary': skusResponse },
})
renderWithProviders(
<TagForm mode="create" initialValues={baseValues} onSubmit={jest.fn()} isLoading={false} stores={stores} />
)
it('ATAGF-02: an empty name blocks submission', async () => {
const { view, onSubmit } = renderForm()
expect(screen.getByDisplayValue('Bestsellers')).toBeVisible()
expect(screen.getByDisplayValue('Top picks')).toBeVisible()
expect(screen.getByText('Mark as Dashboard Tag')).toBeVisible()
expect(screen.getByText('Create Tag')).toBeVisible()
expect(screen.getByText('No products selected yet')).toBeVisible()
fireEvent.changeText(nameInput(view), '')
await submit(view)
expect(onSubmit).not.toHaveBeenCalled()
})
it('shows edit-mode labels', () => {
setupApiMocks({
procedures: { 'common.product.getAllSkusSummary': skusResponse },
})
renderWithProviders(
<TagForm mode="edit" initialValues={baseValues} onSubmit={jest.fn()} isLoading={false} stores={stores} />
)
it('ATAGF-03: picked images are passed to onSubmit', async () => {
const { view, onSubmit } = renderForm()
expect(screen.getByText('Update Tag')).toBeVisible()
expect(screen.getByText('Tag Image (Upload new to replace)')).toBeVisible()
const uploader = view.UNSAFE_getByType(ImageUploaderNeo)
act(() => {
uploader.props.onImageAdd([{ url: 'file:///tag.jpg', mimeType: 'image/jpeg' }])
})
await submit(view)
expect(onSubmit).toHaveBeenCalledTimes(1)
expect(onSubmit.mock.calls[0][1]).toEqual([
{ imgUrl: 'file:///tag.jpg', mimeType: 'image/jpeg' },
])
expect(onSubmit.mock.calls[0][2]).toBe(false)
})
it('shows the submit-progress label', () => {
setupApiMocks({
procedures: { 'common.product.getAllSkusSummary': skusResponse },
it('ATAGF-04: the dashboard checkbox submits a boolean', async () => {
const { view, onSubmit } = renderForm()
const checkbox = view.UNSAFE_getAllByType(Checkbox)[0]
act(() => {
checkbox.props.onPress?.()
})
renderWithProviders(
<TagForm mode="create" initialValues={baseValues} onSubmit={jest.fn()} isLoading stores={stores} />
)
await submit(view)
expect(screen.getByText('Creating...')).toBeVisible()
expect(screen.queryByText('Create Tag')).toBeNull()
})
it('submits the current form values', async () => {
const onSubmit = jest.fn()
setupApiMocks({
procedures: { 'common.product.getAllSkusSummary': skusResponse },
})
renderWithProviders(
<TagForm mode="create" initialValues={baseValues} onSubmit={onSubmit} isLoading={false} stores={stores} />
)
fireEvent.changeText(screen.getByDisplayValue('Bestsellers'), 'Featured')
fireEvent.press(screen.getByText('Create Tag'))
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
const [values, images, removedExisting] = onSubmit.mock.calls[0]
expect(values.tagName).toBe('Featured')
expect(values.tagDescription).toBe('Top picks')
expect(values.productIds).toEqual([])
expect(images).toEqual([])
expect(removedExisting).toBe(false)
})
it('toggles the dashboard-tag checkbox', async () => {
const onSubmit = jest.fn()
setupApiMocks({
procedures: { 'common.product.getAllSkusSummary': skusResponse },
})
renderWithProviders(
<TagForm mode="create" initialValues={baseValues} onSubmit={onSubmit} isLoading={false} stores={stores} />
)
fireEvent.press(screen.getByRole('checkbox'))
fireEvent.press(screen.getByText('Create Tag'))
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
expect(onSubmit.mock.calls[0][0].isDashboardTag).toBe(true)
})
it('adds a selected product to the ordered list and submits its id', async () => {
const onSubmit = jest.fn()
const api = setupApiMocks({
procedures: { 'common.product.getAllSkusSummary': skusResponse },
it('ATAGF-05: related stores submit their ids', async () => {
const { view, onSubmit } = renderForm()
const storesDropdown = view.UNSAFE_getAllByType(BottomDropdown)[0]
act(() => {
storesDropdown.props.onValueChange(['1'])
})
const result = renderWithProviders(
<TagForm mode="create" initialValues={baseValues} onSubmit={onSubmit} isLoading={false} stores={stores} />
)
await submit(view)
await waitFor(() =>
expectProcedureCalled(api.fetchMock, 'common.product.getAllSkusSummary')
)
// ProductsSelector is rendered without a testID. Open the SKU dropdown by
// its placeholder text, then pick the first option.
fireEvent.press(screen.getByText('Search and select products...'))
const option = await screen.findByLabelText('undefined-option-1')
fireEvent.press(option)
await waitFor(() => expect(screen.getAllByText('Chicken 1kg').length).toBeGreaterThan(0))
fireEvent.press(screen.getByText('Create Tag'))
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
expect(onSubmit.mock.calls[0][0].productIds).toEqual([10])
expect(onSubmit.mock.calls[0][0].relatedStores).toEqual([1])
})
it('renders seeded products from productIds', async () => {
setupApiMocks({
procedures: { 'common.product.getAllSkusSummary': skusResponse },
})
renderWithProviders(
<TagForm
mode="edit"
initialValues={{ ...baseValues, productIds: [11] }}
onSubmit={jest.fn()}
isLoading={false}
stores={stores}
/>
)
it('ATAGF-06: product selection submits product ids', async () => {
const { view, onSubmit } = renderForm()
// SKU options arrive from a real query; wait for them before selecting.
await flush()
await waitFor(() => expect(screen.getByText('Mutton 1kg')).toBeVisible())
expect(screen.getByText(/1 items/)).toBeVisible()
const dropdowns = view.UNSAFE_getAllByType(BottomDropdown)
const productsDropdown = dropdowns[dropdowns.length - 1]
act(() => {
productsDropdown.props.onValueChange(['11'])
})
await flush()
await submit(view)
expect(onSubmit.mock.calls[0][0].productIds).toEqual([2])
})
it('ATAGF-07: submitting passes the complete tag payload', async () => {
const { view, onSubmit } = renderForm({
mode: 'edit',
initialValues: {
tagName: 'Chicken',
tagDescription: 'All chicken items',
isDashboardTag: true,
relatedStores: [1],
productIds: [2],
},
})
await submit(view, 'edit')
expect(onSubmit).toHaveBeenCalledTimes(1)
expect(onSubmit.mock.calls[0][0]).toMatchObject({
tagName: 'Chicken',
tagDescription: 'All chicken items',
isDashboardTag: true,
relatedStores: [1],
productIds: [2],
})
})
it('ATAGF-08: the form exposes no cancel control', () => {
const { view } = renderForm()
// TagForm has no onClose prop/button; the only action is Create Tag.
expect(view.queryByText('Cancel')).toBeNull()
expect(view.getByText('Create Tag')).toBeTruthy()
})
})

View file

@ -1,118 +0,0 @@
/**
* TagMenu (src/components/TagMenu.tsx) — per-tag options menu: open dialog,
* navigate to edit, and delete with confirmation.
*
* The trigger has no testID in source, so it is located as the first
* TouchableOpacity rendered by the component.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert, TouchableOpacity } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import { TagMenu } from '@/src/components/TagMenu'
import { resetStorage, setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
} from '../mocks/procedures'
import { routerMock } from '../mocks/router'
import { renderWithProviders } from '../helpers/render'
const openMenu = (result: ReturnType<typeof renderWithProviders>) => {
const trigger = result.UNSAFE_getAllByType(TouchableOpacity)[0]
fireEvent.press(trigger)
}
const pressLastAlertButton = (label: string) => {
const calls = (Alert.alert as jest.Mock).mock.calls
const call = calls[calls.length - 1]
const buttons = (call?.[2] ?? []) as { text: string; onPress?: () => void }[]
act(() => buttons.find((b) => b.text === label)?.onPress?.())
}
describe('TagMenu', () => {
beforeEach(async () => {
await resetStorage()
setupApiMocks()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('opens the options dialog', async () => {
const result = renderWithProviders(<TagMenu tagId={1} />)
expect(screen.queryByText('Tag Options')).toBeNull()
openMenu(result)
await waitFor(() => expect(screen.getByText('Tag Options')).toBeVisible())
expect(screen.getByText('Edit Tag')).toBeVisible()
expect(screen.getByText('Delete Tag')).toBeVisible()
})
it('navigates to the edit screen', async () => {
const result = renderWithProviders(<TagMenu tagId={7} />)
openMenu(result)
fireEvent.press(await screen.findByText('Edit Tag'))
expect(routerMock.push).toHaveBeenCalledWith(
'/(drawer)/dashboard/product-tags/edit?tagId=7'
)
})
it('asks for confirmation before deleting', async () => {
const result = renderWithProviders(<TagMenu tagId={7} />)
openMenu(result)
fireEvent.press(await screen.findByText('Delete Tag'))
expect(Alert.alert).toHaveBeenCalledWith(
'Delete Tag',
'Are you sure you want to delete this tag? This action cannot be undone.',
expect.any(Array)
)
})
it('deletes the tag and calls onDeleteSuccess', async () => {
const onDeleteSuccess = jest.fn()
const api = setupApiMocks({
procedures: {
'admin.product.deleteProductTag': { message: 'Tag deleted successfully' },
},
})
const result = renderWithProviders(
<TagMenu tagId={7} onDeleteSuccess={onDeleteSuccess} />
)
openMenu(result)
fireEvent.press(await screen.findByText('Delete Tag'))
pressLastAlertButton('Delete')
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.product.deleteProductTag'))
expect(lastProcedureInput(api.fetchMock, 'admin.product.deleteProductTag')).toEqual({ id: 7 })
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Tag deleted successfully')
)
expect(onDeleteSuccess).toHaveBeenCalled()
})
it('shows an error alert when deletion fails', async () => {
setupApiMocks({
procedures: {
'admin.product.deleteProductTag': () => {
throw new Error('nope')
},
},
})
const result = renderWithProviders(<TagMenu tagId={7} />)
openMenu(result)
fireEvent.press(await screen.findByText('Delete Tag'))
pressLastAlertButton('Delete')
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Error', expect.any(String))
)
})
})

View file

@ -1,249 +1,261 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* UserIncidentsView (components/UserIncidentsView.tsx) — incident list, empty
* state, add-incident dialog, validation and the addUserIncident mutation.
* Catalogue section 14.5 — User incidents (`tests/components/user-incidents-view.test.tsx`).
*
* HARNESS BUG WORKAROUND: tests/mocks/native.ts has a stray top-level `return`
* (line 89 → "'return' outside of function"). Re-mock the expo modules that
* `common-ui` eagerly imports locally. See report.
* The shared `USER_INCIDENTS` fixture is DB-shaped (`addedBy` is an object,
* `order` is nested). The component renders `addedBy` as a child, so this file
* feeds the procedure-shaped value the backend actually returns.
*/
jest.mock('expo-image', () => {
const React = require('react')
const { View } = require('react-native')
const Image = (props: Record<string, unknown>) =>
React.createElement(View, { testID: 'mock-image', ...props })
return { __esModule: true, Image, default: Image }
})
jest.mock('expo-image-picker', () => {
const asset = { uri: 'file:///tmp/pick.jpg', fileName: 'pick.jpg', mimeType: 'image/jpeg' }
return {
__esModule: true,
MediaTypeOptions: { Images: 'Images', All: 'All', Videos: 'Videos' },
launchImageLibraryAsync: jest.fn(async () => ({ canceled: false, assets: [asset] })),
launchCameraAsync: jest.fn(async () => ({ canceled: false, assets: [asset] })),
requestMediaLibraryPermissionsAsync: jest.fn(async () => ({ granted: true, status: 'granted' })),
requestCameraPermissionsAsync: jest.fn(async () => ({ granted: true, status: 'granted' })),
}
})
jest.mock('expo-document-picker', () => ({
__esModule: true,
getDocumentAsync: jest.fn(async () => ({
canceled: false,
assets: [{ uri: 'file:///tmp/doc.pdf', name: 'doc.pdf', mimeType: 'application/pdf' }],
})),
}))
import React from 'react'
import { Alert } from 'react-native'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import { act, fireEvent, waitFor } from '@testing-library/react-native'
import dayjs from 'dayjs'
import { UserIncidentsView } from '@/components/UserIncidentsView'
import { resetStorage, setupApiMocks } from '../mocks/api'
import { expectProcedureCalled, lastProcedureInput, procCount } from '../mocks/procedures'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { renderWithProviders } from '../helpers/render'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import {
lastMutationInput,
procedureMutationCalls,
procedureQueryCalls,
setProcedure,
} from '../mocks/trpc-client'
const incident = {
const NOW = new Date().toISOString()
const INCIDENT = {
id: 1,
userId: 3,
orderId: 7,
dateAdded: '2026-01-01T10:00:00.000Z',
adminComment: 'Abusive behaviour',
addedBy: 'shafi',
negativityScore: 5,
orderStatus: 'cancelled',
userId: 5,
orderId: 11,
dateAdded: NOW,
adminComment: 'Late delivery',
addedBy: 'Admin One',
negativityScore: 2,
orderStatus: 'active',
}
const procedures = (overrides: Record<string, unknown> = {}) => ({
'admin.user.getUserIncidents': { incidents: [incident] },
'admin.user.addUserIncident': { success: true, data: { id: 2 } },
...overrides,
})
const renderView = (
props: { userId: number; orderId: number | null } = { userId: 3, orderId: null },
overrides: Record<string, unknown> = {}
) => {
const { fetchMock } = setupApiMocks({ procedures: procedures(overrides) })
renderWithProviders(<UserIncidentsView {...props} />)
return { fetchMock }
function setIncidents(incidents: any[]) {
setProcedure('admin.user.getUserIncidents', { data: { incidents } })
}
const openDialog = async () => {
fireEvent.press(screen.getByText('Add Incident'))
await screen.findByText('Add User Incident')
function renderView(orderId: number | null = null) {
return renderWithProviders(<UserIncidentsView userId={5} orderId={orderId} />, { auth: 'in' })
}
const submit = () => {
fireEvent.press(screen.getAllByText('Add Incident').pop()!)
async function openDialog(view: ReturnType<typeof renderView>) {
fireEvent.press(view.getByText('Add Incident'))
await flush()
}
describe('UserIncidentsView', () => {
beforeEach(async () => {
resetStaffAuthMock()
await resetStorage()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
async function pressSubmit(view: ReturnType<typeof renderView>) {
// [0] is the header button, [1] is the dialog's submit button.
fireEvent.press(view.getAllByText('Add Incident')[1])
await flush(2)
}
describe('User incidents view (AINC-01..09, AUIV-01..03)', () => {
let alertSpy: jest.SpyInstance
beforeEach(() => {
resetAllMocks()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
setIncidents([])
})
it('renders the section header and add button', async () => {
renderView()
afterEach(() => alertSpy?.mockRestore())
expect(screen.getByText('User Incidents')).toBeVisible()
expect(screen.getByText('Add Incident')).toBeVisible()
await screen.findByText('Abusive behaviour')
it('AINC-01: a pending query shows no spinner (current gap) and the empty copy', async () => {
setProcedure('admin.user.getUserIncidents', { mode: 'pending' })
const view = renderView()
await flush()
// The component never reads `isLoading`, so there is no spinner today.
expect(view.UNSAFE_queryAllByType(require('react-native').ActivityIndicator)).toHaveLength(0)
expect(view.getByText('No incidents recorded for this user')).toBeTruthy()
})
it('queries incidents for the given user', async () => {
const { fetchMock } = renderView()
it('AINC-02: an empty list shows the empty copy', async () => {
const view = renderView()
await flush()
await waitFor(() =>
expectProcedureCalled(fetchMock, 'admin.user.getUserIncidents')
)
expect(lastProcedureInput(fetchMock, 'admin.user.getUserIncidents')).toEqual({
userId: 3,
})
expect(view.getByText('No incidents recorded for this user')).toBeTruthy()
})
it('does not query when there is no user id', () => {
const { fetchMock } = renderView({ userId: 0, orderId: null })
it('AINC-03: a row shows comment, date, addedBy, score and order', async () => {
setIncidents([INCIDENT])
expect(procCount(fetchMock, 'admin.user.getUserIncidents')).toBe(0)
const view = renderView()
await flush()
expect(view.getByText('Late delivery')).toBeTruthy()
expect(view.getByText(dayjs(NOW).format('MMM DD, YYYY • h:mm A'))).toBeTruthy()
expect(view.getByText('Added by Admin One')).toBeTruthy()
expect(view.getByText('Score: 2')).toBeTruthy()
expect(view.getByText('Order #11')).toBeTruthy()
// `orderStatus` is returned by the API but not rendered by the component.
expect(view.queryByText('active')).toBeNull()
})
it('renders each incident with its score, author and order', async () => {
renderView()
it('AINC-04: Add Incident opens the dialog form', async () => {
const view = renderView()
await flush()
expect(await screen.findByText('Abusive behaviour')).toBeVisible()
expect(screen.getByText('Score: 5')).toBeVisible()
expect(screen.getByText('Added by shafi')).toBeVisible()
expect(screen.getByText('Order #7')).toBeVisible()
expect(screen.getByText(/Jan 01, 2026/)).toBeVisible()
await openDialog(view)
expect(view.getByText('Add User Incident')).toBeTruthy()
expect(view.getByText('Admin Comment')).toBeTruthy()
expect(view.getByText('Negativity Score (Optional)')).toBeTruthy()
expect(view.getByPlaceholderText('Enter details about the incident...')).toBeTruthy()
expect(view.getByPlaceholderText('0')).toBeTruthy()
expect(view.getByText('Cancel')).toBeTruthy()
expect(view.getAllByText('Add Incident')).toHaveLength(2)
})
it('renders the empty state when there are no incidents', async () => {
renderView({ userId: 3, orderId: null }, { 'admin.user.getUserIncidents': { incidents: [] } })
it('AINC-05: submitting nothing alerts and makes no API call', async () => {
const view = renderView()
await flush()
expect(
await screen.findByText('No incidents recorded for this user')
).toBeVisible()
await openDialog(view)
await pressSubmit(view)
expect(alertSpy).toHaveBeenCalledWith('Error', 'Please enter a comment or negativity score')
expect(procedureMutationCalls('admin.user.addUserIncident')).toHaveLength(0)
})
it('renders the empty state when the query returns null', async () => {
renderView({ userId: 3, orderId: null }, { 'admin.user.getUserIncidents': null })
expect(
await screen.findByText('No incidents recorded for this user')
).toBeVisible()
})
it('rejects an empty incident without calling the mutation', async () => {
const { fetchMock } = renderView()
await openDialog()
submit()
expect(Alert.alert).toHaveBeenCalledWith(
'Error',
'Please enter a comment or negativity score'
)
expect(procCount(fetchMock, 'admin.user.addUserIncident')).toBe(0)
})
it('adds an incident with an admin comment', async () => {
const { fetchMock } = renderView()
await openDialog()
it('AINC-06: submitting sends the mutation, alerts, refetches and resets the form', async () => {
const view = renderView()
await flush()
await openDialog(view)
fireEvent.changeText(
screen.getByPlaceholderText('Enter details about the incident...'),
'Repeated cancellations'
view.getByPlaceholderText('Enter details about the incident...'),
'Rude to staff'
)
submit()
const queriesBefore = procedureQueryCalls('admin.user.getUserIncidents').length
await pressSubmit(view)
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.user.addUserIncident'))
expect(lastProcedureInput(fetchMock, 'admin.user.addUserIncident')).toEqual({
userId: 3,
adminComment: 'Repeated cancellations',
await waitFor(() => {
expect(lastMutationInput('admin.user.addUserIncident')).toEqual({
userId: 5,
orderId: undefined,
adminComment: 'Rude to staff',
negativityScore: undefined,
})
})
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Incident added successfully')
)
expect(alertSpy).toHaveBeenCalledWith('Success', 'Incident added successfully')
await waitFor(() => {
expect(procedureQueryCalls('admin.user.getUserIncidents').length).toBeGreaterThan(
queriesBefore
)
})
expect(view.queryByText('Add User Incident')).toBeNull()
})
it('adds an incident with only a negativity score', async () => {
const { fetchMock } = renderView()
await openDialog()
it('AINC-07: a failed mutation alerts the error', async () => {
setProcedure('admin.user.addUserIncident', { mode: 'error', error: new Error('boom') })
fireEvent.changeText(screen.getByPlaceholderText('0'), '7')
submit()
const view = renderView()
await flush()
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.user.addUserIncident'))
expect(lastProcedureInput(fetchMock, 'admin.user.addUserIncident')).toEqual({
userId: 3,
negativityScore: 7,
})
await openDialog(view)
fireEvent.changeText(view.getByPlaceholderText('Enter details about the incident...'), 'Rude')
await pressSubmit(view)
expect(alertSpy).toHaveBeenCalledWith('Error', 'boom')
})
it('adds an incident with a comment and score including the order id', async () => {
const { fetchMock } = renderView({ userId: 3, orderId: 7 })
await openDialog()
it('AINC-08: an order-scoped incident sends orderId + parsed score, omitting empty fields', async () => {
const view = renderView(11)
await flush()
fireEvent.changeText(
screen.getByPlaceholderText('Enter details about the incident...'),
'Rude call'
)
fireEvent.changeText(screen.getByPlaceholderText('0'), '3')
submit()
await openDialog(view)
fireEvent.changeText(view.getByPlaceholderText('Enter details about the incident...'), 'Rude')
fireEvent.changeText(view.getByPlaceholderText('0'), '3')
await pressSubmit(view)
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.user.addUserIncident'))
expect(lastProcedureInput(fetchMock, 'admin.user.addUserIncident')).toEqual({
userId: 3,
orderId: 7,
adminComment: 'Rude call',
expect(lastMutationInput('admin.user.addUserIncident')).toEqual({
userId: 5,
orderId: 11,
adminComment: 'Rude',
negativityScore: 3,
})
})
it('refetches the incidents and closes the dialog after adding', async () => {
const { fetchMock } = renderView()
await screen.findByText('Abusive behaviour')
const before = procCount(fetchMock, 'admin.user.getUserIncidents')
it('AINC-09: a pending submit shows "Adding..." and disables a second submit', async () => {
setProcedure('admin.user.addUserIncident', { mode: 'pending' })
await openDialog()
fireEvent.changeText(
screen.getByPlaceholderText('Enter details about the incident...'),
'Late arrival'
)
submit()
const view = renderView()
await flush()
await waitFor(() =>
expect(procCount(fetchMock, 'admin.user.getUserIncidents')).toBeGreaterThan(before)
)
await waitFor(() => expect(screen.queryByText('Add User Incident')).toBeNull())
await openDialog(view)
fireEvent.changeText(view.getByPlaceholderText('Enter details about the incident...'), 'Rude')
fireEvent.press(view.getAllByText('Add Incident')[1])
await flush(2)
expect(view.getByText('Adding...')).toBeTruthy()
fireEvent.press(view.getByText('Adding...'))
await act(async () => {
await flush()
})
expect(procedureMutationCalls('admin.user.addUserIncident')).toHaveLength(1)
})
it('shows the error alert when adding fails and keeps the dialog open', async () => {
const { fetchMock } = renderView(
{ userId: 3, orderId: null },
{
'admin.user.addUserIncident': () => {
throw new Error('nope')
},
}
)
await openDialog()
/* ---------------------------------------------------------------------- */
/* Catalogue §17.1 — UserIncidentsView aliases */
/* ---------------------------------------------------------------------- */
fireEvent.changeText(
screen.getByPlaceholderText('Enter details about the incident...'),
'Something'
)
submit()
it('AUIV-01: renders the empty state and then a populated list', async () => {
setIncidents([])
const empty = renderView()
await flush()
expect(empty.getByText('No incidents recorded for this user')).toBeTruthy()
empty.unmount()
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Error', 'nope')
)
expect(fetchMock).toBeTruthy()
expect(screen.getByText('Add User Incident')).toBeVisible()
setIncidents([INCIDENT])
const view = renderView()
await flush()
expect(view.getByText('Late delivery')).toBeTruthy()
expect(view.getByText('Added by Admin One')).toBeTruthy()
expect(view.getByText('Score: 2')).toBeTruthy()
})
it('AUIV-02: adding an incident calls the API and refetches', async () => {
const view = renderView()
await flush()
await openDialog(view)
fireEvent.changeText(view.getByPlaceholderText('Enter details about the incident...'), 'Rude')
const queriesBefore = procedureQueryCalls('admin.user.getUserIncidents').length
await pressSubmit(view)
await waitFor(() => {
expect(lastMutationInput('admin.user.addUserIncident')).toEqual({
userId: 5,
orderId: undefined,
adminComment: 'Rude',
negativityScore: undefined,
})
})
await waitFor(() => {
expect(procedureQueryCalls('admin.user.getUserIncidents').length).toBeGreaterThan(
queriesBefore
)
})
})
it('AUIV-03: a failed add alerts the error', async () => {
setProcedure('admin.user.addUserIncident', { mode: 'error', error: new Error('boom') })
const view = renderView()
await flush()
await openDialog(view)
fireEvent.changeText(view.getByPlaceholderText('Enter details about the incident...'), 'Rude')
await pressSubmit(view)
expect(alertSpy).toHaveBeenCalledWith('Error', 'boom')
})
})

View file

@ -0,0 +1,163 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 4.2 — Variant stock dialog (`src/components/VariantStockDialog.tsx`).
*/
import React from 'react'
import { fireEvent } from '@testing-library/react-native'
import Toast from 'react-native-toast-message'
import VariantStockDialog from '@/src/components/VariantStockDialog'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { lastMutationInput, procedureMutationCalls, setProcedure } from '../mocks/trpc-client'
import { P_CHICKEN, P_CUCUMBER, P_PARTIAL } from '../fixtures'
function renderDialog(overrides: Partial<React.ComponentProps<typeof VariantStockDialog>> = {}) {
const onClose = jest.fn()
const onApplied = jest.fn()
const view = renderWithProviders(
<VariantStockDialog
open
product={P_CHICKEN as any}
onClose={onClose}
onApplied={onApplied}
{...overrides}
/>,
{ auth: false }
)
return { view, onClose, onApplied }
}
describe('Variant stock dialog (AVSTOCK-01..12)', () => {
beforeEach(() => resetAllMocks())
it('AVSTOCK-01: opens with the product name and all variants selected', () => {
const { view } = renderDialog()
expect(view.getByText('Chicken Breast')).toBeTruthy()
expect(view.getByText('Variants (2/2)')).toBeTruthy()
expect(view.getByTestId('variant-stock-11').props.accessibilityState.checked).toBe(true)
expect(view.getByTestId('variant-stock-12').props.accessibilityState.checked).toBe(true)
})
it('AVSTOCK-02: shows the amber partial-state copy', () => {
const { view } = renderDialog({ product: P_PARTIAL as any })
expect(view.getByText('1 of 2 variants are out of stock')).toBeTruthy()
})
it('AVSTOCK-03: selecting/deselecting a variant updates the count', () => {
const { view } = renderDialog()
fireEvent.press(view.getByTestId('variant-stock-11'))
expect(view.getByText('Variants (1/2)')).toBeTruthy()
expect(view.getByTestId('variant-stock-11').props.accessibilityState.checked).toBe(false)
})
it('AVSTOCK-04: Clear all / Select all toggles every variant', () => {
const { view } = renderDialog()
fireEvent.press(view.getByText('Clear all'))
expect(view.getByText('Variants (0/2)')).toBeTruthy()
fireEvent.press(view.getByText('Select all'))
expect(view.getByText('Variants (2/2)')).toBeTruthy()
})
it('AVSTOCK-05: with no selection both apply buttons are disabled', () => {
const { view } = renderDialog()
fireEvent.press(view.getByText('Clear all'))
expect(view.getByText('Mark out of stock')).toBeDisabled()
expect(view.getByText('Mark in stock')).toBeDisabled()
})
it('AVSTOCK-06: Mark out sends the selected variants as out of stock', async () => {
const { view } = renderDialog()
fireEvent.press(view.getByText('Mark out of stock'))
await flush()
expect(lastMutationInput('admin.product.toggleOutOfStock')).toEqual({
id: 2,
skuIds: [11, 12],
isOutOfStock: true,
})
})
it('AVSTOCK-07: Mark in sends isOutOfStock false', async () => {
const { view } = renderDialog()
fireEvent.press(view.getByText('Mark in stock'))
await flush()
expect(lastMutationInput('admin.product.toggleOutOfStock')).toEqual({
id: 2,
skuIds: [11, 12],
isOutOfStock: false,
})
})
it('AVSTOCK-08: success shows a toast, applies and closes', async () => {
const { view, onClose, onApplied } = renderDialog()
fireEvent.press(view.getByText('Mark out of stock'))
await flush()
expect(Toast.show).toHaveBeenCalledWith(
expect.objectContaining({ type: 'success', text1: 'Stock updated' })
)
expect(onApplied).toHaveBeenCalled()
expect(onClose).toHaveBeenCalled()
})
it('AVSTOCK-09: a failed mutation shows an error toast and keeps the dialog open', async () => {
setProcedure('admin.product.toggleOutOfStock', { mode: 'error', error: new Error('nope') })
const { view, onClose, onApplied } = renderDialog()
fireEvent.press(view.getByText('Mark out of stock'))
await flush()
expect(Toast.show).toHaveBeenCalledWith(
expect.objectContaining({ type: 'error', text1: 'nope' })
)
expect(onApplied).not.toHaveBeenCalled()
expect(onClose).not.toHaveBeenCalled()
expect(view.getByText('Variants (2/2)')).toBeTruthy()
})
it('AVSTOCK-10: pending mutations disable the apply buttons', async () => {
setProcedure('admin.product.toggleOutOfStock', { mode: 'pending' })
const { view } = renderDialog()
fireEvent.press(view.getByText('Mark out of stock'))
await flush()
expect(view.getByText('Mark out of stock')).toBeDisabled()
expect(view.getByText('Mark in stock')).toBeDisabled()
})
it('AVSTOCK-11: Cancel only closes the dialog', async () => {
const { view, onClose } = renderDialog()
fireEvent.press(view.getByText('Cancel'))
await flush()
expect(onClose).toHaveBeenCalled()
expect(procedureMutationCalls('admin.product.toggleOutOfStock')).toHaveLength(0)
})
it('AVSTOCK-12: changing the product while open resets the selection', () => {
const { view } = renderDialog()
view.rerender(
<VariantStockDialog open product={P_CUCUMBER as any} onClose={jest.fn()} onApplied={jest.fn()} />
)
expect(view.getByText('Variants (1/1)')).toBeTruthy()
expect(view.getByTestId('variant-stock-13').props.accessibilityState.checked).toBe(true)
expect(view.queryByTestId('variant-stock-11')).toBeNull()
})
})

View file

@ -1,240 +1,183 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* VendorSnippetForm (components/VendorSnippetForm.tsx) — create/edit form for
* vendor snippets: snippet-code validation, slot + product selection, and the
* create/update mutations.
* Catalogue section 15 — VendorSnippetForm
* (`tests/components/vendor-snippet-form.test.tsx`).
*/
import React from 'react'
import { Alert } from 'react-native'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import { fireEvent } from '@testing-library/react-native'
jest.mock('@/components/context/staff-auth-context', () =>
require('../mocks/staff-auth-context')
)
import VendorSnippetForm from '@/components/VendorSnippetForm'
import { resetStorage, setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { renderWithProviders } from '../helpers/render'
import { __setStaffState } from '../mocks/staff-auth-context'
import { resetAllMocks } from '../helpers/reset'
import { flush, renderWithProviders } from '../helpers/test-utils'
import { lastMutationInput, procedureMutationCalls } from '../mocks/trpc-client'
import { SLOT_1, SNIPPET_1, STAFF } from '../fixtures'
const DELIVERY_TIME = '2026-12-31T10:00:00.000Z'
const SLOT_LABEL = new Date(DELIVERY_TIME).toLocaleString()
const slotsResponse = {
slots: [{ id: 1, deliveryTime: DELIVERY_TIME, freezeTime: '2026-12-30T10:00:00.000Z' }],
count: 1,
}
const skusResponse = {
skus: [{ id: 1, productId: 10, productName: 'Chicken', label: 'Chicken 1kg' }],
}
const onClose = jest.fn()
const onSuccess = jest.fn()
const renderForm = (snippet?: React.ComponentProps<typeof VendorSnippetForm>['snippet']) =>
renderWithProviders(
<VendorSnippetForm snippet={snippet} onClose={onClose} onSuccess={onSuccess} />
function renderForm(props: Partial<React.ComponentProps<typeof VendorSnippetForm>> = {}) {
return renderWithProviders(
<VendorSnippetForm onClose={jest.fn()} onSuccess={jest.fn()} {...props} />,
{ auth: 'in' }
)
}
describe('VendorSnippetForm', () => {
beforeEach(async () => {
await resetStorage()
onClose.mockClear()
onSuccess.mockClear()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
async function selectProduct(view: ReturnType<typeof renderForm>, label: string) {
fireEvent.press(view.getByText('Select products'))
fireEvent.press(view.getByText(label))
fireEvent.press(view.getByText('Done'))
}
describe('VendorSnippetForm (AVFORM-01..08)', () => {
beforeEach(() => {
resetAllMocks()
__setStaffState({ isLoggedIn: true, isLoading: false, staff: STAFF })
})
it('renders the create form with an auto-generated snippet code', async () => {
setupApiMocks({
procedures: {
'user.slots.getSlots': slotsResponse,
'common.product.getAllSkusSummary': skusResponse,
},
})
renderForm()
expect(screen.getByText('Create Vendor Snippet')).toBeVisible()
expect(screen.getByPlaceholderText('Enter snippet code')).toBeVisible()
expect(screen.getByText('Create Snippet')).toBeVisible()
await waitFor(() =>
expect(screen.getByPlaceholderText('Enter snippet code').props.value).toMatch(/^VS_/)
)
afterEach(() => {
jest.restoreAllMocks()
})
it('validates slot and product selection before submitting', async () => {
const api = setupApiMocks({
procedures: {
'user.slots.getSlots': slotsResponse,
'common.product.getAllSkusSummary': skusResponse,
},
})
renderForm()
it('AVFORM-01: renders code / slot / products / validTill / permanent fields', () => {
const view = renderForm()
fireEvent.press(screen.getByText('Create Snippet'))
expect(view.getByText('Create Vendor Snippet')).toBeTruthy()
expect(view.getByText('Snippet Code')).toBeTruthy()
expect(view.getByText('Is Permanent?')).toBeTruthy()
expect(view.getByText('Delivery Slot')).toBeTruthy()
expect(view.getByText('Choose a delivery slot')).toBeTruthy()
expect(view.getByText('Select products')).toBeTruthy()
expect(view.getByText('Valid Till (Optional)')).toBeTruthy()
expect(view.getByText('Create Snippet')).toBeTruthy()
expect(await screen.findByText('Slot selection is required')).toBeVisible()
expect(await screen.findByText('At least one product must be selected')).toBeVisible()
expect(procCount(api.fetchMock, 'admin.vendorSnippets.create')).toBe(0)
// A unique snippet code is generated on mount for new snippets.
const codeInput = view.getByPlaceholderText('Enter snippet code')
expect(String(codeInput.props.value)).toMatch(/^VS_\d+_[a-z0-9]+$/)
})
it('rejects a snippet code with invalid characters', async () => {
setupApiMocks({
procedures: {
'user.slots.getSlots': slotsResponse,
'common.product.getAllSkusSummary': skusResponse,
},
it('AVFORM-02: an empty code blocks submit with a validation message', async () => {
const view = renderForm()
fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), '')
fireEvent.press(view.getByText('Create Snippet'))
await flush()
expect(view.getByText('Snippet code is required')).toBeTruthy()
expect(procedureMutationCalls('admin.vendorSnippets.create')).toHaveLength(0)
})
it('AVFORM-03: submitting without products blocks the mutation', async () => {
const view = renderForm()
fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), 'CODE123')
fireEvent.press(view.getByText('Is Permanent?'))
fireEvent.press(view.getByText('Create Snippet'))
await flush()
expect(view.getByText('At least one product must be selected')).toBeTruthy()
expect(procedureMutationCalls('admin.vendorSnippets.create')).toHaveLength(0)
})
it('AVFORM-04: permanent snippets hide the delivery slot section', () => {
const view = renderForm()
expect(view.getByText('Delivery Slot')).toBeTruthy()
fireEvent.press(view.getByText('Is Permanent?'))
expect(view.queryByText('Delivery Slot')).toBeNull()
expect(view.queryByText('Select Slot')).toBeNull()
// validTill is not tied to the permanence toggle in the current form.
expect(view.getByText('Valid Till (Optional)')).toBeTruthy()
})
it('AVFORM-05: the product selector stores the selected SKU ids', async () => {
const view = renderForm()
await flush()
fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), 'CODE123')
fireEvent.press(view.getByText('Is Permanent?'))
fireEvent.press(view.getByText('Select products'))
fireEvent.press(view.getByText('Chicken Breast - 500g'))
fireEvent.press(view.getByText('Chicken Breast - 1kg'))
fireEvent.press(view.getByText('Done'))
expect(view.getByText('Chicken Breast - 500g, Chicken Breast - 1kg')).toBeTruthy()
fireEvent.press(view.getByText('Create Snippet'))
await flush()
expect(lastMutationInput('admin.vendorSnippets.create').skuIds).toEqual([11, 12])
})
it('AVFORM-06: create submits the exact payload and reports success', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const onClose = jest.fn()
const onSuccess = jest.fn()
const view = renderForm({ onClose, onSuccess })
await flush()
fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), 'MYCODE')
fireEvent.press(view.getByText('Choose a delivery slot'))
fireEvent.press(view.getByText(new Date(SLOT_1.deliveryTime).toLocaleString()))
await selectProduct(view, 'Chicken Breast - 500g')
fireEvent.press(view.getByText('Create Snippet'))
await flush()
expect(lastMutationInput('admin.vendorSnippets.create')).toEqual({
snippetCode: 'MYCODE',
slotId: 1849,
isPermanent: false,
skuIds: [11],
validTill: undefined,
})
renderForm()
expect(alertSpy).toHaveBeenCalledWith('Success', 'Vendor snippet created successfully')
expect(onSuccess).toHaveBeenCalledTimes(1)
expect(onClose).toHaveBeenCalledTimes(1)
})
fireEvent.changeText(
screen.getByPlaceholderText('Enter snippet code'),
'bad code!'
)
fireEvent.press(screen.getByText('Create Snippet'))
it('AVFORM-07: editing prefills the form and submits an update payload', async () => {
jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const onSuccess = jest.fn()
const view = renderForm({ snippet: SNIPPET_1 as any, onSuccess })
await flush()
expect(view.getByText('Edit Vendor Snippet')).toBeTruthy()
expect(view.getByDisplayValue('ABC123')).toBeTruthy()
// The existing SKU is shown as the current selection.
expect(view.getByText('Chicken Breast - 500g')).toBeTruthy()
expect(view.getByText(`Delivery Slot`)).toBeTruthy()
expect(
await screen.findByText(
'Snippet code can only contain letters, numbers, and underscores'
)
).toBeVisible()
})
view.getByText(new Date(SLOT_1.deliveryTime).toLocaleString())
).toBeTruthy()
it('creates a snippet with the selected slot and products', async () => {
const api = setupApiMocks({
procedures: {
'user.slots.getSlots': slotsResponse,
'common.product.getAllSkusSummary': skusResponse,
'admin.vendorSnippets.create': { id: 5 },
},
})
renderForm()
fireEvent.press(view.getByText('Update Snippet'))
await flush()
fireEvent.press(screen.getByText('Choose a delivery slot'))
fireEvent.press(await screen.findByText(SLOT_LABEL))
fireEvent.press(screen.getByText('Select products'))
fireEvent.press(await screen.findByText('Chicken 1kg'))
fireEvent.press(screen.getByText('Done'))
fireEvent.press(screen.getByText('Create Snippet'))
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.vendorSnippets.create'))
expect(lastProcedureInput(api.fetchMock, 'admin.vendorSnippets.create')).toEqual(
expect.objectContaining({
expect(lastMutationInput('admin.vendorSnippets.update')).toEqual({
id: 1,
updates: {
snippetCode: 'ABC123',
slotId: 1849,
isPermanent: false,
slotId: 1,
skuIds: [1],
})
)
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Success',
'Vendor snippet created successfully'
)
)
expect(onSuccess).toHaveBeenCalled()
expect(onClose).toHaveBeenCalled()
})
it('updates an existing snippet', async () => {
const api = setupApiMocks({
procedures: {
'user.slots.getSlots': slotsResponse,
'common.product.getAllSkusSummary': skusResponse,
'admin.vendorSnippets.update': { id: 3 },
skuIds: [11],
validTill: SNIPPET_1.validTill,
},
})
renderForm({
id: 3,
snippetCode: 'VS_EXISTING',
slotId: 2,
isPermanent: false,
skuIds: [7],
validTill: '2027-01-01T00:00:00.000Z',
createdAt: '2026-01-01T00:00:00.000Z',
})
expect(screen.getByText('Edit Vendor Snippet')).toBeVisible()
fireEvent.press(screen.getByText('Update Snippet'))
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.vendorSnippets.update'))
expect(lastProcedureInput(api.fetchMock, 'admin.vendorSnippets.update')).toEqual({
id: 3,
updates: expect.objectContaining({
snippetCode: 'VS_EXISTING',
slotId: 2,
isPermanent: false,
skuIds: [7],
validTill: '2027-01-01T00:00:00.000Z',
}),
})
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Success',
'Vendor snippet updated successfully'
)
)
expect(onSuccess).toHaveBeenCalledTimes(1)
})
it('allows a permanent snippet without a slot and hides the slot picker', async () => {
setupApiMocks({
procedures: {
'user.slots.getSlots': slotsResponse,
'common.product.getAllSkusSummary': skusResponse,
},
})
renderForm()
it('AVFORM-08: the close button calls onClose without saving', async () => {
const onClose = jest.fn()
const view = renderForm({ onClose })
expect(screen.getByText('Choose a delivery slot')).toBeVisible()
fireEvent.press(screen.getByText('Is Permanent?'))
fireEvent.press(view.getByText('✕'))
await flush()
await waitFor(() => expect(screen.queryByText('Choose a delivery slot')).toBeNull())
fireEvent.press(screen.getByText('Create Snippet'))
await waitFor(() =>
expect(screen.queryByText('Slot selection is required')).toBeNull()
)
})
it('shows an error alert when the mutation fails', async () => {
setupApiMocks({
procedures: {
'user.slots.getSlots': slotsResponse,
'common.product.getAllSkusSummary': skusResponse,
'admin.vendorSnippets.update': () => {
throw new Error('save failed')
},
},
})
renderForm({
id: 3,
snippetCode: 'VS_EXISTING',
slotId: 2,
isPermanent: false,
skuIds: [7],
validTill: null,
createdAt: '2026-01-01T00:00:00.000Z',
})
fireEvent.press(screen.getByText('Update Snippet'))
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Error', expect.any(String))
)
})
it('cancels through the close button', () => {
setupApiMocks({
procedures: {
'user.slots.getSlots': slotsResponse,
'common.product.getAllSkusSummary': skusResponse,
},
})
renderForm()
fireEvent.press(screen.getByText('✕'))
expect(onClose).toHaveBeenCalled()
expect(onClose).toHaveBeenCalledTimes(1)
expect(procedureMutationCalls('admin.vendorSnippets.create')).toHaveLength(0)
})
})

View file

@ -1,185 +0,0 @@
/**
* staff-auth-context (components/context/staff-auth-context.tsx) — the REAL
* provider. tests/setup.ts mocks this module globally, so it is unmocked here.
*
* It imports the `@/utils/queryClient` singleton (cleared between tests) and
* needs expo-router (mocked) plus the trpc/React Query provider stack.
*/
jest.unmock('@/components/context/staff-auth-context')
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { DeviceEventEmitter } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import { MyText, MyTouchableOpacity } from 'common-ui'
import {
StaffAuthProvider,
useStaffAuth,
} from '@/components/context/staff-auth-context'
import { getJWT, saveJWT } from '@/hooks/useJWT'
import queryClient from '@/utils/queryClient'
import { FORCE_LOGOUT_EVENT } from 'common-ui/src/lib/const-strs'
import { resetStorage, setupApiMocks } from '../mocks/api'
import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures'
import { resetRouterMock, routerMock } from '../mocks/router'
import { renderWithProviders } from '../helpers/render'
type Auth = ReturnType<typeof useStaffAuth>
const authSpy = jest.fn<void, [Auth]>()
function Consumer() {
const auth = useStaffAuth()
authSpy(auth)
return (
<>
<MyTouchableOpacity testID="login" onPress={() => auth.login('shafi', 'secret')}>
<MyText>login</MyText>
</MyTouchableOpacity>
<MyTouchableOpacity testID="logout" onPress={() => auth.logout()}>
<MyText>logout</MyText>
</MyTouchableOpacity>
</>
)
}
const lastAuth = (): Auth => authSpy.mock.calls[authSpy.mock.calls.length - 1][0]
const renderProvider = () =>
renderWithProviders(
<StaffAuthProvider>
<Consumer />
</StaffAuthProvider>
)
const trpcErrorResponse = (message: string) => [
{ error: { message, code: -32600, data: { code: 'UNAUTHORIZED', httpStatus: 401 } } },
]
describe('staff-auth-context (real provider)', () => {
beforeEach(async () => {
authSpy.mockClear()
queryClient.clear()
resetRouterMock()
await resetStorage()
setupApiMocks({
procedures: {
'admin.staffUser.login': { token: 'jwt-abc', staff: { id: 1, name: 'shafi' } },
},
})
})
it('redirects to /login when there is no token', async () => {
renderProvider()
await waitFor(() => expect(routerMock.replace).toHaveBeenCalledWith('/login'))
await waitFor(() => expect(lastAuth().isLoading).toBe(false))
expect(lastAuth().isLoggedIn).toBe(false)
expect(lastAuth().staff).toBeNull()
})
it('marks the session logged in when a token exists', async () => {
await saveJWT('existing-token')
renderProvider()
await waitFor(() => expect(lastAuth().isLoggedIn).toBe(true))
expect(lastAuth().isLoading).toBe(false)
expect(routerMock.replace).not.toHaveBeenCalled()
})
it('login saves the JWT, sets staff and routes to the dashboard', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'admin.staffUser.login': { token: 'jwt-abc', staff: { id: 7, name: 'shafi' } },
},
})
renderProvider()
await waitFor(() => expect(lastAuth().isLoading).toBe(false))
fireEvent.press(screen.getByTestId('login'))
await waitFor(() =>
expect(routerMock.replace).toHaveBeenCalledWith('/(drawer)/dashboard')
)
await waitFor(async () => expect(await getJWT()).toBe('jwt-abc'))
expect(lastAuth().staff).toEqual({ id: 7, name: 'shafi' })
expect(lastAuth().isLoggedIn).toBe(true)
expect(lastAuth().loginError).toBeNull()
expectProcedureCalled(fetchMock, 'admin.staffUser.login', { times: 1 })
expect(lastProcedureInput(fetchMock, 'admin.staffUser.login')).toEqual({
name: 'shafi',
password: 'secret',
})
})
it('login sets loginError when the backend rejects', async () => {
setupApiMocks()
;(global as unknown as { fetch: unknown }).fetch = jest.fn(async () => ({
ok: true,
status: 200,
statusText: 'OK',
headers: new Map(),
url: '',
json: async () => trpcErrorResponse('Invalid credentials'),
text: async () => JSON.stringify(trpcErrorResponse('Invalid credentials')),
}))
renderProvider()
await waitFor(() => expect(lastAuth().isLoading).toBe(false))
fireEvent.press(screen.getByTestId('login'))
await waitFor(() => expect(lastAuth().loginError).toBe('Invalid credentials'))
expect(lastAuth().isLoggedIn).toBe(false)
expect(routerMock.replace).not.toHaveBeenCalledWith('/(drawer)/dashboard')
})
it('logout deletes the JWT, clears the query cache and routes to /login', async () => {
await saveJWT('existing-token')
const clearSpy = jest.spyOn(queryClient, 'clear')
renderProvider()
await waitFor(() => expect(lastAuth().isLoggedIn).toBe(true))
fireEvent.press(screen.getByTestId('logout'))
await waitFor(() => expect(routerMock.replace).toHaveBeenCalledWith('/login'))
await waitFor(async () => expect(await getJWT()).toBeNull())
expect(clearSpy).toHaveBeenCalled()
expect(lastAuth().isLoggedIn).toBe(false)
expect(lastAuth().staff).toBeNull()
})
it('FORCE_LOGOUT_EVENT logs the staff member out', async () => {
await saveJWT('existing-token')
renderProvider()
await waitFor(() => expect(lastAuth().isLoggedIn).toBe(true))
await act(async () => {
DeviceEventEmitter.emit(FORCE_LOGOUT_EVENT)
})
await waitFor(() => expect(routerMock.replace).toHaveBeenCalledWith('/login'))
await waitFor(async () => expect(await getJWT()).toBeNull())
expect(lastAuth().isLoggedIn).toBe(false)
})
it('useStaffAuth throws when used outside the provider', () => {
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {})
expect(() => renderWithProviders(<Consumer />)).toThrow(
'useStaffAuth must be used within a StaffAuthProvider'
)
consoleError.mockRestore()
})
})

571
apps/admin-ui/tests/fixtures/index.ts vendored Normal file
View file

@ -0,0 +1,571 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Backend-shaped fixtures used across the admin-ui suite.
*
* Shapes mirror `@packages/shared` (AdminProductWithRelations, AdminSku,
* AdminOrderListItem, AdminSlotWithProducts, Coupon, …) so the API mock can feed
* the pages the same payloads the real procedures return.
*/
/* -------------------------------------------------------------------------- */
/* Regions, staff, bounds, settings */
/* -------------------------------------------------------------------------- */
export const REGION = {
id: 1,
name: 'Mahabubnagar',
description: 'Region one',
effectiveBoundId: 7,
}
export const REGION_2 = {
id: 2,
name: 'Hyderabad',
description: 'Region two',
effectiveBoundId: 8,
}
export const STAFF = { id: 3, name: 'Admin One', regionId: 1, regionName: 'Mahabubnagar' }
export const STAFF_NO_REGION = { id: 4, name: 'Unassigned', regionId: 0 }
/** A decodable (unverified) JWT used for the staff session. */
export const TEST_JWT = `header.${Buffer.from(JSON.stringify({ id: 3, name: 'Admin One' })).toString('base64url')}.signature`
export const B1 = { id: 7, regionId: 1, priority: 1, name: 'Bound 1' }
export const B2 = { id: 8, regionId: 1, priority: 10, name: 'Bound 2' }
export const BOUNDS = [B1, B2]
export const BOUND_SETTINGS = {
freeDeliveryThreshold: '249',
deliveryCharge: '15',
flashFreeDeliveryThreshold: '199',
flashDeliveryCharge: '25',
isFlashDeliveryEnabled: 'true',
}
export const REGION_CONSTANTS = {
popularItems: '[2,5]',
allItemsOrder: '[2,5,7]',
supportMobile: '8688182552',
supportEmail: 'support@freshyo.in',
welcomeMessage: 'Welcome',
tagsOrder: '[1,2]',
}
/* -------------------------------------------------------------------------- */
/* Stores */
/* -------------------------------------------------------------------------- */
export const STORE_1 = {
id: 1,
name: 'The Freshyo Meat House',
description: 'Fresh meat and produce',
imageUrl: 'https://assets.test/store1.jpg',
isGlobal: false,
productCount: 12,
createdAt: new Date().toISOString(),
}
export const STORE_GLOBAL = {
id: 2,
name: 'Freshyo Central',
description: 'Shared across regions',
imageUrl: null,
isGlobal: true,
productCount: 4,
createdAt: new Date().toISOString(),
}
export const STORES = [STORE_1, STORE_GLOBAL]
/* -------------------------------------------------------------------------- */
/* Products */
/* -------------------------------------------------------------------------- */
const sku = (over: Partial<any> = {}) => ({
id: 11,
productId: 2,
name: null,
price: '215',
marketPrice: '220',
images: ['chicken.jpg'],
imageKeys: ['product-images/chicken.jpg'],
isOutOfStock: false,
isSuspended: false,
isSuspendedInRegion: false,
isFlashAvailable: false,
flashPrice: null,
isOffer: false,
isComboOnly: false,
isDeleted: false,
createdAt: new Date().toISOString(),
features: [{ id: 1, skuId: 11, featureName: 'quantity', featureValue: '500g' }],
comboItems: [],
...over,
})
/** Product 2 — 2 SKUs, both in stock. */
export const P_CHICKEN = {
id: 2,
name: 'Chicken Breast',
shortDescription: 'Tender boneless breast',
longDescription: 'Tender boneless chicken breast.',
storeId: 1,
incrementStep: 1,
createdAt: new Date().toISOString(),
productType: 'item',
isGlobal: false,
store: STORE_1,
skus: [
sku({ id: 11, productId: 2, features: [{ id: 1, skuId: 11, featureName: 'quantity', featureValue: '500g' }] }),
sku({ id: 12, productId: 2, name: 'Chicken Breast 1kg', price: '410', features: [{ id: 2, skuId: 12, featureName: 'quantity', featureValue: '1kg' }] }),
],
}
/** Product 5 — 1 SKU, in stock. */
export const P_CUCUMBER = {
id: 5,
name: 'Cucumber',
shortDescription: 'Farm fresh cucumbers',
longDescription: 'Farm fresh cucumbers.',
storeId: 1,
incrementStep: 1,
createdAt: new Date().toISOString(),
productType: 'item',
isGlobal: false,
store: STORE_1,
skus: [
sku({ id: 13, productId: 5, price: '15', marketPrice: '20', images: ['cucumber.jpg'], features: [{ id: 3, skuId: 13, featureName: 'quantity', featureValue: '500g' }] }),
],
}
/** Product 9 — global, single SKU 91. */
export const P_GLOBAL = {
id: 9,
name: 'Global Paneer',
shortDescription: 'Shared paneer',
longDescription: 'Shared paneer.',
storeId: 2,
incrementStep: 1,
createdAt: new Date().toISOString(),
productType: 'item',
isGlobal: true,
store: STORE_GLOBAL,
skus: [
sku({ id: 91, productId: 9, price: '90', marketPrice: '100', images: ['paneer.jpg'], features: [{ id: 4, skuId: 91, featureName: 'quantity', featureValue: '200g' }] }),
],
}
/** Product 6 — all SKUs out of stock. */
export const P_OUT = {
id: 6,
name: 'Mutton',
shortDescription: 'Fresh mutton',
longDescription: 'Fresh mutton.',
storeId: 1,
incrementStep: 1,
createdAt: new Date().toISOString(),
productType: 'item',
isGlobal: false,
store: STORE_1,
skus: [sku({ id: 61, productId: 6, price: '400', isOutOfStock: true, features: [{ id: 5, skuId: 61, featureName: 'quantity', featureValue: '500g' }] })],
}
/** Product 7 — no images. */
export const P_NO_IMAGE = {
id: 7,
name: 'No Image Item',
shortDescription: '',
longDescription: '',
storeId: 1,
incrementStep: 1,
createdAt: new Date().toISOString(),
productType: 'item',
isGlobal: false,
store: STORE_1,
skus: [sku({ id: 71, productId: 7, price: '10', marketPrice: null, images: [], imageKeys: [], features: [{ id: 6, skuId: 71, featureName: 'quantity', featureValue: '1pc' }] })],
}
export const P_PARTIAL = {
id: 8,
name: 'Mixed Stock',
shortDescription: 'One in, one out',
longDescription: '',
storeId: 1,
incrementStep: 1,
createdAt: new Date().toISOString(),
productType: 'item',
isGlobal: false,
store: STORE_1,
skus: [
sku({ id: 81, productId: 8, isOutOfStock: false, features: [{ id: 7, skuId: 81, featureName: 'quantity', featureValue: '250g' }] }),
sku({ id: 82, productId: 8, isOutOfStock: true, features: [{ id: 8, skuId: 82, featureName: 'quantity', featureValue: '500g' }] }),
],
}
export const PRODUCTS = [P_CHICKEN, P_CUCUMBER, P_GLOBAL, P_OUT, P_NO_IMAGE, P_PARTIAL]
export const PRODUCTS_RESPONSE = { products: PRODUCTS, count: PRODUCTS.length }
/** SKU summaries for ProductsSelector / getAllSkusSummary. */
export const SKUS_SUMMARY = [
{ id: 11, productId: 2, productName: 'Chicken Breast', label: 'Chicken Breast - 500g', images: ['chicken.jpg'], storeId: 1, price: '215' },
{ id: 12, productId: 2, productName: 'Chicken Breast', label: 'Chicken Breast - 1kg', images: ['chicken.jpg'], storeId: 1, price: '410' },
{ id: 13, productId: 5, productName: 'Cucumber', label: 'Cucumber - 500g', images: ['cucumber.jpg'], storeId: 1, price: '15' },
{ id: 91, productId: 9, productName: 'Global Paneer', label: 'Global Paneer - 200g', images: ['paneer.jpg'], storeId: 2, price: '90' },
]
export const PRODUCTS_SUMMARY = {
products: PRODUCTS.map((p) => ({
id: p.id,
name: p.name,
shortDescription: p.shortDescription,
images: p.skus?.[0]?.images ?? [],
})),
}
export const STORES_SUMMARY = { stores: STORES }
/* -------------------------------------------------------------------------- */
/* Slots */
/* -------------------------------------------------------------------------- */
const HOUR = 60 * 60 * 1000
const iso = (offsetMs: number) => new Date(Date.now() + offsetMs).toISOString()
export const SLOT_1 = {
id: 1849,
deliveryTime: iso(2 * HOUR),
freezeTime: iso(1 * HOUR),
isActive: true,
isFlash: false,
isCapacityFull: false,
deliverySequence: [],
groupIds: [],
products: [P_CHICKEN.skus[0] ? { id: 2, name: 'Chicken Breast', images: ['chicken.jpg'] } : null, { id: 5, name: 'Cucumber', images: ['cucumber.jpg'] }],
}
export const SLOT_FULL = { ...SLOT_1, id: 1850, isCapacityFull: true, deliveryTime: iso(4 * HOUR), freezeTime: iso(3 * HOUR) }
export const SLOT_INACTIVE = { ...SLOT_1, id: 1851, isActive: false, deliveryTime: iso(6 * HOUR), freezeTime: iso(5 * HOUR) }
export const SLOTS = [SLOT_1, SLOT_FULL, SLOT_INACTIVE]
export const SLOTS_RESPONSE = { slots: SLOTS, count: SLOTS.length }
export const SLOT_DETAIL = {
...SLOT_1,
deliverySequence: [101, 102],
groupIds: [1],
vendorSnippets: [
{ id: 1, snippetCode: 'ABC123', slotId: 1849, skuIds: [11], isPermanent: false, validTill: iso(24 * HOUR), createdAt: iso(0), accessUrl: 'https://access.test/ABC123' },
],
}
/* -------------------------------------------------------------------------- */
/* Orders */
/* -------------------------------------------------------------------------- */
const ORDER_ITEMS = [
{ id: 1, productId: 2, name: 'Chicken Breast', amount: 430, quantity: 2, price: 215, unit: '500g', productSize: 500, isPackaged: false, isPackageVerified: false, is_packaged: false, is_package_verified: false, skuName: 'Chicken Breast - 500g', features: [{ featureName: 'quantity', featureValue: '500g' }] },
{ id: 2, productId: 5, name: 'Cucumber', amount: 15, quantity: 1, price: 15, unit: '500g', productSize: 500, isPackaged: true, isPackageVerified: false, is_packaged: true, is_package_verified: false, skuName: 'Cucumber - 500g', features: [{ featureName: 'quantity', featureValue: '500g' }] },
]
export const ORDER_1 = {
id: 11,
orderId: 'ORD-1011',
readableId: 101,
userId: 5,
customerName: 'Test User',
customerMobile: '9876543210',
address: '12 Main Road, Mahabubnagar',
addressId: 11,
latitude: 17,
longitude: 78,
totalAmount: 445,
deliveryCharge: 15,
items: ORDER_ITEMS,
createdAt: new Date().toISOString(),
deliveryTime: iso(2 * HOUR),
status: 'pending',
isPackaged: false,
isDelivered: false,
isFlashDelivery: false,
userNotes: null,
adminNotes: null,
userNegativityScore: 0,
}
export const ORDER_FLASH = { ...ORDER_1, id: 12, orderId: 'ORD-1012', readableId: 102, isFlashDelivery: true, deliveryCharge: 0 }
export const ORDER_DELIVERED = { ...ORDER_1, id: 13, orderId: 'ORD-1013', readableId: 103, status: 'delivered', isDelivered: true, isPackaged: true }
export const ORDER_CANCELLED = { ...ORDER_1, id: 14, orderId: 'ORD-1014', readableId: 104, status: 'cancelled' }
export const ORDER_NEGATIVE = { ...ORDER_1, id: 15, orderId: 'ORD-1015', readableId: 105, userNegativityScore: 5 }
export const ORDERS = [ORDER_1, ORDER_FLASH, ORDER_DELIVERED, ORDER_CANCELLED, ORDER_NEGATIVE]
export const ORDERS_RESPONSE = { orders: ORDERS }
export const ORDER_DETAILS = {
id: 11,
readableId: 101,
userId: 5,
customerName: 'Test User',
customerEmail: 'test@example.com',
customerMobile: '9876543210',
address: { name: 'Home', line1: '12 Main Road', line2: null, city: 'Mahabubnagar', state: 'Telangana', phone: '9876543210' },
slotInfo: { time: iso(2 * HOUR), sequence: 1 },
totalAmount: 445,
deliveryCharge: 15,
adminNotes: null,
userNotes: null,
createdAt: new Date().toISOString(),
status: 'pending',
isPackaged: false,
isDelivered: false,
items: ORDER_ITEMS.map((i) => ({ ...i, quantity: String(i.quantity), price: String(i.price) })),
cancelReason: null,
cancellationReviewed: false,
couponData: null,
couponCode: null,
couponDescription: null,
discountAmount: null,
orderStatus: {
id: 1,
orderTime: new Date().toISOString(),
userId: 5,
orderId: 11,
isPackaged: false,
isDelivered: false,
isCancelled: false,
cancelReason: null,
isCancelledByAdmin: null,
cancellationUserNotes: null,
cancellationAdminNotes: null,
cancellationReviewed: false,
cancellationReviewedAt: null,
},
isFlashDelivery: false,
}
export const SLOT_ORDERS = [
{ ...ORDER_1, address: '12 Main Road, Mahabubnagar', items: ORDER_ITEMS, slotId: 1849, deliveryTime: iso(2 * HOUR) },
]
/* -------------------------------------------------------------------------- */
/* Users */
/* -------------------------------------------------------------------------- */
export const USER_1 = {
id: 5,
name: 'Test User',
mobile: '9876543210',
isSuspended: false,
totalOrders: 3,
createdAt: new Date().toISOString(),
lastOrderDate: new Date().toISOString(),
}
export const USER_SUSPENDED = { ...USER_1, id: 6, name: 'Suspended', mobile: '9876543211', isSuspended: true, totalOrders: 0, lastOrderDate: null }
export const USER_NO_NAME = { ...USER_1, id: 7, name: null, mobile: null, totalOrders: 0, lastOrderDate: null }
export const USERS = [USER_1, USER_SUSPENDED, USER_NO_NAME]
export const USERS_RESPONSE = { users: USERS, nextCursor: undefined }
export const USER_DETAILS = {
...USER_1,
email: 'test@example.com',
orders: [ORDER_1, ORDER_DELIVERED],
}
export const USER_INCIDENTS = [
{ id: 1, userId: 5, orderId: 11, dateAdded: new Date().toISOString(), adminComment: 'Late delivery', addedBy: { name: 'Admin One' }, negativityScore: 2, order: { orderStatus: [{ isCancelled: false }] } },
]
export const NOTIFICATION_USERS = [
{ id: 5, name: 'Test User', mobile: '9876543210' },
{ id: 6, name: 'Second User', mobile: '9876543211' },
]
/* -------------------------------------------------------------------------- */
/* Coupons */
/* -------------------------------------------------------------------------- */
export const COUPON_1 = {
id: 21,
couponCode: 'SAVE10',
discountPercent: '10',
maxValue: 50,
minOrder: null,
flatDiscount: null,
validTill: null,
isApplyForAll: true,
isInvalidated: false,
skuIds: [],
applicableUsers: [],
isExclusive: false,
firstOrderOnly: false,
exclusiveApply: false,
isFirstOrderOnly: false,
regionId: 1,
maxLimitForUser: null,
usedCount: 0,
createdAt: '2026-01-01T00:00:00.000Z',
creator: { id: 1, name: 'Admin One', mobile: '9999999999' },
}
export const COUPON_GLOBAL = { ...COUPON_1, id: 22, couponCode: 'GLOBAL10', isApplyForAll: true, regionId: null }
export const COUPON_EXPIRED = { ...COUPON_1, id: 23, couponCode: 'OLD', validTill: iso(-24 * HOUR) }
export const COUPON_INVALIDATED = { ...COUPON_1, id: 24, couponCode: 'DEAD', isInvalidated: true }
export const COUPON_RESERVED = { ...COUPON_1, id: 25, couponCode: 'RES10' }
export const COUPONS = [COUPON_1, COUPON_GLOBAL, COUPON_EXPIRED, COUPON_INVALIDATED]
export const COUPONS_RESPONSE = { coupons: COUPONS, count: COUPONS.length, nextCursor: undefined }
export const RESERVED_COUPONS = [
{ ...COUPON_RESERVED, secretCode: 'SECRET123', isRedeemed: false, redeemedBy: null, createdBy: 'Admin One' },
]
export const RESERVED_COUPONS_RESPONSE = { coupons: RESERVED_COUPONS, count: 1, nextCursor: undefined }
/* -------------------------------------------------------------------------- */
/* Product tags / groups */
/* -------------------------------------------------------------------------- */
export const TAG_1 = {
id: 1,
tagName: 'Chicken',
tagDescription: 'All chicken items',
imageUrl: 'https://assets.test/tag1.jpg',
isDashboardTag: true,
relatedStores: [1],
sortOrder: [],
createdAt: new Date().toISOString(),
products: [],
productIds: [2],
}
export const TAG_2 = {
id: 2,
tagName: 'Veg',
tagDescription: null,
imageUrl: null,
isDashboardTag: false,
relatedStores: [1],
sortOrder: [],
createdAt: new Date().toISOString(),
products: [],
productIds: [5],
}
export const TAGS = [TAG_1, TAG_2]
export const TAGS_RESPONSE = { tags: TAGS }
export const GROUP_1 = {
id: 1,
groupName: 'Breakfast',
description: 'Morning items',
createdAt: new Date().toISOString(),
products: [P_CHICKEN.skus[0], P_CUCUMBER.skus[0]],
productCount: 2,
}
export const GROUPS = [GROUP_1]
export const GROUPS_RESPONSE = { groups: GROUPS }
/* -------------------------------------------------------------------------- */
/* Banners */
/* -------------------------------------------------------------------------- */
export const BANNER_1 = {
id: 1,
name: 'Dash Banner',
description: 'Top banner',
imageUrl: 'https://assets.test/banner1.jpg',
skuIds: [11],
redirectUrl: null,
serialNumber: 1,
isActive: true,
}
export const BANNERS = [BANNER_1]
export const BANNERS_RESPONSE = { banners: BANNERS, count: BANNERS.length }
/* -------------------------------------------------------------------------- */
/* Vendor snippets */
/* -------------------------------------------------------------------------- */
export const SNIPPET_1 = {
id: 1,
snippetCode: 'ABC123',
slotId: 1849,
skuIds: [11],
isPermanent: false,
validTill: iso(24 * HOUR),
createdAt: iso(0),
accessUrl: 'https://access.test/ABC123',
slot: SLOT_1,
products: [{ id: 11, name: 'Chicken Breast - 500g' }],
}
export const SNIPPETS = [SNIPPET_1]
export const SNIPPETS_RESPONSE = { snippets: SNIPPETS, count: SNIPPETS.length }
export const SNIPPET_ORDERS = {
success: true,
data: [
{
orderId: 'ORD-1011',
orderDate: iso(0),
customerName: 'Test User',
totalAmount: 445,
slotInfo: { time: iso(2 * HOUR), sequence: 1 },
products: [
{ orderItemId: 1, productId: 2, productName: 'Chicken Breast', quantity: 2, productSize: 500, price: 215, unit: '500g', subtotal: 430, is_packaged: false, is_package_verified: false },
],
matchedProducts: [2],
snippetCode: 'ABC123',
},
],
snippet: { id: 1, snippetCode: 'ABC123', slotId: 1849, skuIds: [11], createdAt: iso(0), isPermanent: false },
}
/* -------------------------------------------------------------------------- */
/* Complaints */
/* -------------------------------------------------------------------------- */
export const COMPLAINT_1 = {
id: 1,
userId: 5,
orderId: 11,
complaintBody: 'Late delivery',
complaintImages: [],
complaintStatus: 'pending',
complaintResponse: null,
createdAt: new Date().toISOString(),
regionId: 1,
user: { id: 5, name: 'Test User', mobile: '9876543210' },
}
export const COMPLAINT_2 = {
...COMPLAINT_1,
id: 2,
orderId: null,
complaintBody: 'App issue',
complaintImages: ['issue.jpg'],
complaintStatus: 'resolved',
complaintResponse: 'We fixed it',
}
export const COMPLAINTS = [COMPLAINT_1, COMPLAINT_2]
export const COMPLAINTS_RESPONSE = { complaints: COMPLAINTS, count: COMPLAINTS.length }
/* -------------------------------------------------------------------------- */
/* Uploads */
/* -------------------------------------------------------------------------- */
export const UPLOAD_URLS_RESPONSE = {
uploadUrls: ['https://upload.test/meatfarmer/product-images/img-1.jpg'],
}
export const PRODUCT_REVIEWS = {
reviews: [
{ id: 1, reviewBody: 'Great', ratings: 5, reviewTime: iso(0), userName: 'A', imageUrls: [], adminResponse: null, adminResponseImages: [], signedImageUrls: [], signedAdminImageUrls: [] },
{ id: 2, reviewBody: 'Okay', ratings: 3, reviewTime: iso(0), userName: 'B', imageUrls: [], adminResponse: 'Thanks', adminResponseImages: [], signedImageUrls: [], signedAdminImageUrls: [] },
],
hasMore: false,
}

View file

@ -1,52 +0,0 @@
/**
* Provider stack shared by the admin-ui tests.
*
* Mirrors app/_layout.tsx minus the native wrappers: trpc + React Query +
* Refresh. StaffAuthProvider is mocked globally in tests/setup.ts, so screens
* that read the session mount without it; real-provider tests render it
* explicitly.
*/
import React from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render } from '@testing-library/react-native'
import { RefreshProvider } from 'common-ui'
import { trpc, trpcClient } from '@/src/trpc-client'
export function createQueryClient() {
return new QueryClient({
defaultOptions: { queries: { retry: false, gcTime: 0 } },
})
}
export interface ProviderOptions {
/** Reuse a specific query client (e.g. to assert refetches). */
queryClient?: QueryClient
}
export function Providers({
children,
queryClient,
}: { children?: React.ReactNode } & ProviderOptions) {
const client = React.useMemo(
() => queryClient ?? createQueryClient(),
[queryClient]
)
return (
<trpc.Provider client={trpcClient} queryClient={client}>
<QueryClientProvider client={client}>
<RefreshProvider queryClient={client}>{children}</RefreshProvider>
</QueryClientProvider>
</trpc.Provider>
)
}
/** Render a screen/component inside the standard provider stack. */
export function renderWithProviders(
ui: React.ReactElement,
options?: ProviderOptions
) {
return render(<Providers {...options}>{ui}</Providers>)
}

View file

@ -0,0 +1,28 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Reset helpers. Call `resetAllMocks()` in `beforeEach` so no storage key,
* procedure fixture, navigation spy or auth state leaks between cases.
*/
import { resetTrpcMocks, seedDefaultProcedures } from '../mocks/trpc-client'
import { __reset as resetSecureStore } from '../mocks/secure-store-mock'
import { __reset as resetNotifications } from '../mocks/expo-notifications-mock'
import { __resetRouterMock } from '../mocks/expo-router-mock'
import { __resetStaffState } from '../mocks/staff-auth-context'
import queryClient from '@/utils/queryClient'
export function resetStores() {
queryClient.clear()
}
export function resetAllMocks() {
jest.clearAllMocks()
jest.useRealTimers()
resetStores()
resetTrpcMocks()
resetSecureStore()
resetNotifications()
__resetRouterMock()
__resetStaffState()
}
export { seedDefaultProcedures }

View file

@ -0,0 +1,112 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import * as React from 'react'
import { render as rtlRender, RenderResult } from '@testing-library/react-native'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { RefreshProvider } from 'common-ui'
import { trpc, trpcClient } from '@/src/trpc-client'
import { recordQueryInvalidation } from '../mocks/trpc-client'
import { StaffAuthProvider } from '@/components/context/staff-auth-context'
import { __set as setSecureItem, __delete as deleteSecureItem } from '../mocks/secure-store-mock'
import { STAFF, TEST_JWT } from '../fixtures'
export function createTestQueryClient(): QueryClient {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
gcTime: Infinity,
staleTime: Infinity,
refetchOnWindowFocus: false,
},
mutations: { retry: false },
},
})
const originalInvalidate = queryClient.invalidateQueries.bind(queryClient)
;(queryClient as any).invalidateQueries = ((filters?: any, options?: any) => {
recordQueryInvalidation(filters)
return originalInvalidate(filters, options)
}) as any
return queryClient
}
type AuthMode = 'in' | 'out' | false
export interface RenderOptions {
queryClient?: QueryClient
auth?: AuthMode
withRefresh?: boolean
withAuth?: boolean
}
/** Persist (or clear) the staff session the real StaffAuthProvider bootstraps from. */
export function seedAuthStorage(mode: AuthMode, staff = STAFF, token = TEST_JWT) {
if (mode === 'in') {
setSecureItem('jwt_token', token)
setSecureItem('staff_session', JSON.stringify(staff))
} else {
deleteSecureItem('jwt_token')
deleteSecureItem('staff_session')
}
}
export interface RenderWithProvidersResult extends RenderResult {
queryClient: QueryClient
}
export function renderWithProviders(
ui: React.ReactElement,
options: RenderOptions = {}
): RenderWithProvidersResult {
const queryClient = options.queryClient ?? createTestQueryClient()
const auth = options.auth ?? 'out'
const withRefresh = options.withRefresh ?? true
const withAuth = options.withAuth ?? true
if (auth !== false) {
// Synchronous seeding so AuthProvider's bootstrap effect reads the token.
seedAuthStorage(auth)
}
const Wrapper = ({ children }: { children: React.ReactNode }) => {
let tree: React.ReactElement = React.createElement(React.Fragment, null, children)
if (withAuth && auth !== false) {
tree = React.createElement(StaffAuthProvider, null, tree)
}
if (withRefresh) {
tree = React.createElement(RefreshProvider, { queryClient, children: tree } as any)
}
tree = React.createElement(trpc.Provider, { client: trpcClient, queryClient, children: tree })
tree = React.createElement(QueryClientProvider, { client: queryClient }, tree)
return tree
}
const result = rtlRender(ui, { wrapper: Wrapper })
return { ...result, queryClient }
}
/** Render and let queued effects / microtasks settle. */
export async function renderAndFlush(
ui: React.ReactElement,
options: RenderOptions = {}
): Promise<RenderWithProvidersResult> {
const result = renderWithProviders(ui, options)
await flush()
return result
}
/** Await a macrotask so promise chains and effects settle. */
export async function flush(times = 2) {
const { act } = require('@testing-library/react-native')
for (let index = 0; index < times; index += 1) {
// eslint-disable-next-line no-await-in-loop
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0))
})
}
}
export function setConsoleErrorMock() {
return jest.spyOn(console, 'error').mockImplementation(() => undefined)
}

View file

@ -1,41 +0,0 @@
/**
* useJWT (hooks/useJWT.ts) — secure-store token persistence.
*
* StorageService is globally mocked by tests/setup.ts with an in-memory map;
* resetStorage() clears the `jwt_token` slot between tests.
*/
import { StorageService } from 'common-ui'
import { deleteJWT, getJWT, JWT_KEY, saveJWT } from '@/hooks/useJWT'
import { resetStorage } from '../mocks/api'
describe('useJWT', () => {
beforeEach(async () => {
await resetStorage()
})
it('uses the jwt_token storage key', () => {
expect(JWT_KEY).toBe('jwt_token')
})
it('returns null when no token has been stored', async () => {
await expect(getJWT()).resolves.toBeNull()
})
it('saves a token under JWT_KEY and reads it back', async () => {
await saveJWT('token-abc')
expect(StorageService.setItem).toHaveBeenCalledWith('jwt_token', 'token-abc')
await expect(getJWT()).resolves.toBe('token-abc')
})
it('deletes the stored token', async () => {
await saveJWT('token-abc')
await deleteJWT()
expect(StorageService.removeItem).toHaveBeenCalledWith('jwt_token')
await expect(getJWT()).resolves.toBeNull()
})
})

View file

@ -1,231 +0,0 @@
/**
* useUploadToObjectStorage (hooks/useUploadToObjectStore.ts) — requests
* presigned URLs from `common.generateUploadUrls`, then PUTs each image in
* parallel and extracts the object key from the presigned URL.
*
* Fake timers: mutations are driven with act() + waitFor(), never awaited
* directly (see tests/screens/login.test.tsx for the pattern).
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { act, renderHook, waitFor } from '@testing-library/react-native'
import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore'
import { resetStorage, setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { Providers } from '../helpers/render'
const wrapper = ({ children }: { children?: React.ReactNode }) => (
<Providers>{children}</Providers>
)
const presigned = (key: string) =>
`https://meatfarmer.s3.amazonaws.com/meatfarmer/${key}`
const blob = {} as Blob
const jpeg = { blob, mimeType: 'image/jpeg' }
const png = { blob, mimeType: 'image/png' }
/** Kick off `upload` without awaiting it (fake timers would deadlock). */
const startUpload = (
result: { current: ReturnType<typeof useUploadToObjectStorage> },
input: Parameters<ReturnType<typeof useUploadToObjectStorage>['upload']>[0]
) => {
let promise: Promise<unknown> = Promise.resolve()
act(() => {
promise = result.current.upload(input)
promise.catch(() => {})
})
return promise
}
describe('useUploadToObjectStorage', () => {
beforeEach(async () => {
await resetStorage()
})
it('requests one presigned URL per image and uploads them in parallel', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'common.generateUploadUrls': {
uploadUrls: [
presigned('product-images/a.jpg'),
presigned('product-images/b.png'),
],
},
},
})
const { result } = renderHook(() => useUploadToObjectStorage(), { wrapper })
const promise = startUpload(result, {
images: [jpeg, png],
contextString: 'product_info',
})
await waitFor(() => expect(result.current.isUploading).toBe(false))
const uploaded = await promise
expectProcedureCalled(fetchMock, 'common.generateUploadUrls', { times: 1 })
expect(lastProcedureInput(fetchMock, 'common.generateUploadUrls')).toEqual({
contextString: 'product_info',
mimeTypes: ['image/jpeg', 'image/png'],
})
expect(uploaded).toEqual({
keys: ['product-images/a.jpg', 'product-images/b.png'],
presignedUrls: [
presigned('product-images/a.jpg'),
presigned('product-images/b.png'),
],
})
const putCalls = fetchMock.mock.calls.filter(
([, options]) => (options as { method?: string } | undefined)?.method === 'PUT'
)
expect(putCalls).toHaveLength(2)
expect(result.current.error).toBeNull()
})
it('resolves an empty batch without calling the backend', async () => {
const { fetchMock } = setupApiMocks()
const { result } = renderHook(() => useUploadToObjectStorage(), { wrapper })
let resolved: unknown
await act(async () => {
resolved = await result.current.upload({ images: [], contextString: 'store' })
})
expect(resolved).toEqual({ keys: [], presignedUrls: [] })
expect(procCount(fetchMock, 'common.generateUploadUrls')).toBe(0)
})
it('fails when the backend returns a URL count that does not match', async () => {
setupApiMocks({
procedures: {
'common.generateUploadUrls': { uploadUrls: [presigned('tags/only.jpg')] },
},
})
const { result } = renderHook(() => useUploadToObjectStorage(), { wrapper })
const promise = startUpload(result, {
images: [jpeg, png],
contextString: 'tags',
})
await waitFor(() =>
expect(result.current.error?.message).toBe('Expected 2 URLs, got 1')
)
await expect(promise).rejects.toThrow('Expected 2 URLs, got 1')
})
it('surfaces the failed PUT status and stops uploading', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'common.generateUploadUrls': {
uploadUrls: [presigned('store-images/x.jpg')],
},
},
})
const trpcFetch = global.fetch
;(global as unknown as { fetch: unknown }).fetch = jest.fn(
async (url: string, options?: { method?: string }) => {
if (options?.method === 'PUT') {
return {
ok: false,
status: 500,
statusText: 'Server Error',
headers: new Map(),
url: String(url),
text: async (): Promise<string> => '<Error><Code>AccessDenied</Code></Error>',
json: async () => ({}),
}
}
return trpcFetch(url, options)
}
)
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {})
const { result } = renderHook(() => useUploadToObjectStorage(), { wrapper })
const promise = startUpload(result, {
images: [jpeg],
contextString: 'store',
})
await waitFor(() =>
expect(result.current.error?.message).toBe('Upload 1 failed with status 500')
)
await expect(promise).rejects.toThrow('Upload 1 failed with status 500')
expect(result.current.isUploading).toBe(false)
expect(result.current.progress).toBeNull()
expectProcedureCalled(fetchMock, 'common.generateUploadUrls', { times: 1 })
consoleError.mockRestore()
})
it('reports progress as each upload settles', async () => {
setupApiMocks({
procedures: {
'common.generateUploadUrls': {
uploadUrls: [
presigned('product-images/a.jpg'),
presigned('product-images/b.jpg'),
],
},
},
})
const trpcFetch = global.fetch
const resolvers: Array<(value: unknown) => void> = []
;(global as unknown as { fetch: unknown }).fetch = jest.fn(
(url: string, options?: { method?: string }) => {
if (options?.method === 'PUT') {
return new Promise((resolve) => resolvers.push(resolve))
}
return trpcFetch(url, options)
}
)
const okResponse = {
ok: true,
status: 200,
statusText: 'OK',
headers: new Map(),
url: '',
text: async () => '',
json: async () => ({}),
}
const { result } = renderHook(() => useUploadToObjectStorage(), { wrapper })
const promise = startUpload(result, {
images: [jpeg, png],
contextString: 'product_info',
})
await waitFor(() => expect(resolvers).toHaveLength(2))
expect(result.current.progress).toEqual({ completed: 0, total: 2 })
act(() => resolvers[0](okResponse))
await waitFor(() => expect(result.current.progress).toEqual({ completed: 1, total: 2 }))
act(() => resolvers[1](okResponse))
await waitFor(() => expect(result.current.progress).toBeNull())
const uploaded = await promise
expect(uploaded).toEqual({
keys: ['product-images/a.jpg', 'product-images/b.jpg'],
presignedUrls: [
presigned('product-images/a.jpg'),
presigned('product-images/b.jpg'),
],
})
})
})

View file

@ -1,6 +0,0 @@
/// <reference types="jest" />
// Declares the Jest globals (describe, it, expect, jest, ...) for the tests in
// this folder. @types/jest is a devDependency, but the explicit reference means
// the globals are declared by a file inside the project rather than relying on
// ambient @types auto-inclusion.

View file

@ -1,62 +1,104 @@
/* eslint-disable */
const path = require('path')
const appRoot = path.resolve(__dirname, '..')
const repoRoot = path.resolve(__dirname, '../../..')
// Packages that ship untranspiled ESM/JSX and must run through babel.
const transformAllowList = [
'(jest-)?react-native',
'@react-native(-community)?',
'expo(nent)?',
'@expo(nent)?/.*',
'@expo-google-fonts/.*',
'react-navigation',
'@react-navigation/.*',
'@unimodules/.*',
'unimodules',
'sentry-expo',
'native-base',
'react-native-svg',
'react-native-reanimated',
'react-native-gesture-handler',
'react-native-toast-message',
'react-native-webview',
'react-native-element-dropdown',
'react-native-keyboard-aware-scroll-view',
'react-native-pager-view',
'react-native-paper',
'react-native-tab-view',
'react-native-draggable-flatlist',
'twrnc',
'@trpc/.*',
'@tanstack/.*',
'zustand',
'formik',
'yup',
'jwt-decode',
'@packages/.*',
'common-ui',
]
/**
* Jest project for apps/admin-ui integration tests.
*
* Mirrors apps/user-ui/tests/jest.config.js. Tests live under tests/ and are
* kept out of the app build by living outside the app/ route tree.
*/
module.exports = {
preset: 'jest-expo',
rootDir: appRoot,
roots: ['<rootDir>/tests'],
testMatch: ['<rootDir>/tests/**/*.test.ts', '<rootDir>/tests/**/*.test.tsx'],
setupFiles: ['<rootDir>/tests/setup.ts'],
clearMocks: true,
// The suites are heavy (expo-router + react-query + fake timers) and several
// install module-level fakes; running them in parallel workers exhausts
// resources and hangs. Serial is ~80s and stable.
maxWorkers: 1,
forceExit: true,
moduleNameMapper: {
'^@backend/(.*)$': '<rootDir>/../backend/src/$1',
'^@/(.*)$': '<rootDir>/$1',
'^shared-types$': '<rootDir>/../shared-types',
'^@packages/shared$': '<rootDir>/../../packages/shared',
'^@packages/shared/(.*)$': '<rootDir>/../../packages/shared/$1',
'^global-shared$': '<rootDir>/../../packages/shared',
'^global-shared/(.*)$': '<rootDir>/../../packages/shared/$1',
'^common-ui$': '<rootDir>/../../packages/ui',
'^common-ui/(.*)$': '<rootDir>/../../packages/ui/$1',
},
rootDir: __dirname,
testMatch: ['<rootDir>/**/*.test.ts', '<rootDir>/**/*.test.tsx'],
setupFiles: [require.resolve('react-native-gesture-handler/jestSetup')],
setupFilesAfterEnv: [path.join(__dirname, 'setup.ts')],
transformIgnorePatterns: [
'node_modules/(?!(?:.pnpm/)?(' +
[
'(jest-)?react-native',
'@react-native(-community)?',
'expo(nent)?',
'@expo(nent)?/.*',
'@expo-google-fonts/.*',
'react-navigation',
'@react-navigation/.*',
'@sentry/react-native',
'native-base',
'react-native-svg',
'react-native-gesture-handler',
'react-native-reanimated',
'react-native-safe-area-context',
'react-native-screens',
'react-native-draggable-flatlist',
'react-native-tab-view',
'react-native-toast-message',
'@trpc/.*',
'@tanstack/.*',
'twrnc',
'zod',
'@testing-library/react-native',
].join('|') +
'))',
'/node_modules/(?!((jest-)?react-native|@react-native(-community)?)|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*|@sentry/react-native|native-base|react-native-svg|react-native-reanimated|react-native-gesture-handler|react-native-toast-message|react-native-webview|react-native-element-dropdown|react-native-keyboard-aware-scroll-view|react-native-pager-view|react-native-paper|react-native-tab-view|react-native-draggable-flatlist|@trpc/.*|@tanstack/.*|zustand|formik|yup|jwt-decode|fuse.js|twrnc)',
'/node_modules/react-native-reanimated/plugin/',
],
moduleNameMapper: {
// Manual mocks first (order matters: moduleNameMapper is first-match-wins).
// Native / platform modules -> shared shims (every copy of a package, root
// or packages/ui/node_modules, resolves to the same mock).
'^react-native-reanimated$': path.join(repoRoot, 'node_modules/react-native-reanimated/mock.js'),
'^expo-secure-store$': '<rootDir>/mocks/native/secure-store.ts',
'^expo-notifications$': '<rootDir>/mocks/native/notifications.ts',
'^expo-constants$': '<rootDir>/mocks/native/constants.ts',
'^expo-router$': '<rootDir>/mocks/native/expo-router.tsx',
'^expo-router/(.*)$': '<rootDir>/mocks/native/expo-router.tsx',
'^expo-image$': '<rootDir>/mocks/native/common.tsx',
'^expo-linear-gradient$': '<rootDir>/mocks/native/common.tsx',
'^expo-blur$': '<rootDir>/mocks/native/common.tsx',
'^expo-status-bar$': '<rootDir>/mocks/native/common.tsx',
'^expo-font$': '<rootDir>/mocks/native/common.tsx',
'^expo-updates$': '<rootDir>/mocks/native/common.tsx',
'^expo-splash-screen$': '<rootDir>/mocks/native/common.tsx',
'^expo-web-browser$': '<rootDir>/mocks/native/common.tsx',
'^expo-linking$': '<rootDir>/mocks/native/common.tsx',
'^expo-haptics$': '<rootDir>/mocks/native/common.tsx',
'^expo-image-picker$': '<rootDir>/mocks/native/common.tsx',
'^expo-document-picker$': '<rootDir>/mocks/native/common.tsx',
'^expo-device$': '<rootDir>/mocks/native/common.tsx',
'^expo-symbols$': '<rootDir>/mocks/native/common.tsx',
'^expo-system-ui$': '<rootDir>/mocks/native/common.tsx',
'^react-native-webview$': '<rootDir>/mocks/native/common.tsx',
'^react-native-safe-area-context$': '<rootDir>/mocks/native/common.tsx',
'^react-native-svg$': '<rootDir>/mocks/native/svg.tsx',
'^react-native-draggable-flatlist$': '<rootDir>/mocks/native/draggable-flatlist.tsx',
'^@react-native-community/datetimepicker$': '<rootDir>/mocks/native/datetimepicker.tsx',
'^@react-native-picker/picker$': '<rootDir>/mocks/native/picker.tsx',
'^react-native-toast-message$': '<rootDir>/mocks/native/toast-message.tsx',
'^@react-navigation/native$': '<rootDir>/mocks/native/react-navigation.tsx',
// Workspace packages.
'^@packages/shared$': path.join(repoRoot, 'packages/shared'),
'^@packages/shared/(.*)$': path.join(repoRoot, 'packages/shared') + '/$1',
'^common-ui$': path.join(repoRoot, 'packages/ui/index.ts'),
'^common-ui/(.*)$': path.join(repoRoot, 'packages/ui') + '/$1',
'^@backend/(.*)$': path.join(repoRoot, 'apps/backend/src') + '/$1',
// App-root alias.
'^@/(.*)$': appRoot + '/$1',
},
clearMocks: false,
restoreMocks: false,
fakeTimers: {
doNotFake: ['nextTick', 'queueMicrotask', 'setImmediate'],
},
testTimeout: 20000,
verbose: false,
maxWorkers: '50%',
// Real React Query + tRPC client can leave pending timers; force exit.
forceExit: true,
}

View file

@ -0,0 +1,30 @@
/**
* Catalogue section 17.2 — queryClient (`tests/lib/query-client.test.ts`).
*/
import { QueryClient } from '@tanstack/react-query'
import queryClient from '@/utils/queryClient'
import { resetAllMocks } from '../helpers/reset'
describe('queryClient (AQC-01..02)', () => {
beforeEach(() => resetAllMocks())
it('AQC-01: exposes the production retry defaults', () => {
expect(queryClient).toBeInstanceOf(QueryClient)
const defaults = queryClient.getDefaultOptions()
expect(defaults.queries).toEqual({ retry: 3 })
})
it('AQC-02: clearing the client on logout drops every cached query', () => {
queryClient.setQueryData(['admin', 'product', 'getProducts'], { products: [] })
queryClient.setQueryData(['admin', 'region', 'current'], { region: { id: 1 } })
expect(queryClient.getQueryCache().getAll()).toHaveLength(2)
queryClient.clear()
expect(queryClient.getQueryCache().getAll()).toHaveLength(0)
expect(queryClient.getQueryData(['admin', 'product', 'getProducts'])).toBeUndefined()
expect(queryClient.getQueryData(['admin', 'region', 'current'])).toBeUndefined()
})
})

View file

@ -1,37 +0,0 @@
/**
* queryClient (utils/queryClient.ts) — the app-wide singleton defaults.
*
* The source only overrides `retry`. React Query therefore supplies the
* remaining observable defaults (staleTime resolves to 0, refetchOnWindowFocus
* behaves as true). We assert both the configured value and that the other two
* options are deliberately left unset.
*/
import { QueryClient } from '@tanstack/react-query'
import queryClient from '@/utils/queryClient'
describe('queryClient', () => {
it('is a QueryClient instance', () => {
expect(queryClient).toBeInstanceOf(QueryClient)
})
it('retries failed queries 3 times by default', () => {
expect(queryClient.getDefaultOptions().queries?.retry).toBe(3)
})
it('retries every query with the configured default', () => {
const resolved = queryClient.defaultQueryOptions({ queryKey: ['probe'] })
expect(resolved.retry).toBe(3)
})
it('does not override staleTime / refetchOnWindowFocus (library defaults apply)', () => {
const queries = queryClient.getDefaultOptions().queries
expect(queries?.staleTime).toBeUndefined()
expect(queries?.refetchOnWindowFocus).toBeUndefined()
const resolved = queryClient.defaultQueryOptions({ queryKey: ['probe'] })
expect(resolved.staleTime).toBeUndefined()
expect(resolved.refetchOnWindowFocus).toBeUndefined()
})
})

View file

@ -1,51 +0,0 @@
/**
* toaster (services/toaster.tsx) — Info/Error/Success helpers funnel into
* react-native-toast-message's Toast.show with the right type/position and an
* onPress that hides the toast.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import Toast from 'react-native-toast-message'
import { ErrorToast, InfoToast, SuccessToast } from '@/services/toaster'
const showMock = Toast.show as jest.Mock
const hideMock = Toast.hide as jest.Mock
const showArg = (index: number) => showMock.mock.calls[index][0]
describe('toaster', () => {
it('InfoToast shows an info toast at the top', () => {
InfoToast('heads up')
expect(showMock).toHaveBeenCalledWith(
expect.objectContaining({ type: 'info', text1: 'heads up', position: 'top' })
)
expect(showArg(0).visibilityTime).toBe(10000)
})
it('ErrorToast shows an error toast at the top', () => {
ErrorToast('boom')
expect(showMock).toHaveBeenCalledWith(
expect.objectContaining({ type: 'error', text1: 'boom', position: 'top' })
)
})
it('SuccessToast shows a success toast at the top', () => {
SuccessToast('done')
expect(showMock).toHaveBeenCalledWith(
expect.objectContaining({ type: 'success', text1: 'done', position: 'top' })
)
})
it('hides the toast when pressed', () => {
SuccessToast('done')
showArg(0).onPress()
expect(hideMock).toHaveBeenCalledTimes(1)
})
})

View file

@ -0,0 +1,109 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 17.2 — tRPC client (`tests/lib/trpc-client.test.ts`).
*
* `@/src/trpc-client` is module-mapped to the procedure-registry mock for every
* other suite. Here the real module is loaded with an explicit relative path
* (which does not match the mapper) so the production `httpBatchLink` fetch
* wrapper, bearer-header builder and 401 force-logout handler run for real.
*/
import { DeviceEventEmitter } from 'react-native'
import { resetAllMocks } from '../helpers/reset'
import { __set } from '../mocks/secure-store-mock'
import { TEST_JWT } from '../fixtures'
import { FORCE_LOGOUT_EVENT } from 'common-ui/src/lib/const-strs'
function loadRealClient() {
// The explicit `.ts` suffix keeps this request out of the moduleNameMapper.
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('../../src/trpc-client.ts') as typeof import('@/src/trpc-client')
}
function jsonResponse(status: number, body: any) {
const make = (): any => ({
ok: status >= 200 && status < 300,
status,
statusText: String(status),
headers: { get: () => 'application/json' },
json: async () => body,
text: async () => JSON.stringify(body),
})
const response = make()
response.clone = () => make()
return response
}
describe('trpc client (ATRPC-01..03)', () => {
beforeEach(() => {
resetAllMocks()
jest.spyOn(DeviceEventEmitter, 'emit')
})
afterEach(() => {
jest.restoreAllMocks()
})
it('ATRPC-01: a 401 UNAUTHORIZED response emits the force-logout event', async () => {
const { trpcClient } = loadRealClient()
__set('jwt_token', TEST_JWT)
;(global as any).fetch = jest.fn(async () =>
jsonResponse(401, {
error: {
message: 'UNAUTHORIZED',
code: -32001,
data: { code: 'UNAUTHORIZED', httpStatus: 401 },
},
})
)
await expect(trpcClient.admin.staffUser.me.query()).rejects.toBeTruthy()
expect(DeviceEventEmitter.emit).toHaveBeenCalledWith(FORCE_LOGOUT_EVENT)
expect((global as any).fetch).toHaveBeenCalledTimes(1)
})
it('ATRPC-02: a 500 / non-UNAUTHORIZED failure does not force logout', async () => {
const { trpcClient } = loadRealClient()
;(global as any).fetch = jest.fn(async () =>
jsonResponse(500, {
error: {
message: 'Something exploded',
code: -32603,
data: { code: 'INTERNAL_SERVER_ERROR', httpStatus: 500 },
},
})
)
await expect(trpcClient.admin.staffUser.me.query()).rejects.toBeTruthy()
expect(DeviceEventEmitter.emit).not.toHaveBeenCalledWith(FORCE_LOGOUT_EVENT)
// A 401 that is not the UNAUTHORIZED code must also stay signed in.
;(global as any).fetch = jest.fn(async () =>
jsonResponse(401, {
error: {
message: 'Session is not the right shape',
code: -32001,
data: { code: 'BAD_REQUEST', httpStatus: 401 },
},
})
)
await expect(trpcClient.admin.staffUser.me.query()).rejects.toBeTruthy()
expect(DeviceEventEmitter.emit).not.toHaveBeenCalledWith(FORCE_LOGOUT_EVENT)
})
it('ATRPC-03: attaches the stored JWT as a bearer Authorization header', async () => {
const { trpcClient } = loadRealClient()
__set('jwt_token', TEST_JWT)
;(global as any).fetch = jest.fn(async () =>
jsonResponse(200, { result: { data: { id: 3, name: 'Admin One' } } })
)
await trpcClient.admin.staffUser.me.query()
const [url, options] = ((global as any).fetch as jest.Mock).mock.calls[0]
expect(String(url)).toContain('/api/trpc')
expect(options.method).toBe('GET')
expect(options.headers).toMatchObject({ Authorization: `Bearer ${TEST_JWT}` })
})
})

View file

@ -0,0 +1,235 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 17.2 — useUploadToObjectStorage
* (`tests/lib/upload-hook.test.tsx`).
*
* The hook is exercised through a probe component so React state
* (`isUploading`) can be observed while the upload is in flight.
*
* The real tRPC client + React Query run, so the probe needs the same providers
* as a page. Presigned PUTs go to a non-tRPC URL and are answered by
* `setRawFetchHandler` (never by replacing `global.fetch`, which would take the
* harness' tRPC network mock with it).
*/
import React from 'react'
import { Text } from 'react-native'
import { act } from '@testing-library/react-native'
import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore'
import { resetAllMocks } from '../helpers/reset'
import {
lastMutationInput,
procedureMutationCalls,
setProcedure,
setRawFetchHandler,
} from '../mocks/trpc-client'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { UPLOAD_URLS_RESPONSE } from '../fixtures'
type HookApi = ReturnType<typeof useUploadToObjectStorage>
let hook: HookApi | null = null
function Probe() {
const api = useUploadToObjectStorage()
hook = api
return (
<>
<Text testID="uploading">{api.isUploading ? 'uploading' : 'idle'}</Text>
<Text testID="error">{api.error?.message ?? 'none'}</Text>
<Text testID="progress">
{api.progress ? `${api.progress.completed}/${api.progress.total}` : 'none'}
</Text>
</>
)
}
function renderProbe() {
return renderWithProviders(<Probe />, { auth: false })
}
const blob = {} as any
const OK_RESPONSE = {
ok: true,
status: 200,
text: async () => '',
json: async () => ({}),
}
const ERROR_RESPONSE = {
ok: false,
status: 500,
text: async () => '<Error><Code>InternalError</Code></Error>',
json: async () => ({}),
}
/** Records the presigned PUTs the hook makes (non-tRPC requests). */
function stubPut(response: any = OK_RESPONSE) {
const put = jest.fn(async (_url: string, _init?: any) => ({ ...response }))
setRawFetchHandler(put as any)
return put
}
describe('useUploadToObjectStorage (AUPL-01..06)', () => {
beforeEach(() => {
resetAllMocks()
hook = null
})
afterEach(() => {
jest.restoreAllMocks()
})
it('AUPL-01: uploads a single image via the presigned PUT and returns key/url', async () => {
const put = stubPut()
const view = renderProbe()
let result: any
await act(async () => {
result = await hook!.uploadSingle(blob, 'image/jpeg', 'product_info')
})
expect(lastMutationInput('common.generateUploadUrls')).toEqual({
contextString: 'product_info',
mimeTypes: ['image/jpeg'],
})
expect(put).toHaveBeenCalledTimes(1)
const [url, options] = put.mock.calls[0]
expect(url).toBe(UPLOAD_URLS_RESPONSE.uploadUrls[0])
expect(options).toMatchObject({
method: 'PUT',
body: blob,
headers: { 'Content-Type': 'image/jpeg' },
})
expect(result).toEqual({
key: 'product-images/img-1.jpg',
presignedUrl: UPLOAD_URLS_RESPONSE.uploadUrls[0],
})
expect(view.getByTestId('uploading').props.children).toBe('idle')
})
it('AUPL-02: uploads every image and requests one URL per mime type', async () => {
const urls = [
'https://upload.test/meatfarmer/review-images/a.jpg',
'https://upload.test/meatfarmer/review-images/b.png',
]
setProcedure('common.generateUploadUrls', { data: { uploadUrls: urls } })
const put = stubPut()
const view = renderProbe()
let result: any
await act(async () => {
result = await hook!.upload({
images: [
{ blob, mimeType: 'image/jpeg' },
{ blob, mimeType: 'image/png' },
],
contextString: 'review',
})
})
expect(lastMutationInput('common.generateUploadUrls')).toEqual({
contextString: 'review',
mimeTypes: ['image/jpeg', 'image/png'],
})
expect(put).toHaveBeenCalledTimes(2)
expect(put.mock.calls.map((call: any[]) => call[0])).toEqual(urls)
expect(result).toEqual({
keys: ['review-images/a.jpg', 'review-images/b.png'],
presignedUrls: urls,
})
expect(view.getByTestId('uploading').props.children).toBe('idle')
})
it('AUPL-03: an empty image list makes no URL or PUT request', async () => {
const put = stubPut()
const view = renderProbe()
let result: any
await act(async () => {
result = await hook!.upload({ images: [], contextString: 'product_info' })
})
expect(result).toEqual({ keys: [], presignedUrls: [] })
expect(procedureMutationCalls('common.generateUploadUrls')).toHaveLength(0)
expect(put).not.toHaveBeenCalled()
expect(view.getByTestId('uploading').props.children).toBe('idle')
})
it('AUPL-04: rejects when the URL count does not match the image count', async () => {
const put = stubPut()
const view = renderProbe()
let error: any
await act(async () => {
try {
await hook!.upload({
images: [
{ blob, mimeType: 'image/jpeg' },
{ blob, mimeType: 'image/jpeg' },
],
contextString: 'product_info',
})
} catch (err) {
error = err
}
})
expect(error).toBeInstanceOf(Error)
expect(error.message).toBe('Expected 2 URLs, got 1')
expect(put).not.toHaveBeenCalled()
await flush()
expect(view.getByTestId('error').props.children).toBe('Expected 2 URLs, got 1')
expect(view.getByTestId('uploading').props.children).toBe('idle')
})
it('AUPL-05: rejects when the presigned PUT fails', async () => {
jest.spyOn(console, 'error').mockImplementation(() => undefined)
const put = stubPut(ERROR_RESPONSE)
const view = renderProbe()
let error: any
await act(async () => {
try {
await hook!.uploadSingle(blob, 'image/jpeg', 'product_info')
} catch (err) {
error = err
}
})
expect(error).toBeInstanceOf(Error)
expect(error.message).toBe('Upload 1 failed with status 500')
expect(put).toHaveBeenCalledTimes(1)
await flush()
expect(view.getByTestId('error').props.children).toBe('Upload 1 failed with status 500')
expect(view.getByTestId('uploading').props.children).toBe('idle')
})
it('AUPL-06: isUploading is true while the PUT is in flight and false afterwards', async () => {
let resolvePut: (value: any) => void = () => undefined
const pendingPut = new Promise((resolve) => {
resolvePut = resolve
})
setRawFetchHandler((() => pendingPut) as any)
const view = renderProbe()
expect(view.getByTestId('uploading').props.children).toBe('idle')
let uploadPromise: Promise<any> = Promise.resolve()
act(() => {
uploadPromise = hook!.uploadSingle(blob, 'image/jpeg', 'product_info')
})
await flush()
expect(view.getByTestId('uploading').props.children).toBe('uploading')
expect(view.getByTestId('progress').props.children).toBe('0/1')
await act(async () => {
resolvePut({ ...OK_RESPONSE })
await uploadPromise
})
expect(view.getByTestId('uploading').props.children).toBe('idle')
expect(view.getByTestId('progress').props.children).toBe('none')
})
})

View file

@ -0,0 +1,54 @@
/**
* Catalogue section 17.2 — useJWT (`tests/lib/use-jwt.test.ts`).
*/
import {
JWT_KEY,
STAFF_KEY,
saveJWT,
getJWT,
deleteJWT,
saveStaff,
getStaff,
deleteStaff,
} from '@/hooks/useJWT'
import { resetAllMocks } from '../helpers/reset'
import { __set, __snapshot } from '../mocks/secure-store-mock'
import { STAFF, TEST_JWT } from '../fixtures'
describe('useJWT (AJWT-01..03)', () => {
beforeEach(() => resetAllMocks())
it('AJWT-01: saves, reads and deletes the JWT', async () => {
expect(JWT_KEY).toBe('jwt_token')
await expect(getJWT()).resolves.toBeNull()
await saveJWT(TEST_JWT)
expect(__snapshot()[JWT_KEY]).toBe(TEST_JWT)
await expect(getJWT()).resolves.toBe(TEST_JWT)
await deleteJWT()
await expect(getJWT()).resolves.toBeNull()
expect(__snapshot()).not.toHaveProperty(JWT_KEY)
})
it('AJWT-02: saves, reads and deletes the stored staff', async () => {
expect(STAFF_KEY).toBe('staff_session')
await expect(getStaff()).resolves.toBeNull()
await saveStaff(STAFF)
expect(__snapshot()[STAFF_KEY]).toBe(JSON.stringify(STAFF))
await expect(getStaff()).resolves.toEqual(STAFF)
await deleteStaff()
await expect(getStaff()).resolves.toBeNull()
expect(__snapshot()).not.toHaveProperty(STAFF_KEY)
})
it('AJWT-03: missing keys return null, malformed staff returns null', async () => {
await expect(getJWT()).resolves.toBeNull()
await expect(getStaff()).resolves.toBeNull()
__set(STAFF_KEY, '{not-json')
await expect(getStaff()).resolves.toBeNull()
})
})

View file

@ -1,73 +0,0 @@
/**
* Network-layer mocks for the admin-ui tests.
*
* All tRPC traffic goes through `global.fetch` (httpBatchLink). The registry
* resolves each batched procedure by name; anything not supplied resolves to
* `null`, and tests override with the exact shape they assert against. Tests
* that need to prove "nothing was called" use tests/mocks/procedures.ts.
*/
import { StorageService } from 'common-ui/src/services/StorageService'
import { StorageServiceCasual } from 'common-ui/src/services/StorageServiceCasual'
import { parseTrpcUrl } from './procedures'
const jsonResponse = (body: unknown) => ({
ok: true,
status: 200,
statusText: 'OK',
headers: new Map(),
url: '',
json: async () => body,
text: async () => JSON.stringify(body),
clone: () => jsonResponse(body),
})
export interface ApiMockOptions {
/**
* Procedure registry: name -> data, or (input) => data. Unlisted procedures
* resolve to null.
*/
procedures?: Record<string, unknown | ((input: unknown) => unknown)>
/** The essentialConsts-style consts payload, if a screen reads it. */
consts?: unknown
}
export function setupApiMocks(opts: ApiMockOptions = {}) {
const resolveProcedure = (name: string, input: unknown): unknown => {
const override = opts.procedures?.[name]
if (override !== undefined) {
return typeof override === 'function'
? (override as (value: unknown) => unknown)(input)
: override
}
return null
}
const fetchMock = jest.fn(
async (url: string, options?: { method?: string; body?: unknown }) => {
const target = String(url)
const calls = parseTrpcUrl(target, options?.body)
if (calls.length === 0) {
// Presigned S3 uploads PUT straight to a URL.
if (options?.method === 'PUT') return jsonResponse({})
throw new Error(`[tests] unmocked fetch: ${url}`)
}
const batch = calls.map(({ name, input }) => ({
result: { data: resolveProcedure(name, input) },
}))
return jsonResponse(batch)
}
)
;(global as unknown as { fetch: unknown }).fetch = fetchMock
return { fetchMock }
}
/** Clear the in-memory auth token + any casual storage. Call from beforeEach. */
export async function resetStorage() {
await StorageService.clearAll(['jwt_token'])
await StorageServiceCasual.clearAll([])
}

View file

@ -0,0 +1,113 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Configurable stand-in for `expo-notifications`.
*
* Tests can flip the permission result and fire the received/response listeners
* that `NotificationProvider` subscribes to.
*/
interface NotifConfig {
permission: 'granted' | 'denied' | 'undetermined'
requestResult: 'granted' | 'denied'
token: string
projectId: string | null
}
const config: NotifConfig = {
permission: 'granted',
requestResult: 'granted',
token: 'ExponentPushToken[test-token]',
projectId: 'test-project-id',
}
type Listener = (payload: any) => void
const receivedListeners: Listener[] = []
const responseListeners: Listener[] = []
export function __configure(next: Partial<NotifConfig>) {
Object.assign(config, next)
}
export function __reset() {
config.permission = 'granted'
config.requestResult = 'granted'
config.token = 'ExponentPushToken[test-token]'
config.projectId = 'test-project-id'
receivedListeners.length = 0
responseListeners.length = 0
}
export function __emitNotification(notification: any) {
receivedListeners.forEach((listener) => listener(notification))
}
export function __emitResponse(response: any) {
responseListeners.forEach((listener) => listener(response))
}
export const AndroidImportance = { MAX: 5, HIGH: 4, DEFAULT: 3, LOW: 2, MIN: 1 }
export const setNotificationHandler = jest.fn()
export const setNotificationChannelAsync = jest.fn(async () => null)
export const getPermissionsAsync = jest.fn(async () => ({
status: config.permission,
granted: config.permission === 'granted',
canAskAgain: true,
}))
export const requestPermissionsAsync = jest.fn(async () => ({
status: config.requestResult,
granted: config.requestResult === 'granted',
canAskAgain: true,
}))
export const getExpoPushTokenAsync = jest.fn(async (_args?: any) => ({ data: config.token }))
export const getDevicePushTokenAsync = jest.fn(async () => ({ data: config.token }))
export const scheduleNotificationAsync = jest.fn(async () => 'notification-id')
export const cancelAllScheduledNotificationsAsync = jest.fn(async () => undefined)
export const getLastNotificationResponseAsync = jest.fn(async () => null)
export function addNotificationReceivedListener(listener: Listener) {
receivedListeners.push(listener)
return {
remove: () => {
const index = receivedListeners.indexOf(listener)
if (index >= 0) receivedListeners.splice(index, 1)
},
}
}
export function addNotificationResponseReceivedListener(listener: Listener) {
responseListeners.push(listener)
return {
remove: () => {
const index = responseListeners.indexOf(listener)
if (index >= 0) responseListeners.splice(index, 1)
},
}
}
export const removeNotificationSubscription = jest.fn((subscription: any) => {
subscription?.remove?.()
})
export const useLastNotificationResponse = () => null
export default {
AndroidImportance,
setNotificationHandler,
setNotificationChannelAsync,
getPermissionsAsync,
requestPermissionsAsync,
getExpoPushTokenAsync,
getDevicePushTokenAsync,
scheduleNotificationAsync,
cancelAllScheduledNotificationsAsync,
getLastNotificationResponseAsync,
addNotificationReceivedListener,
addNotificationResponseReceivedListener,
removeNotificationSubscription,
useLastNotificationResponse,
__configure,
__reset,
__emitNotification,
__emitResponse,
}

Some files were not shown because too many files have changed in this diff Show more