TEST_AUTOMATION #9

Merged
shafi merged 19 commits from TEST_AUTOMATION into main 2026-10-03 05:20:55 +00:00
385 changed files with 50751 additions and 2102 deletions

View file

@ -81,7 +81,24 @@
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo && npx tsc --noEmit -p tests 2>&1 | tail -5; echo \"tsc_exit=$?\"; bun run test:e2e > /tmp/e2e_run9.log 2>&1; echo \"exit=$?\" >> /tmp/e2e_run9.log)",
"Shell(DEBUG=pw:browser npx playwright test tests/specs/smoke.spec.ts 2 >& 1)",
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo && git diff product_to_sku_c1 -- apps/user-ui/hooks/cart-query-hooks.tsx apps/user-ui/hooks/useUploadToObjectStore.ts apps/user-ui/eas.json apps/user-ui/'(drawer)' 2>/dev/null; git diff product_to_sku_c1 -- \"apps/user-ui/app/(drawer)/(tabs)/me/addresses/index.tsx\" \"apps/user-ui/app/(drawer)/(tabs)/me/my-orders/index.tsx\" | head -160)",
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo/packages/db_helper_sqlite && npx tsc --noEmit 2>&1 | tail -8; echo \"sqlite_exit=$?\"; echo \"=== user-ui ===\"; cd /Users/mohammedshafiuddin/WebDev/freshyo/apps/user-ui && npx tsc --noEmit 2>&1 | tee /tmp/uui_tsc.txt | tail -5; echo \"userui_errors=$(grep -cE 'error TS' /tmp/uui_tsc.txt)\")"
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo/packages/db_helper_sqlite && npx tsc --noEmit 2>&1 | tail -8; echo \"sqlite_exit=$?\"; echo \"=== user-ui ===\"; cd /Users/mohammedshafiuddin/WebDev/freshyo/apps/user-ui && npx tsc --noEmit 2>&1 | tee /tmp/uui_tsc.txt | tail -5; echo \"userui_errors=$(grep -cE 'error TS' /tmp/uui_tsc.txt)\")",
"Shell(/.maestro/bin/maestro:*)",
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo && adb shell am force-stop in.freshyo.app; adb shell monkey -p in.freshyo.app -c android.intent.category.LAUNCHER 1 >/dev/null 2>&1; sleep 8; mkdir -p \"$COMMANDCODE_SCRATCHPAD\"; adb exec-out screencap -p > \"$COMMANDCODE_SCRATCHPAD/screen1.png\"; ls -la \"$COMMANDCODE_SCRATCHPAD/screen1.png\")",
"Shell(adb:*)",
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo && adb exec-out screencap -p > \"$COMMANDCODE_SCRATCHPAD/screen2.png\" && ls -la \"$COMMANDCODE_SCRATCHPAD/screen2.png\")",
"Shell(bash e2e/run.sh flows/smoke.yaml 2 >& 1)",
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo && \"$HOME/.maestro/bin/maestro\" hierarchy --platform android 2>/dev/null > \"$COMMANDCODE_SCRATCHPAD/hier.json\"; wc -c \"$COMMANDCODE_SCRATCHPAD/hier.json\"; echo \"=== occurrences ===\"; grep -o \"product-card\" \"$COMMANDCODE_SCRATCHPAD/hier.json\" | head -3; echo \"--- context around testID usages ---\"; grep -oE '\"(resource-id|content-desc|text|accessibilityText)\": \"[^\"]{0,40}\"' \"$COMMANDCODE_SCRATCHPAD/hier.json\" | sort | uniq -c | sort -rn | head -20)",
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo && adb shell uiautomator dump /sdcard/ui.xml >/dev/null 2>&1; adb shell cat /sdcard/ui.xml > \"$COMMANDCODE_SCRATCHPAD/ui.xml\" 2>/dev/null; wc -c \"$COMMANDCODE_SCRATCHPAD/ui.xml\"; echo \"=== product-card? ===\"; grep -o \"product-card\" \"$COMMANDCODE_SCRATCHPAD/ui.xml\" | head -2; echo \"=== sample attrs ===\"; grep -oE 'content-desc=\"[^\"]{1,40}\"' \"$COMMANDCODE_SCRATCHPAD/ui.xml\" | sort -u | head -15; echo \"=== text sample ===\"; grep -oE 'text=\"[^\"]{2,40}\"' \"$COMMANDCODE_SCRATCHPAD/ui.xml\" | sort -u | head -20)",
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo && adb shell am force-stop in.freshyo.app; adb shell monkey -p in.freshyo.app -c android.intent.category.LAUNCHER 1 >/dev/null 2>&1; sleep 16; adb shell uiautomator dump /sdcard/ui2.xml >/dev/null 2>&1; adb shell cat /sdcard/ui2.xml > \"$COMMANDCODE_SCRATCHPAD/ui2.xml\" 2>/dev/null; echo \"size: $(wc -c < \"$COMMANDCODE_SCRATCHPAD/ui2.xml\")\"; echo \"=== product-card occurrences ===\"; grep -c \"product-card\" \"$COMMANDCODE_SCRATCHPAD/ui2.xml\" || true; echo \"=== resource-id sample ===\"; grep -oE 'resource-id=\"[^\"]{1,50}\"' \"$COMMANDCODE_SCRATCHPAD/ui2.xml\" | sort -u | head -15; echo \"=== content-desc sample ===\"; grep -oE 'content-desc=\"[^\"]{2,40}\"' \"$COMMANDCODE_SCRATCHPAD/ui2.xml\" | sort -u | head -15)",
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo && cat > \"$COMMANDCODE_SCRATCHPAD/probe2.yaml\" <<'YAML' appId: in.freshyo.app --- - assertVisible: id: \"product-card\" YAML \"$HOME/.maestro/bin/maestro\" test \"$COMMANDCODE_SCRATCHPAD/probe2.yaml\" --platform android 2>&1 | tail -6)",
"Shell(bash e2e/run.sh flows/place-order.yaml 2 >& 1)",
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo && ls ~/.maestro/tests/2026-09-14_154602/place-order/screen-hierarchy/ 2>/dev/null; F=$(ls ~/.maestro/tests/2026-09-14_154602/place-order/screen-hierarchy/*Me* 2>/dev/null | head -1); echo \"file: $F\"; grep -oE '\"(text|accessibilityText|resource-id)\": \"[^\"]{1,30}\"' \"$F\" 2>/dev/null | sort -u | head -40)",
"Shell(mkdir:*)",
"Shell(node -e console.log('node sees NODE_ENV:', JSON.stringify(process.env.NODE_ENV)))",
"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(',')); \")"
],
"deny": [],
"defaultMode": "default"

View file

@ -1,4 +1,6 @@
# Taste
- Wants each UI component/feature to own a dedicated test file rather than sharing one file across related features — explicitly asked for "a file exclusively for the floating cart bar tests", replacing the combined cart test file (deleting the superseded one and updating the README/index so there's exactly one file per component). Confidence: 0.6
- For cart/price tests, expects the money and delivery logic to be verified with concrete, pinned fixture products and exact numbers: add exactly the named products, then assert the running total, the free-delivery threshold (remaining amount, then "unlocked"), the slot each item lands in, and that the total recomputes when quantity changes — rather than loosely computed expectations ("note some products, add exactly those products and confirm the free delivery threshold, confirm the total cost, confirm the slots, test the price on change of quantity too"). Confidence: 0.6
- Defines tunable/magic numbers as named module-level constants in the SAME file where they are used (e.g., `const TOKENS_PER_QUEUE_MESSAGE = 5` next to the code it configures, with a short explanatory comment) instead of inline literals or a shared/global config — explicitly stated: "Define 5 as a constant in the same file." Confidence: 0.7
- Prefers that the agent not run typechecks; instead, read the project's AGENTS.md for instructions on what to do/not do before finalizing work. Confidence: 0.9
- Judges completion by seeing the feature live in the running app ("I still don't see it on the /home route page"), so for data-driven features the agent must verify the app's actual runtime data source (API base URL, cache/backend) has the required data — not just that code builds and typechecks. Confirmed when the user signaled success only after the fix (pointing web-ui at the local backend with the tags data) made the section visible in the running app, and reconfirmed with the admin-ui product selector showing no products because it points at the production worker. Confidence: 0.9
@ -96,7 +98,12 @@ er-ui/app/(drawer)/(tabs)/home/index.tsx, I want similar here") and expects the
- When an analysis/audit has been produced for one app in the monorepo, expects the same analysis run for the sibling apps too — after the user-ui dead-code audit he immediately asked "now do the same for the @apps/admin-ui" — applying the identical exhaustive methodology and document style to each named app. Confidence: 0.85
- For analysis documents, expects a consistent naming pattern following the established convention (`user_ui_dpsk.md` → `admin_ui_dpsk.md`, i.e., `{app}_dpsk.md` at the repo root) rather than an ad-hoc filename — "make another md file with same naming pattern"; the `_dpsk.md` suffix also applies to cross-cutting topic analyses (e.g., `repeat_types_dpsk.md` for the repeated-types scan). Confidence: 0.9
- When commissioning a cross-cutting audit/analysis, expects the scan to span the entire monorepo in one pass — every app, the backend, AND the shared packages (e.g., "scan the entire @apps/user-ui/ @apps/admin-ui/ @apps/backend/ and also entire @packages/") — not just one app or one area. Confidence: 0.65
- Wants change-log entries written to a specific, dedicated repo-root file rather than the generic `change-log.txt` — he directs the target filename explicitly ("write all change-log entries to backend-test-change-log.txt (at the repo root) instead of change-log.txt") and expects that choice to persist for subsequent entries. Confidence: 0.9
- Values type-level hygiene alongside runtime structures: wants repeated type declarations across the monorepo hunted down and classified (identical duplicates, near-identical/unifiable shapes, same-name-different-shape collisions) and documented in a report before any refactor, rather than fixing types piecemeal. Confidence: 0.6
- Prefers **jest** as the runner for the repo's automated tests — when offered a choice between jest and a lighter/zero-dependency alternative (bun test), he deliberately chose jest (consistent with the existing `apps/user-ui` jest setup); the runner is a decided matter for him, not a default. Confidence: 0.6
- Wants a distinct phase of **backend API/integration testing that drives the real running HTTP API** — create a record via one endpoint, then read it back (e.g. place an order, then fetch orders to prove it was created) — rather than relying only on network-mocked component tests: "I want to automate the backend testing. I want to call various apis and test." Confidence: 0.75
- For backend API tests, targets a **locally running backend (wrangler dev) with the base URL overridable via an env var** (`API_BASE_URL`) instead of hard-coding the URL or pointing at a deployed environment. Confidence: 0.55
- Prefers test preconditions/fixtures to be **created through the public API** (staff login → create store → product/SKU → slot → register a throwaway user → address) rather than direct DB inserts, and to **leave the created data behind** after a run (no automatic cleanup), matching the existing Maestro flows. Confidence: 0.55
- Requires the parallel DB-helper packages (db_helper_sqlite and db_helper_postgres) to not duplicate type definitions: they must share one canonical set of types and emit exactly the same data shape, since they represent the same business entities on different backends — stated directly: "they shouldn't duplicate types. They should emit exactly same type of data. They should share the types." Confidence: 0.9
@ -124,6 +131,25 @@ er-ui/app/(drawer)/(tabs)/home/index.tsx, I want similar here") and expects the
- Prefers that disruptive user-facing dialogs be reserved for genuinely important events: the OTA update prompt should NOT be shown for every update — only for a few crucial releases ("I don't want to show this for all the updates. Only a few updates are so important"), while routine updates apply silently in the background. Confidence: 0.7
- Uses "quantity" loosely to refer to the pack size / unit notation on order items: he reported "we aren't showing quantity" about a row that already rendered the numeric count, then clarified "yeah, show the pack size" — so when he says a quantity isn't shown, check whether he actually means the unit/pack-size notation is missing. Confidence: 0.55
- For new operational switches/flags, prefers a backend constant in the admin-editable constants store (CONST_KEYS + seed + exposed via essentialConsts, editable in Customize App) over build/publish-time config (e.g. an `expo.extra` flag in app.json) or hardcoding — chosen when offered the trade-off ("let's introduce a new constant"), because it can be changed remotely with no rebuild or republish. Confidence: 0.6
- 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
- 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
- Wants a markdown file placed INSIDE the test directory (e.g. `apps/user-ui/tests/home-page/README.md`) that enumerates every test case covered — all cases grouped by test file with the per-file count and a one-line "what it asserts" for each, plus how to run the suite and the folder layout ("now make an md file in the dir which lists all the test cases which we've covered"). Coverage documentation should live with the tests it describes, not only in a central report. Confidence: 0.65
- Groups unit/integration tests by the page or feature they cover into a dedicated subfolder inside the app's `tests/` directory — e.g., `apps/user-ui/tests/home-page/` holding that page's test files while shared mocks/fixtures stay at the `tests/` root ("create a folder home page and then move the tests of that page in it"). Confidence: 0.7
- When adding coverage, expects the agent to determine and state explicitly whether any additional API mock responses are needed for the new tests — reusing/extending the existing mock infrastructure (variants of already-mocked endpoints, local storage for the cart) rather than adding unnecessary new mocks ("Do we need mock response of any other apis?"). Confidence: 0.6
- Expects EVERY page and EVERY component of an app to be covered by tests — not a sample — and wants tests organized by concern into separate folders under the app's `tests/` directory, including a dedicated folder for components ("I want every page and every component tested. If needed create separate test folder for components too"). Reconfirms by objecting to any leftover uncovered surface and demanding full coverage before stopping ("why are you leaving things uncovered. Cover all the things."). Confidence: 0.88
- When a button/control in the UI triggers a network call, expects a test case that explicitly asserts the API was invoked — "When buttons which trigger api calls are clicked, write an expected case for the api to be called" — treating the call assertion as a required part of coverage, not optional. Confidence: 0.85
- Wants a canonical test-case document kept PER PROJECT named exactly `test-case-info.md`, listing every covered test case ("Keep an md file per project which lists down the test cases. Call it test-case-info.md"); uses the specified filename verbatim rather than an ad-hoc one. Wants it to enumerate EVERY individual case rather than summarize — "I want the test-case-info.md to list all the cases we have" — grouped by area then test file, each file its own section with a per-file count, and one row per case giving the test name and what it asserts (including the API procedure each mutating case pins down), with the counts reconciling to the suite total. Confidence: 0.8
- Wants test mocks to mirror the REAL backend's data shape and format — points the agent at the backend app (`Look at the @apps/backend for the data shape and format`) and expects mock payloads derived from the actual routers/types/schemas rather than invented structures. Confidence: 0.7
- On long, already-scoped/approved tasks, wants the agent to run straight through to completion autonomously and NOT pause for reviews or check-in approvals — explicitly: "continue. don't stop until you're done with all the tests. Don't ask for reviews." Progress checkpoints that ask "want me to continue, or pause for review?" are unwanted unless a genuine blocker/decision is hit. He equally rejects the agent parking in-scope work as "pending/remaining": when a checkpoint listed the still-to-cover items he pushed back — "why leave it pending. GO ahead and write it" — expecting the agent to keep writing the already-planned tests (product-detail, checkout, address components, remaining hooks) rather than stopping to enumerate a roadmap. Confidence: 0.9
- For credential-gated work, wants to supply the credentials himself and not paste secrets into the chat: he asks the agent to scaffold a blank template (committed `.env.example` + git-ignored `.env`) and he fills in the real values ("I'll provide the creds for both the apps"). Expects the agent to then authenticate with those credentials — "you then need to login, get the tokens and then move ahead" — i.e. log in once, obtain the tokens (staff and user) and reuse the issued tokens for the rest of the flow rather than re-authenticating per call or hard-coding/committing secrets. Confirmed again when he filled the git-ignored `apps/backend/tests/.env` himself and handed control back ("I've populated the .env file") rather than pasting the values into the chat. Confidence: 0.68
- 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
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
@ -142,3 +168,6 @@ er-ui/app/(drawer)/(tabs)/home/index.tsx, I want similar here") and expects the
y, including details like item counts and container styling. Confidence: 0.9
tes; approval of a redesign's layout/composition does not imply approval of color or theme 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
0.9
ence: 0.9
0.9

10
.gitignore vendored
View file

@ -132,4 +132,12 @@ dist
.pnp.*
type-clusters/*
type-clusters/*
apps/user-ui/android/
apps/admin-ui/android/
.maestro-output/*
apps/admin-ui/.expo/cache/*

View file

@ -2,6 +2,7 @@
## Important instructions
- Don't run any drizzle migrations. User will handle it.
- don't try to run any test from the suite unless user explicitly asks for
## Code Style Guidelines

View file

@ -1,6 +1,6 @@
{
"expo": {
"name": "Symbuyote Admin",
"name": "Freshyo Admin",
"slug": "freshyoadmin",
"version": "1.0.0",
"orientation": "portrait",
@ -62,9 +62,10 @@
"foregroundImage": "./assets/images/symbuyoteadmin.png",
"backgroundColor": "#fff0f6"
},
"edgeToEdgeEnabled": true,
"package": "in.freshyo.adminui",
"intentFilters": [
"edgeToEdgeEnabled": true,
"package": "in.freshyo.adminui",
"googleServicesFile": "./google-services.json",
"intentFilters": [
{
"action": "VIEW",
"autoVerify": true,
@ -95,8 +96,9 @@
"backgroundColor": "#ffffff"
}
],
"expo-secure-store"
],
"expo-secure-store",
"expo-notifications"
],
"experiments": {
"typedRoutes": true
},

View file

@ -9,20 +9,7 @@ export default function CreateCoupon() {
const router = useRouter();
const createCoupon = trpc.admin.coupon.create.useMutation();
const createReservedCoupon = trpc.admin.coupon.createReservedCoupon.useMutation();
const { refetch: refetchCoupons } = trpc.admin.coupon.getAll.useInfiniteQuery(
{ limit: 20, search: '' },
{
enabled: false,
getNextPageParam: (lastPage) => lastPage.nextCursor,
}
)
const { refetch: refetchReservedCoupons } = trpc.admin.coupon.getReservedCoupons.useInfiniteQuery(
{ limit: 20, search: '' },
{
enabled: false,
getNextPageParam: (lastPage) => lastPage.nextCursor,
}
)
const utils = trpc.useUtils();
const handleCreateCoupon = async (values: any) => {
const { isReservedCoupon, couponCodes, ...rest } = values;
@ -47,8 +34,9 @@ export default function CreateCoupon() {
const mutation = isReservedCoupon ? createReservedCoupon : createCoupon;
try {
await mutation.mutateAsync({ ...payload, couponCodes: codes });
await refetchCoupons()
await refetchReservedCoupons()
// Invalidate by path so the list refreshes whatever search term it holds.
utils.admin.coupon.getAll.invalidate()
utils.admin.coupon.getReservedCoupons.invalidate()
Alert.alert('Success', `${codes.length} coupon${codes.length > 1 ? 's' : ''} created successfully`, [
{ text: 'OK', onPress: () => router.back() }
]);

View file

@ -13,21 +13,8 @@ export default function EditCoupon() {
const couponId = parseInt(id as string);
const { data: coupon, isLoading, refetch } = trpc.admin.coupon.getById.useQuery({ id: couponId });
const { refetch: refetchCoupons } = trpc.admin.coupon.getAll.useInfiniteQuery(
{ limit: 20, search: '' },
{
enabled: false,
getNextPageParam: (lastPage) => lastPage.nextCursor,
}
)
const { refetch: refetchReservedCoupons } = trpc.admin.coupon.getReservedCoupons.useInfiniteQuery(
{ limit: 20, search: '' },
{
enabled: false,
getNextPageParam: (lastPage) => lastPage.nextCursor,
}
)
const updateCoupon = trpc.admin.coupon.update.useMutation();
const utils = trpc.useUtils();
const handleUpdateCoupon = (values: CreateCouponPayload & { isReservedCoupon?: boolean }) => {
// Transform targetUsers array to targetUser for backend compatibility
@ -45,8 +32,9 @@ export default function EditCoupon() {
updateCoupon.mutate({ id: couponId, updates }, {
onSuccess: async () => {
await refetch()
await refetchCoupons()
await refetchReservedCoupons()
// Invalidate by path so the list refreshes whatever search term it holds.
utils.admin.coupon.getAll.invalidate()
utils.admin.coupon.getReservedCoupons.invalidate()
Alert.alert('Success', 'Coupon updated successfully', [
{ text: 'OK', onPress: () => router.back() }
]);

View file

@ -21,7 +21,6 @@ import {
import { useRouter } from "expo-router";
import { trpc } from "../../../../src/trpc-client";
import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import { useQueryClient } from "@tanstack/react-query";
const { width: screenWidth } = Dimensions.get("window");
// Item takes full width minus padding
@ -88,7 +87,7 @@ const ProductItem: React.FC<DragOrderItemProps<Product>> = ({
export default function AllItemsOrder() {
const router = useRouter();
const queryClient = useQueryClient();
const utils = trpc.useUtils();
const [products, setProducts] = useState<Product[]>([]);
const [hasChanges, setHasChanges] = useState(false);
@ -177,7 +176,7 @@ export default function AllItemsOrder() {
onSuccess: () => {
setHasChanges(false);
Alert.alert('Success', 'All items order updated successfully!');
queryClient.invalidateQueries({ queryKey: ['const.getConstants'] });
utils.admin.const.getConstants.invalidate();
},
onError: (error) => {
Alert.alert('Error', 'Failed to update items order. Please try again.');

View file

@ -28,6 +28,8 @@ const CONST_LABELS: Record<string, string> = {
isFlashDeliveryEnabled: 'Enable Flash Delivery',
supportMobile: 'Support Mobile',
supportEmail: 'Support Email',
internalAppVersion: 'Internal App Version',
welcomeMessage: 'Welcome Message',
};
const CONST_VISIBILITY: Record<string, boolean> = {
@ -36,20 +38,22 @@ const CONST_VISIBILITY: Record<string, boolean> = {
deliveryCharge: true,
flashFreeDeliveryThreshold: true,
flashDeliveryCharge: true,
platformFeePercent: true,
platformFeePercent: false,
taxRate: false,
minOrderAmountForCoupon: true,
minOrderAmountForCoupon: false,
maxCouponDiscount: false,
flashDeliverySlotId: true,
flashDeliverySlotId: false,
readableOrderId: false,
versionNum: true,
playStoreUrl: true,
appStoreUrl: true,
versionNum: false,
playStoreUrl: false,
appStoreUrl: false,
popularItems: true,
allItemsOrder: true,
isFlashDeliveryEnabled: true,
supportMobile: true,
supportEmail: true,
internalAppVersion: false,
welcomeMessage: true,
tester: false,
};
@ -157,6 +161,23 @@ const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFi
);
}
// Welcome message — multiline text area
if (constantKey === 'welcomeMessage') {
return (
<MyTextInput
topLabel={CONST_LABELS[constantKey] || constantKey}
value={value === null || value === undefined ? '' : String(value)}
onChangeText={(value) => {
setFieldValue(fieldName, value)
}}
placeholder="Enter welcome message"
multiline
numberOfLines={4}
style={tw`min-h-24`}
/>
);
}
// Default to string
return (
<MyTextInput

View file

@ -23,7 +23,6 @@ import ProductsSelector from "../../../../components/ProductsSelector";
import { useRouter } from "expo-router";
import { trpc } from "../../../../src/trpc-client";
import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import { useQueryClient } from "@tanstack/react-query";
import type { StoreProductCard } from '@packages/shared';
import type { DragOrderItemProps } from '@/types/drag-order-item';
@ -113,7 +112,7 @@ const ProductItem: React.FC<ProductItemProps> = ({
export default function CustomizePopularItems() {
const router = useRouter();
const queryClient = useQueryClient();
const utils = trpc.useUtils();
const [popularProducts, setPopularProducts] = useState<PopularProduct[]>([]);
const [hasChanges, setHasChanges] = useState(false);
const [showAddDialog, setShowAddDialog] = useState(false);
@ -211,7 +210,7 @@ export default function CustomizePopularItems() {
onSuccess: () => {
setHasChanges(false);
Alert.alert('Success', 'Popular items updated successfully!');
queryClient.invalidateQueries({ queryKey: ['const.getConstants'] });
utils.admin.const.getConstants.invalidate();
},
onError: (error) => {
Alert.alert('Error', 'Failed to update popular items. Please try again.');

View file

@ -36,6 +36,7 @@ export default function EditBanner() {
enabled: false,
});
const [banner, setBanner] = useState<typeof bannerData>(undefined);
const utils = trpc.useUtils();
useEffect(() => {
@ -105,6 +106,8 @@ export default function EditBanner() {
});
await refetchBanners()
// This screen renders getBanner (and mirrors it into local state).
utils.admin.banner.getBanner.invalidate();
Alert.alert('Success', 'Banner updated successfully', [
{
text: 'OK',

View file

@ -148,6 +148,9 @@ export default function DashboardBanners() {
serialNum: null
});
// getBanners carries the serialNum -> slot labels this list renders.
refetch();
// Update local state
setSlotAssignments(prev => ({
...prev,

View file

@ -29,6 +29,8 @@ const MenuItemComponent: React.FC<MenuItemComponentProps> = ({ item, router }) =
return (
<Pressable
testID={item.testID}
accessibilityLabel={item.testID}
onPress={() => item.onPress ? item.onPress() : router.push(item.route as any)}
style={({ pressed }) => [
tw`flex-row items-center p-4 bg-white border border-gray-100 rounded-xl mb-3 shadow-sm`,
@ -108,6 +110,7 @@ export default function Dashboard() {
description: 'Create a new product listing',
route: '/(drawer)/dashboard/products/add',
category: 'quick',
testID: 'add-product-menu-item',
iconColor: theme.colors.brand500,
iconBg: theme.colors.brand50,
},

View file

@ -46,6 +46,7 @@ interface OrderWithSequence {
adminNotes?: string | null;
customerName?: string | null;
assignedUserName?: string | null;
isFirstOrder?: boolean;
}
interface SlotProgressProps {
@ -449,6 +450,10 @@ export default function DeliverySequences() {
onSuccess: () => {
setHasSequenceChanged(false);
Alert.alert("Success", "Delivery sequence updated successfully");
// The saved sequence lives in getDeliverySequence / getSlotOrders, both of which
// stay mounted on this screen.
refetchSequence();
refetchOrders();
},
onError: (error: any) => {
Alert.alert(
@ -718,6 +723,7 @@ export default function DeliverySequences() {
adminNotes: selectedOrder?.adminNotes || null,
latitude: selectedOrder?.latitude || null,
longitude: selectedOrder?.longitude || null,
isFirstOrder: selectedOrder?.isFirstOrder ?? false,
}}
onViewDetails={() => {
if (selectedOrder) {
@ -763,7 +769,10 @@ export default function DeliverySequences() {
setShowOrderMenu(false);
setCancelDialogOpen(true);
}}
onAttachLocation={() => {}}
onAttachLocation={() => {
refetchOrders();
refetchSequence();
}}
onWhatsApp={() => {}}
onDial={() => {}}
/>

View file

@ -48,6 +48,7 @@ export default function OrderDetails() {
: "N/A"
}`
);
refetch();
setGenerateCouponDialogOpen(false);
},
onError: (error: any) => {
@ -66,6 +67,7 @@ export default function OrderDetails() {
`Refund initiated successfully!\n\nAmount: `
// `Refund initiated successfully!\n\nAmount: ₹${result.amount}\nStatus: ${result.status}`
);
refetch();
setInitiateRefundDialogOpen(false);
},
onError: (error: any) => {

View file

@ -366,6 +366,7 @@ const OrderItem = ({ order, refetch }: { order: OrderType; refetch: () => void }
latitude: order.latitude,
longitude: order.longitude,
status: order.status,
isFirstOrder: order.isFirstOrder,
}}
onViewDetails={handleMenuOption}
onTogglePackaged={() => handleMarkPackaged(!order.isPackaged)}

View file

@ -23,6 +23,7 @@ export default function EditTag() {
enabled: false,
});
const updateTag = trpc.admin.product.updateProductTag.useMutation();
const utils = trpc.useUtils();
const { data: storesData } = trpc.admin.store.getStores.useQuery();
const { upload, isUploading } = useUploadToObjectStorage();
@ -59,6 +60,8 @@ export default function EditTag() {
})
await refetchTags()
// The detail query this screen was seeded from is not the list.
utils.admin.product.getProductTagById.invalidate();
Alert.alert('Success', 'Tag updated successfully', [
{
text: 'OK',

View file

@ -20,7 +20,6 @@ import {
import { useRouter } from 'expo-router';
import { trpc } from '../../../../src/trpc-client';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { useQueryClient } from '@tanstack/react-query';
import type { DragOrderItemProps } from '@/types/drag-order-item';
const { width: screenWidth } = Dimensions.get('window');
@ -79,7 +78,7 @@ const TagItem: React.FC<DragOrderItemProps<Tag>> = ({ item, drag, isActive }) =>
export default function TagOrders() {
const router = useRouter();
const queryClient = useQueryClient();
const utils = trpc.useUtils();
const [tags, setTags] = useState<Tag[]>([]);
const [hasChanges, setHasChanges] = useState(false);
@ -166,7 +165,7 @@ export default function TagOrders() {
onSuccess: () => {
setHasChanges(false);
Alert.alert('Success', 'Tag order updated successfully!');
queryClient.invalidateQueries({ queryKey: ['const.getConstants'] });
utils.admin.const.getConstants.invalidate();
},
onError: (error) => {
Alert.alert('Error', 'Failed to update tag order. Please try again.');

View file

@ -1,10 +1,19 @@
import React from 'react'
import { Alert } from 'react-native'
import { AppContainer, ImageUploaderNeoPayload } from 'common-ui'
import { Alert, View } from 'react-native'
import { ImageUploaderNeoPayload, tw } from 'common-ui'
import ProductForm from '@/src/components/ProductForm'
import { trpc } from '@/src/trpc-client'
import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore'
// SKUs store bucket-relative object keys, not URLs. Drop the query string and
// keep the last two path segments:
// https://<acct>.r2.cloudflarestorage.com/meatfarmer-dev/product-images/1.jpg?X-Amz-...
// -> product-images/1.jpg
const toImageKey = (url: string): string => {
const parts = url.split('?')[0].split('/').filter(Boolean)
return parts.slice(-2).join('/')
}
export default function AddProduct() {
const createProduct = trpc.admin.product.createProduct.useMutation()
const { refetch: refetchProducts } = trpc.admin.product.getProducts.useQuery(undefined, {
@ -63,7 +72,8 @@ export default function AddProduct() {
let urlCursor = 0
const skus = values.variants.map((variant: any, vIndex: number) => {
const count = imageCounts[vIndex]
const variantUrls = allUploadUrls.slice(urlCursor, urlCursor + count)
// Send keys, not the presigned URLs.
const variantUrls = allUploadUrls.slice(urlCursor, urlCursor + count).map(toImageKey)
urlCursor += count
return {
@ -129,13 +139,13 @@ export default function AddProduct() {
}
return (
<AppContainer>
<View style={tw`flex-1 bg-white`}>
<ProductForm
mode="create"
initialValues={initialValues}
onSubmit={handleSubmit}
isLoading={createProduct.isPending || isUploading}
/>
</AppContainer>
</View>
)
}

View file

@ -26,6 +26,7 @@ const ReviewResponseForm: React.FC<ReviewResponseFormProps> = ({ reviewId, onClo
const [displayImages, setDisplayImages] = useState<{ uri?: string }[]>([]);
const respondToReview = trpc.admin.product.respondToReview.useMutation();
const utils = trpc.useUtils();
const { upload } = useUploadToObjectStorage();
const handleImagePick = usePickImage({
@ -74,6 +75,8 @@ const ReviewResponseForm: React.FC<ReviewResponseFormProps> = ({ reviewId, onClo
uploadUrls: presignedUrls,
});
// The parent screen's reviews list stays mounted behind this dialog, so refresh it.
utils.admin.product.getProductReviews.invalidate();
Alert.alert('Success', 'Response submitted');
onClose();
setAdminResponse('');

View file

@ -6,6 +6,15 @@ import ProductForm, { ProductFormRef } from '@/src/components/ProductForm';
import { trpc } from '@/src/trpc-client';
import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore';
// SKUs store bucket-relative object keys, not URLs. Drop the query string and
// keep the last two path segments:
// https://<acct>.r2.cloudflarestorage.com/meatfarmer-dev/product-images/1.jpg?X-Amz-...
// -> product-images/1.jpg
const toImageKey = (url: string): string => {
const parts = url.split('?')[0].split('/').filter(Boolean)
return parts.slice(-2).join('/')
}
export default function EditProduct() {
const { id } = useLocalSearchParams();
const productId = Number(id);
@ -140,9 +149,10 @@ export default function EditProduct() {
// Existing images (mimeType === null) stay as-is
const existingUrls = variantImages[vIndex]
?.filter((img) => img.mimeType === null)
.map((img) => img.url) || []
.map((img) => toImageKey(img.url)) || []
const allUrls = [...existingUrls, ...newUrls]
// Send keys, not URLs — the SKU stores the bucket-relative object key.
const allUrls = [...existingUrls, ...newUrls.map(toImageKey)]
return {
id: variant.id,
@ -209,7 +219,7 @@ export default function EditProduct() {
}
return (
<AppContainer>
<View style={tw`flex-1 bg-white`}>
<ProductForm
ref={productFormRef}
mode="edit"
@ -219,6 +229,6 @@ export default function EditProduct() {
existingVariantImages={existingVariantImages}
existingVariantImageKeys={existingVariantImageKeys}
/>
</AppContainer>
</View>
);
}

View file

@ -1,9 +1,9 @@
import React, { useState, useMemo } from 'react';
import { View, TouchableOpacity, RefreshControl } from 'react-native';
import React, { useState, useMemo, useCallback } from 'react';
import { View, TouchableOpacity } from 'react-native';
import { Image } from 'expo-image';
import { useRouter } from 'expo-router';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { AppContainer, MyText, tw, MyButton, useManualRefresh, SearchBar, useMarkDataFetchers, MyFlatList } from 'common-ui';
import { MyText, tw, MyButton, useManualRefresh, SearchBar, useMarkDataFetchers, MyFlatList } from 'common-ui';
import { trpc } from '@/src/trpc-client';
import { SuccessToast, ErrorToast } from '@/services/toaster';
@ -13,15 +13,130 @@ type FilterType = 'all' | 'in-stock' | 'out-of-stock';
type SerializedAdminSku = Omit<AdminSku, 'createdAt'> & { createdAt: string | Date }
function getDefaultSku(product: { skus: SerializedAdminSku[] }): SerializedAdminSku | null {
function getDefaultSku(product: { skus?: SerializedAdminSku[] }): SerializedAdminSku | null {
return product.skus?.[0] ?? null
}
function FilterButton({
filter,
label,
count,
activeFilter,
onSelect,
}: {
filter: FilterType
label: string
count: number
activeFilter: FilterType
onSelect: (filter: FilterType) => void
}) {
const isActive = activeFilter === filter
return (
<TouchableOpacity
onPress={() => onSelect(filter)}
style={tw`px-4 py-2 rounded-lg ${isActive ? 'bg-blue-500' : 'bg-gray-200'}`}
>
<MyText style={tw`${isActive ? 'text-white' : 'text-gray-700'} font-semibold`}>
{label} ({count})
</MyText>
</TouchableOpacity>
)
}
type ProductRowProps = {
product: any
isToggling: boolean
onView: (productId: number) => void
onEdit: (productId: number) => void
onToggle: (product: { id: number }) => void
}
const ProductRow = React.memo(function ProductRow({ product, isToggling, onView, onEdit, onToggle }: ProductRowProps) {
const defaultSku = getDefaultSku(product)
const skuImages = defaultSku?.images ?? null
const isOut = defaultSku?.isOutOfStock ?? false
return (
<View style={tw`bg-white rounded-2xl shadow-lg mb-4 overflow-hidden`}>
{/* Product Image */}
{skuImages && skuImages.length > 0 ? (
<Image
source={{ uri: skuImages[0] }}
style={tw`w-full h-48`}
contentFit="cover"
cachePolicy="memory-disk"
recyclingKey={String(product.id)}
/>
) : (
<View style={tw`w-full h-48 bg-gray-200 justify-center items-center`}>
<MaterialIcons name="image" size={48} color="#9CA3AF" />
</View>
)}
{/* Product Info */}
<View style={tw`p-4`}>
<View style={tw`flex-row justify-between items-start mb-2`}>
<MyText style={tw`text-lg font-bold text-gray-800 flex-1 mr-2`} numberOfLines={2}>
{product.name}
</MyText>
<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'}
</MyText>
</View>
</View>
{product.shortDescription && (
<MyText style={tw`text-gray-600 mb-2`} numberOfLines={2}>
{product.shortDescription}
</MyText>
)}
<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
</MyText>
</View>
{/* Action Buttons */}
<View style={tw`flex-row gap-2`}>
<TouchableOpacity
onPress={() => onView(product.id)}
style={tw`flex-1 bg-gray-500 p-3 rounded-lg flex-row items-center justify-center`}
>
<MaterialIcons name="visibility" size={16} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>View</MyText>
</TouchableOpacity>
<TouchableOpacity
onPress={() => onEdit(product.id)}
style={tw`flex-1 bg-blue-500 p-3 rounded-lg flex-row items-center justify-center`}
>
<MaterialIcons name="edit" size={16} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>Edit</MyText>
</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' : ''}`}
>
<MaterialIcons name={isOut ? 'check-circle' : 'block'} size={16} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>
{isOut ? 'Stock' : 'Out'}
</MyText>
</TouchableOpacity>
</View>
</View>
</View>
)
})
export default function Products() {
const router = useRouter();
const [searchTerm, setSearchTerm] = useState('');
const [activeFilter, setActiveFilter] = useState<FilterType>('all');
const [refreshing, setRefreshing] = useState(false);
const { data: productsData, isLoading, error, refetch } = trpc.admin.product.getProducts.useQuery();
@ -43,18 +158,17 @@ export default function Products() {
const products = productsData?.products || [];
const handleRefresh = async () => {
setRefreshing(true);
const handleRefresh = useCallback(async () => {
await refetch();
setRefreshing(false);
};
}, [refetch]);
const filteredProducts = useMemo(() => {
const term = searchTerm.toLowerCase();
return products.filter(product => {
const defaultSku = getDefaultSku(product)
const matchesSearch = product.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
(product.shortDescription?.toLowerCase().includes(searchTerm.toLowerCase()));
const matchesSearch = product.name.toLowerCase().includes(term) ||
(product.shortDescription?.toLowerCase().includes(term));
const matchesFilter = activeFilter === 'all' ||
(activeFilter === 'in-stock' && !defaultSku?.isOutOfStock) ||
@ -64,64 +178,47 @@ export default function Products() {
});
}, [products, searchTerm, activeFilter]);
const handleEdit = (productId: number) => {
router.push(`/(drawer)/dashboard/products/edit?id=${productId}` as any);
};
const handleViewDetails = (productId: number) => {
router.push(`/(drawer)/dashboard/products/detail/${productId}` as any);
};
const handleToggleStock = (product: { id: number }) => {
toggleOutOfStock.mutate({ id: product.id });
};
const FilterButton = ({ filter, label, count }: { filter: FilterType; label: string; count: number }) => (
<TouchableOpacity
onPress={() => setActiveFilter(filter)}
style={tw`px-4 py-2 rounded-lg ${activeFilter === filter ? 'bg-blue-500' : 'bg-gray-200'}`}
>
<MyText style={tw`${activeFilter === filter ? 'text-white' : 'text-gray-700'} font-semibold`}>
{label} ({count})
</MyText>
</TouchableOpacity>
const inStockCount = useMemo(
() => products.filter(p => { const sku = getDefaultSku(p); return sku && !sku.isOutOfStock }).length,
[products]
);
const outOfStockCount = useMemo(
() => products.filter(p => getDefaultSku(p)?.isOutOfStock).length,
[products]
);
if (isLoading) {
return (
<AppContainer>
<View style={tw`flex-1 justify-center items-center`}>
<MyText style={tw`text-gray-600`}>Loading products...</MyText>
</View>
</AppContainer>
);
}
const handleEdit = useCallback((productId: number) => {
router.push(`/(drawer)/dashboard/products/edit?id=${productId}` as any);
}, [router]);
if (error) {
return (
<AppContainer>
<View style={tw`flex-1 justify-center items-center`}>
<MyText style={tw`text-red-600`}>Error loading products</MyText>
<TouchableOpacity
onPress={() => refetch()}
style={tw`mt-4 bg-blue-500 px-4 py-2 rounded-lg`}
>
<MyText style={tw`text-white font-semibold`}>Retry</MyText>
</TouchableOpacity>
</View>
</AppContainer>
);
}
const handleViewDetails = useCallback((productId: number) => {
router.push(`/(drawer)/dashboard/products/detail/${productId}` as any);
}, [router]);
const inStockCount = products.filter(p => getDefaultSku(p) && !getDefaultSku(p)!.isOutOfStock).length;
const outOfStockCount = products.filter(p => getDefaultSku(p)?.isOutOfStock).length;
const handleToggleStock = useCallback((product: { id: number }) => {
toggleOutOfStock.mutate({ id: product.id });
}, [toggleOutOfStock]);
const listHeader = (
const handleSelectFilter = useCallback((filter: FilterType) => setActiveFilter(filter), []);
const keyExtractor = useCallback((item: { id: number }) => item.id.toString(), []);
const renderItem = useCallback(({ item: product }: { item: any }) => (
<ProductRow
product={product}
isToggling={toggleOutOfStock.isPending && toggleOutOfStock.variables?.id === product.id}
onView={handleViewDetails}
onEdit={handleEdit}
onToggle={handleToggleStock}
/>
), [toggleOutOfStock.isPending, toggleOutOfStock.variables?.id, handleViewDetails, handleEdit, handleToggleStock]);
const listHeader = useMemo(() => (
<>
{/* Header */}
<View style={tw`flex-row justify-between items-center mb-6`}>
<MyText style={tw`text-2xl font-bold text-gray-800`}>Products</MyText>
<MyButton onPress={() => router.push('/(drawer)/dashboard/products/add' as any)}>
<MyButton testID="add-product-button" onPress={() => router.push('/(drawer)/dashboard/products/add' as any)}>
Add Product
</MyButton>
</View>
@ -138,130 +235,72 @@ export default function Products() {
{/* Filter Tabs */}
<View style={tw`flex-row gap-2 mb-6`}>
<FilterButton filter="all" label="All" count={products.length} />
<FilterButton filter="in-stock" label="In Stock" count={inStockCount} />
<FilterButton filter="out-of-stock" label="Out of Stock" count={outOfStockCount} />
<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} />
</View>
</>
);
const renderItem = ({ item: product }: { item: any }) => {
const defaultSku = getDefaultSku(product)
const skuImages = defaultSku?.images ?? null
const isOut = defaultSku?.isOutOfStock ?? false
), [products.length, inStockCount, outOfStockCount, searchTerm, activeFilter, handleSelectFilter, router]);
if (isLoading) {
return (
<View key={product.id} style={tw`bg-white rounded-2xl shadow-lg mb-4 overflow-hidden`}>
{/* Product Image */}
{skuImages && skuImages.length > 0 ? (
<Image
source={{ uri: skuImages[0] }}
style={tw`w-full h-48`}
resizeMode="cover"
/>
) : (
<View style={tw`w-full h-48 bg-gray-200 justify-center items-center`}>
<MaterialIcons name="image" size={48} color="#9CA3AF" />
</View>
)}
{/* Product Info */}
<View style={tw`p-4`}>
<View style={tw`flex-row justify-between items-start mb-2`}>
<MyText style={tw`text-lg font-bold text-gray-800 flex-1 mr-2`} numberOfLines={2}>
{product.name}
</MyText>
<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'}
</MyText>
</View>
</View>
{product.shortDescription && (
<MyText style={tw`text-gray-600 mb-2`} numberOfLines={2}>
{product.shortDescription}
</MyText>
)}
<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
</MyText>
</View>
{/* Action Buttons */}
<View style={tw`flex-row gap-2`}>
<TouchableOpacity
onPress={() => handleViewDetails(product.id)}
style={tw`flex-1 bg-gray-500 p-3 rounded-lg flex-row items-center justify-center`}
>
<MaterialIcons name="visibility" size={16} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>View</MyText>
</TouchableOpacity>
<TouchableOpacity
onPress={() => handleEdit(product.id)}
style={tw`flex-1 bg-blue-500 p-3 rounded-lg flex-row items-center justify-center`}
>
<MaterialIcons name="edit" size={16} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>Edit</MyText>
</TouchableOpacity>
<TouchableOpacity
onPress={() => handleToggleStock(product)}
disabled={toggleOutOfStock.isPending && toggleOutOfStock.variables?.id === product.id}
style={tw`flex-1 ${isOut ? 'bg-green-500' : 'bg-orange-500'} p-3 rounded-lg flex-row items-center justify-center ${toggleOutOfStock.isPending && toggleOutOfStock.variables?.id === product.id ? 'opacity-50' : ''}`}
>
<MaterialIcons name={isOut ? 'check-circle' : 'block'} size={16} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>
{isOut ? 'Stock' : 'Out'}
</MyText>
</TouchableOpacity>
</View>
</View>
<View style={tw`flex-1 bg-white justify-center items-center`}>
<MyText style={tw`text-gray-600`}>Loading products...</MyText>
</View>
)
};
);
}
if (error) {
return (
<View style={tw`flex-1 bg-white justify-center items-center`}>
<MyText style={tw`text-red-600`}>Error loading products</MyText>
<TouchableOpacity
onPress={() => refetch()}
style={tw`mt-4 bg-blue-500 px-4 py-2 rounded-lg`}
>
<MyText style={tw`text-white font-semibold`}>Retry</MyText>
</TouchableOpacity>
</View>
);
}
return (
<AppContainer>
<View style={tw`flex-1`}>
<MyFlatList
data={filteredProducts}
renderItem={renderItem}
keyExtractor={(item) => item.id.toString()}
ListHeaderComponent={listHeader}
ListEmptyComponent={
<View style={tw`flex-1 justify-center items-center py-10`}>
<MaterialIcons name="inventory" size={64} color="#D1D5DB" />
<MyText style={tw`text-gray-500 text-center mt-4 text-lg`}>
{searchTerm || activeFilter !== 'all' ? 'No products match your filters' : 'No products found'}
</MyText>
<MyText style={tw`text-gray-400 text-center mt-2`}>
{searchTerm || activeFilter !== 'all' ? 'Try adjusting your search or filters' : 'Start by adding your first product'}
</MyText>
{(searchTerm || activeFilter !== 'all') && (
<TouchableOpacity
onPress={() => {
setSearchTerm('');
setActiveFilter('all');
}}
style={tw`mt-4 bg-blue-500 px-4 py-2 rounded-lg`}
>
<MyText style={tw`text-white font-semibold`}>Clear Filters</MyText>
</TouchableOpacity>
)}
</View>
}
contentContainerStyle={tw`pb-4`}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />
}
/>
</View>
</AppContainer>
<View style={tw`flex-1 bg-white`}>
<MyFlatList
data={filteredProducts}
renderItem={renderItem}
keyExtractor={keyExtractor}
ListHeaderComponent={listHeader}
ListEmptyComponent={
<View style={tw`flex-1 justify-center items-center py-10`}>
<MaterialIcons name="inventory" size={64} color="#D1D5DB" />
<MyText style={tw`text-gray-500 text-center mt-4 text-lg`}>
{searchTerm || activeFilter !== 'all' ? 'No products match your filters' : 'No products found'}
</MyText>
<MyText style={tw`text-gray-400 text-center mt-2`}>
{searchTerm || activeFilter !== 'all' ? 'Try adjusting your search or filters' : 'Start by adding your first product'}
</MyText>
{(searchTerm || activeFilter !== 'all') && (
<TouchableOpacity
onPress={() => {
setSearchTerm('');
setActiveFilter('all');
}}
style={tw`mt-4 bg-blue-500 px-4 py-2 rounded-lg`}
>
<MyText style={tw`text-white font-semibold`}>Clear Filters</MyText>
</TouchableOpacity>
)}
</View>
}
contentContainerStyle={tw`p-4`}
showsVerticalScrollIndicator={false}
onRefresh={handleRefresh}
initialNumToRender={6}
maxToRenderPerBatch={8}
windowSize={5}
removeClippedSubviews
/>
</View>
);
}

View file

@ -1,7 +1,7 @@
import React, { useState } from 'react';
import { MaterialCommunityIcons, Entypo } from '@expo/vector-icons';
import { View, TouchableOpacity, FlatList, Alert, ActivityIndicator } from 'react-native';
import { AppContainer, MyText, tw, MyFlatList , BottomDialog, MyTouchableOpacity, Checkbox } from 'common-ui';
import { MyText, tw, MyFlatList , BottomDialog, MyTouchableOpacity, Checkbox } from 'common-ui';
import { trpc } from '@/src/trpc-client';
import { useRouter } from 'expo-router';
import dayjs from 'dayjs';

View file

@ -198,6 +198,7 @@ export default function SlotDetails() {
{/* FAB for Edit Slot */}
<MyTouchableOpacity
testID="edit-slot-fab"
onPress={() => router.push(`/(drawer)/dashboard/slots/edit/${slot.id}` as any)}
activeOpacity={0.95}
style={{ position: 'absolute', bottom: 32, right: 24, zIndex: 100 }}

View file

@ -17,11 +17,14 @@ export default function EditStore() {
);
const updateStoreMutation = trpc.admin.store.updateStore.useMutation();
const utils = trpc.useUtils();
const handleSubmit = (values: StoreFormData) => {
updateStoreMutation.mutate({ id: storeId, ...values }, {
onSuccess: (data) => {
refetch();
// The stores list is still mounted behind this screen.
utils.admin.store.getStores.invalidate();
Alert.alert('Success', data.message);
router.push('/(drawer)/dashboard/stores' as any);
},

View file

@ -1,25 +1,40 @@
import { QueryClientProvider } from "@tanstack/react-query";
import queryClient from "../utils/queryClient";
import { Stack } from "expo-router";
import { LogBox } from "react-native";
import { StaffAuthProvider } from "@/components/context/staff-auth-context";
import { trpc, trpcClient } from "@/src/trpc-client";
import { SafeAreaView } from "react-native-safe-area-context";
import { RefreshProvider } from '../../../packages/ui/src/lib/refresh-context';
import Toast from "react-native-toast-message";
import { NotificationProvider } from "@/services/notif-service/notif-context";
import NotifChecker from "@/services/notif-service/notif-checker";
// Silence dev warnings/errors in LogBox. The "Open debugger to view warnings"
// toast overlays the bottom of the UI and intercepts taps (e.g. the Add Slot
// FAB), which breaks E2E flows.
if (__DEV__) {
LogBox.ignoreAllLogs(true);
}
export default function Layout() {
return (
<QueryClientProvider client={queryClient}>
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<StaffAuthProvider>
<SafeAreaView
edges={['left', 'right', 'bottom']}
style={{ flex: 1, backgroundColor: '#fff' }}
testID="app-root"
>
<RefreshProvider queryClient={queryClient}>
<Stack screenOptions={{ headerShown: false }} />
</RefreshProvider>
</SafeAreaView>
<NotificationProvider>
<SafeAreaView
edges={['left', 'right', 'bottom']}
style={{ flex: 1, backgroundColor: '#fff' }}
testID="app-root"
>
<RefreshProvider queryClient={queryClient}>
<Stack screenOptions={{ headerShown: false }} />
</RefreshProvider>
</SafeAreaView>
<NotifChecker />
<Toast />
</NotificationProvider>
</StaffAuthProvider>
</trpc.Provider>
</QueryClientProvider>

View file

@ -28,6 +28,7 @@ interface OrderOptionsMenuProps {
latitude?: number | null;
longitude?: number | null;
status?: string;
isFirstOrder?: boolean;
};
onViewDetails: () => void;
onTogglePackaged: () => void;
@ -53,6 +54,8 @@ export function OrderOptionsMenu({
onDial,
}: OrderOptionsMenuProps) {
const updateAddressCoordsMutation = trpc.admin.order.updateAddressCoords.useMutation();
const { data: constants } = trpc.admin.const.getConstants.useQuery();
const welcomeMessage = constants?.find((c) => c.key === 'welcomeMessage')?.value;
const handleAttachLocation = async () => {
try {
@ -94,6 +97,17 @@ export function OrderOptionsMenu({
}
};
const handleWelcomeWhatsApp = () => {
const phone = extractPhone(order.address);
if (!phone) {
Alert.alert('No phone number found');
return;
}
const message = welcomeMessage ? String(welcomeMessage) : '';
const text = message ? `&text=${encodeURIComponent(message)}` : '';
Linking.openURL(`whatsapp://send?phone=+91${phone}${text}`);
};
const handleDial = () => {
const phone = extractPhone(order.address);
if (phone) {
@ -292,6 +306,30 @@ export function OrderOptionsMenu({
</TouchableOpacity>
)}
{order.isFirstOrder && (
<TouchableOpacity
testID="send-welcome-msg"
style={tw`flex-row items-center p-4 bg-emerald-50 border border-emerald-200 rounded-xl mb-3 shadow-sm`}
onPress={() => {
handleWelcomeWhatsApp();
onClose();
}}
>
<View style={tw`w-10 h-10 rounded-full bg-emerald-100 items-center justify-center mr-4`}>
<MaterialIcons name="celebration" size={20} color="#059669" />
</View>
<View>
<MyText style={tw`font-semibold text-emerald-800 text-base`}>
Send Welcome Msg
</MyText>
<MyText style={tw`text-emerald-600 text-xs`}>
First order — welcome the customer on WhatsApp
</MyText>
</View>
<MaterialIcons name="chevron-right" size={24} color="#9ca3af" style={tw`ml-auto`} />
</TouchableOpacity>
)}
<TouchableOpacity
style={tw`flex-row items-center p-4 bg-white border border-gray-100 rounded-xl mb-3 shadow-sm`}
onPress={() => {

View file

@ -29,6 +29,7 @@ const ProductGroupForm: React.FC<ProductGroupFormProps> = ({
const createGroup = trpc.admin.product.createGroup.useMutation();
const updateGroup = trpc.admin.product.updateGroup.useMutation();
const utils = trpc.useUtils();
const isEditing = !!group;
@ -67,6 +68,8 @@ const ProductGroupForm: React.FC<ProductGroupFormProps> = ({
product_ids: values.product_ids,
});
}
// The groupings list/detail screens render getGroups.
utils.admin.product.getGroups.invalidate();
onSuccess();
} catch (error: any) {
Alert.alert('Error', error.message || 'Failed to save group');

View file

@ -28,6 +28,7 @@ interface ProductsSelectorProps {
selectedGroupIds?: number[];
onGroupChange?: (groupIds: number[]) => void;
showGroups?: boolean;
testID?: string;
}
export default function ProductsSelector({
@ -44,6 +45,7 @@ export default function ProductsSelector({
showGroups = true,
selectedGroupIds = [],
onGroupChange,
testID,
}: ProductsSelectorProps) {
const { data: skusData } = trpc.common.product.getAllSkusSummary.useQuery();
const allSkus: SkuSummary[] = skusData?.skus || [];
@ -147,6 +149,7 @@ export default function ProductsSelector({
)}
<BottomDropdown
testID={testID}
label={label}
options={productOptions}
value={multiple

View file

@ -51,6 +51,7 @@ export default function SlotForm({
const { mutate: createSlot, isPending: isCreating } = trpc.admin.slots.createSlot.useMutation();
const { mutate: updateSlot, isPending: isUpdating } = trpc.admin.slots.updateSlot.useMutation();
const utils = trpc.useUtils();
const isEditMode = !!slotId;
const isPending = isCreating || isUpdating;
@ -87,6 +88,8 @@ export default function SlotForm({
{
onSuccess: () => {
Alert.alert('Success', 'Slot updated successfully!');
// Nothing else refreshes the slot list/detail the admin came from.
utils.admin.slots.invalidate();
onSlotAdded?.();
},
onError: (error: any) => {
@ -160,6 +163,7 @@ export default function SlotForm({
selectedGroupIds={values.selectedGroupIds}
onGroupChange={(newGroupIds) => setFieldValue('selectedGroupIds', newGroupIds)}
label="Select Products"
testID="slot-products-selector"
placeholder="Select products for this slot"
/>
</View>
@ -193,6 +197,7 @@ export default function SlotForm({
selectedGroupIds={snippet.groupIds || []}
onGroupChange={(newGroupIds) => setFieldValue(`vendorSnippetList.${index}.groupIds`, newGroupIds)}
label="Select Products"
testID="snippet-products-selector"
placeholder="Select products for snippet"
isDisabled={(sku) => !values.selectedSkuIds.includes(sku.id)}
/>

View file

@ -0,0 +1,48 @@
{
"project_info": {
"project_number": "535753078248",
"project_id": "freshyo-cefb2",
"storage_bucket": "freshyo-cefb2.firebasestorage.app"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:535753078248:android:a28dec271c1f916b38605d",
"android_client_info": {
"package_name": "in.freshyo.adminui"
}
},
"oauth_client": [],
"api_key": [
{
"current_key": "AIzaSyDW4w6vGDrZnkf8vgwdQObBLnT_iucs2H8"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": []
}
}
},
{
"client_info": {
"mobilesdk_app_id": "1:535753078248:android:d00803550e29eb3238605d",
"android_client_info": {
"package_name": "in.freshyo.app"
}
},
"oauth_client": [],
"api_key": [
{
"current_key": "AIzaSyDW4w6vGDrZnkf8vgwdQObBLnT_iucs2H8"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": []
}
}
}
],
"configuration_version": "1"
}

View file

@ -43,9 +43,11 @@ export function useUploadToObjectStorage() {
headers: { 'Content-Type': mimeType },
});
if (!response.ok) {
throw new Error(`Upload ${index + 1} failed with status ${response.status}`);
}
if (!response.ok) {
const body = await response.text(); // <Error><Code>…</Code></Error>
console.error('upload failed', response.status, body);
throw new Error(`Upload ${index + 1} failed with status ${response.status}`);
}
// Update progress
setProgress(prev => prev ? { ...prev, completed: prev.completed + 1 } : null);

View file

@ -24,4 +24,15 @@ config.resolver.disableHierarchicalLookup = true;
// This is crucial for web builds in a monorepo with expo-router
config.resolver.entryExts = ['js', 'jsx', 'ts', 'tsx', 'mjs', 'cjs'];
// 5. Never bundle the Jest test folder (tests/). It lives outside app/, so it
// is not routed, but blocking it here makes an accidental production import
// fail loudly instead of silently shipping test code.
const escapeForRegExp = (value) =>
value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
config.resolver.blockList = [
...(config.resolver.blockList ? [].concat(config.resolver.blockList) : []),
new RegExp(`^${escapeForRegExp(path.resolve(projectRoot, 'tests'))}[/\\\\].*$`),
];
module.exports = config;

View file

@ -8,7 +8,10 @@
"android": "expo run:android",
"ios": "expo run:ios",
"web": "expo start --web",
"lint": "expo lint"
"lint": "expo lint",
"test": "jest --config tests/jest.config.js",
"test:watch": "jest --config tests/jest.config.js --watch",
"test:typecheck": "tsc --noEmit --project tsconfig.json"
},
"dependencies": {
"@expo/vector-icons": "^14.1.0",
@ -74,7 +77,13 @@
"@types/react-native-razorpay": "^2.2.6",
"eslint": "^9.25.0",
"eslint-config-expo": "~9.2.0",
"typescript": "~5.8.3"
"typescript": "~5.8.3",
"@testing-library/react-native": "^13",
"@types/jest": "^29",
"babel-preset-expo": "~13.0.0",
"jest": "~29.7.0",
"jest-expo": "~53.0.0",
"react-test-renderer": "19.0.0"
},
"private": true
}

View file

@ -0,0 +1,73 @@
import React from "react";
import { useNotification } from "./notif-context";
import { BottomDialog } from "common-ui";
import { MyText } from "common-ui";
import { View, Linking } from "react-native";
import { tw } from "common-ui";
import { MyButton } from "common-ui";
import { useStaffAuth } from "@/components/context/staff-auth-context";
import { trpc } from "@/src/trpc-client";
function NotifChecker() {
const [showPermissionDialog, setShowPermissionDialog] = React.useState(false);
const { isLoggedIn } = useStaffAuth();
const savePushTokenMutation = trpc.admin.staffUser.savePushToken.useMutation();
const { notifPermission, expoPushToken } = useNotification();
React.useEffect(() => {
if (expoPushToken && notifPermission === 'granted' && isLoggedIn) {
savePushTokenMutation.mutate(
{ token: expoPushToken },
{
onError: (error) => {
console.error('Failed to save push token:', error);
},
}
);
}
}, [expoPushToken, notifPermission, isLoggedIn]);
React.useEffect(() => {
if (notifPermission === "denied") {
setShowPermissionDialog(true);
}
}, [notifPermission]);
return (
<BottomDialog
open={showPermissionDialog}
onClose={() => setShowPermissionDialog(false)}
>
<View style={tw`flex flex-col h-64 p-4`}>
<MyText weight="semibold" color="red1" style={tw`mb-2 text-lg`}>
Notification Permission Denied
</MyText>
<MyText>
It seems you have denied notification permissions. Please enable
them in your device settings.
</MyText>
<View style={tw`flex flex-row gap-3 mt-auto justify-center`}>
<MyButton
fillColor="red1"
onPress={() => setShowPermissionDialog(false)}
style={tw`flex-1`}
>
Cancel
</MyButton>
<MyButton
fillColor="brand500"
onPress={() => {
Linking.openSettings();
}}
style={tw`flex-1`}
>
Settings
</MyButton>
</View>
</View>
</BottomDialog>
);
}
export default NotifChecker;

View file

@ -0,0 +1,104 @@
import React, {
createContext,
useContext,
useState,
useEffect,
useRef,
} from "react";
import * as Notifications from "expo-notifications";
import { registerForPushNotificationsAsync } from "./notif-register";
import { useRouter } from "expo-router";
import { NotificationToast } from "../toaster";
import { NOTIF_PERMISSION_DENIED } from "common-ui/src/lib/const-strs";
import type { ReactParentComponent } from '@packages/shared';
interface NotificationContextType {
expoPushToken: string | null;
notification: Notifications.Notification | null;
error: Error | null;
notifPermission: 'pending' | 'granted' | 'denied'
}
export const NotificationContext = createContext<
NotificationContextType | undefined
>(undefined);
export const useNotification = () => {
const context = useContext(NotificationContext);
if (context === undefined) {
throw new Error(
"useNotification must be used within a NotificationProvider"
);
}
return context;
};
export const NotificationProvider: React.FC<ReactParentComponent> = ({
children,
}) => {
const [expoPushToken, setExpoPushToken] = useState<string | null>(null);
const [notification, setNotification] =
useState<Notifications.Notification | null>(null);
const [error, setError] = useState<Error | null>(null);
const [notifPermission, setNotifPermission] = React.useState<NotificationContextType["notifPermission"]>("pending");
const notificationListener = useRef<any>(null);
const responseListener = useRef<any>(null);
const router = useRouter();
useEffect(() => {
registerForPushNotificationsAsync()
.then((token) => {
setExpoPushToken(token);
setNotifPermission("granted");
})
.catch((errorRaw) => {
const err = String(errorRaw).slice(7); // strip leading "Error: "
if (err === NOTIF_PERMISSION_DENIED) {
setNotifPermission("denied");
}
});
notificationListener.current =
Notifications.addNotificationReceivedListener((notification) => {
setNotification(notification);
const content = notification.request?.content;
if (content) {
NotificationToast(
content.title || "Notification",
content.body || "",
content.data || {}
);
}
});
responseListener.current =
Notifications.addNotificationResponseReceivedListener((response) => {
const data = response.notification.request.content.data;
if (data && data.orderId) {
router.push(`/(drawer)/dashboard/manage-orders/order-details/${data.orderId}` as any);
} else {
router.push("/(drawer)/dashboard" as any);
}
});
return () => {
if (notificationListener.current) {
Notifications.removeNotificationSubscription(
notificationListener.current
);
}
if (responseListener.current) {
Notifications.removeNotificationSubscription(responseListener.current);
}
};
}, []);
return (
<NotificationContext.Provider
value={{ expoPushToken, notification, error, notifPermission }}
>
{children}
</NotificationContext.Provider>
);
};

View file

@ -0,0 +1,47 @@
import * as Notifications from "expo-notifications";
import * as Device from "expo-device";
import Constants from "expo-constants";
import { Platform } from "react-native";
import { NOTIF_PERMISSION_DENIED } from "common-ui/src/lib/const-strs";
export async function registerForPushNotificationsAsync() {
if (Platform.OS === "android") {
await Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: "#FF231F7C",
});
}
if (Device.isDevice) {
const { status: existingStatus } =
await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== "granted") {
throw new Error(NOTIF_PERMISSION_DENIED);
}
const projectId =
Constants?.expoConfig?.extra?.eas?.projectId ??
Constants?.easConfig?.projectId;
if (!projectId) {
throw new Error("Project ID not found");
}
try {
const pushTokenString = (
await Notifications.getExpoPushTokenAsync({ projectId })
).data;
return pushTokenString;
} catch (e: unknown) {
throw new Error(`${e}`);
}
} else {
throw new Error("Must use physical device for push notifications");
}
}

View file

@ -253,8 +253,9 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
>
{({ handleChange, handleSubmit, values, setFieldValue, validateForm }) => {
return (
<ScrollView style={tw`flex-1`} contentContainerStyle={tw`pb-10`}>
<ScrollView style={tw`flex-1`} contentContainerStyle={tw`px-4 pt-4 pb-10`} keyboardShouldPersistTaps="handled">
<MyTextInput
testID="product-name-input"
topLabel="Product Name"
placeholder="Enter product name"
value={values.name}
@ -262,6 +263,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
style={{ marginBottom: 16 }}
/>
<MyTextInput
testID="product-short-description-input"
topLabel="Short Description"
placeholder="Enter short description"
multiline
@ -271,6 +273,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
style={{ marginBottom: 16 }}
/>
<MyTextInput
testID="product-long-description-input"
topLabel="Long Description"
placeholder="Enter detailed description"
multiline
@ -280,6 +283,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
style={{ marginBottom: 16 }}
/>
<BottomDropdown
testID="product-store-dropdown"
topLabel="Store"
label="Store"
value={values.storeId}
@ -290,6 +294,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
/>
<BottomDropdown
testID="product-type-dropdown"
topLabel="Product Type"
label="Product Type"
value={values.productType}
@ -308,6 +313,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<View style={tw`flex-row justify-between items-center mb-3`}>
<MyText style={tw`text-lg font-bold text-gray-800`}>Variants</MyText>
<TouchableOpacity
testID="add-variant-button"
onPress={() => {
push(defaultVariant())
setVariantImages((prev) => [...prev, []])
@ -335,6 +341,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
</View>
{(values.variants.length > 1 || isExistingSku) && (
<TouchableOpacity
testID={`variant-${vIndex}-remove`}
onPress={() => {
if (isExistingSku) {
// Mark existing SKU as deleted (sent to backend on save).
@ -355,6 +362,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
</View>
<MyTextInput
testID={`variant-${vIndex}-sku-name`}
topLabel="SKU Name (optional)"
placeholder="Overrides the auto-generated name"
value={variant.name ?? ''}
@ -385,6 +393,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<View key={aIndex} style={tw`flex-row items-center mb-2 gap-2`}>
<View style={tw`flex-1`}>
<MyTextInput
testID={`variant-${vIndex}-attr-${aIndex}-name`}
placeholder="Name"
value={attr.featureName ?? ''}
onChangeText={(text) =>
@ -399,6 +408,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
</View>
<View style={tw`flex-1`}>
<MyTextInput
testID={`variant-${vIndex}-attr-${aIndex}-value`}
placeholder={isQuantityFeature(attr) ? 'e.g. 0.5 kg' : 'Value'}
value={attr.featureValue}
onChangeText={handleChange(`variants.${vIndex}.features.${aIndex}.featureValue`)}
@ -432,6 +442,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<View style={tw`flex-row gap-2 mb-3`}>
<View style={tw`flex-1`}>
<MyTextInput
testID={`variant-${vIndex}-market-price`}
topLabel="Market Price"
placeholder="MRP"
keyboardType="numeric"
@ -442,6 +453,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<View style={tw`flex-1`}>
<MyTextInput
topLabel="Our Price"
testID={`variant-${vIndex}-price`}
placeholder="Selling price"
keyboardType="numeric"
value={variant.price?.toString() ?? ''}
@ -452,6 +464,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<View style={tw`flex-row items-center mb-3`}>
<Checkbox
testID={`variant-${vIndex}-flash`}
checked={variant.isFlashAvailable}
onPress={() => {
setFieldValue(`variants.${vIndex}.isFlashAvailable`, !variant.isFlashAvailable)
@ -464,6 +477,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<View style={tw`flex-row items-center mb-3`}>
<Checkbox
testID={`variant-${vIndex}-offer`}
checked={variant.isOffer}
onPress={() => setFieldValue(`variants.${vIndex}.isOffer`, !variant.isOffer)}
style={tw`mr-3`}
@ -474,6 +488,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
{!(values.productType === 'combo' && (variant.comboItems?.length || 0) > 0) && (
<View style={tw`flex-row items-center mb-3`}>
<Checkbox
testID={`variant-${vIndex}-combo-only`}
checked={variant.isComboOnly}
onPress={() => setFieldValue(`variants.${vIndex}.isComboOnly`, !variant.isComboOnly)}
style={tw`mr-3`}
@ -485,6 +500,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
{mode === 'edit' && (
<View style={tw`flex-row items-center mb-3`}>
<Checkbox
testID={`variant-${vIndex}-suspend`}
checked={variant.isSuspended}
onPress={() => setFieldValue(`variants.${vIndex}.isSuspended`, !variant.isSuspended)}
style={tw`mr-3`}
@ -495,6 +511,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
{variant.isFlashAvailable && (
<MyTextInput
testID={`variant-${vIndex}-flash-price`}
topLabel="Flash Price"
placeholder="Enter flash price"
keyboardType="numeric"
@ -505,6 +522,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
)}
<ImageUploaderNeo
testID={`variant-${vIndex}-image-add`}
images={variantImages[vIndex] || []}
onImageAdd={(payloads) =>
setVariantImages((prev) => {
@ -583,6 +601,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
})}
<TouchableOpacity
testID="add-variant-button-footer"
onPress={() => {
push(defaultVariant())
setVariantImages((prev) => [...prev, []])
@ -597,6 +616,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
</FieldArray>
<TouchableOpacity
testID="create-product-button"
onPress={async () => {
const validationErrors = await validateForm()
if (Object.keys(validationErrors).length > 0) {

View file

@ -1,7 +1,7 @@
import { createTRPCProxyClient, httpBatchLink, TRPCClientError } from '@trpc/client';
import { createTRPCReact } from '@trpc/react-query';
import { AppRouter } from '@backend/trpc/router'
import { BASE_API_URL } from 'common-ui';
import { BASE_API_URL } from '@packages/shared';
import { getJWT } from '@/hooks/useJWT';
import { FORCE_LOGOUT_EVENT } from 'common-ui/src/lib/const-strs';
import { DeviceEventEmitter } from 'react-native';

242
apps/admin-ui/tests/BUGS.md Normal file
View file

@ -0,0 +1,242 @@
# 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,120 @@
/**
* BannerForm component (components/BannerForm.tsx) — validation, submit
* gating, submit/cancel callbacks and the existing-image (edit) display.
*/
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import BannerForm, { BannerFormData } from '@/components/BannerForm'
import { setupApiMocks } from '../mocks/api'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { renderWithProviders } from '../helpers/render'
const onSubmit = jest.fn()
const onCancel = jest.fn()
const initialValues: BannerFormData = {
name: '',
imageUrl: '',
description: '',
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(
<BannerForm
initialValues={initialValues}
onSubmit={onSubmit}
onCancel={onCancel}
{...props}
/>
)
describe('BannerForm', () => {
beforeEach(() => {
resetStaffAuthMock()
onSubmit.mockClear()
onCancel.mockClear()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
setupApiMocks()
})
it('renders the banner fields', () => {
renderForm()
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('requires a banner name', async () => {
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.press(screen.getByText('Create Banner'))
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
expect(onSubmit.mock.calls[0][0]).toMatchObject({ name: 'My Banner' })
expect(onSubmit.mock.calls[0][1]).toBeUndefined()
})
it('uses the provided submit button label', () => {
renderForm({ submitButtonText: 'Update Banner' })
expect(screen.getByText('Update Banner')).toBeVisible()
})
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()
})
})

View file

@ -0,0 +1,98 @@
/**
* CancelOrderDialog — reason gating, the cancelOrder mutation and callbacks.
*/
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, screen, waitFor } 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'
describe('CancelOrderDialog', () => {
const onClose = jest.fn()
const onSuccess = jest.fn()
beforeEach(async () => {
onClose.mockClear()
onSuccess.mockClear()
resetStaffAuthMock()
await resetStorage()
setupApiMocks({ procedures: { 'admin.order.cancelOrder': { success: true, message: 'ok' } } })
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('renders the dialog chrome and reason input', () => {
renderWithProviders(
<CancelOrderDialog orderId={7} open onClose={onClose} onSuccess={onSuccess} />
)
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('does not submit and does not confirm when the reason is empty', () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.order.cancelOrder': { success: true, message: 'ok' } },
})
renderWithProviders(
<CancelOrderDialog orderId={7} open onClose={onClose} onSuccess={onSuccess} />
)
const confirm = screen.getAllByText('Cancel Order').pop()!
fireEvent.press(confirm)
expect(Alert.alert).not.toHaveBeenCalled()
expect(fetchMock).not.toHaveBeenCalled()
})
it('asks for confirmation then cancels with the typed reason', async () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.order.cancelOrder': { success: true, message: 'cancelled' } },
})
renderWithProviders(
<CancelOrderDialog orderId={7} open onClose={onClose} onSuccess={onSuccess} />
)
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?.()
})
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.order.cancelOrder'))
expect(lastProcedureInput(fetchMock, 'admin.order.cancelOrder')).toEqual({
orderId: 7,
reason: 'Out of stock',
})
expect(onClose).toHaveBeenCalled()
expect(onSuccess).toHaveBeenCalled()
})
it('keeps the order via the secondary button', () => {
renderWithProviders(
<CancelOrderDialog orderId={7} open onClose={onClose} onSuccess={onSuccess} />
)
fireEvent.press(screen.getByText('Keep Order'))
expect(onClose).toHaveBeenCalled()
expect(onSuccess).not.toHaveBeenCalled()
})
})

View file

@ -0,0 +1,170 @@
/**
* 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.
*/
import React from 'react'
import { Alert } from 'react-native'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
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'
const onSubmit = jest.fn()
const validInitialValues = {
couponCodes: ['SAVE10'],
isUserBased: false,
isApplyForAll: false,
targetUsers: [],
discountPercent: 10,
applicableUsers: [],
applicableProducts: [],
exclusiveApply: false,
isFirstOrderOnly: false,
isReservedCoupon: false,
}
const usersProcedure = {
users: [
{ id: 11, name: 'Alice', mobile: '9000000001' },
{ id: 12, name: 'Bob', mobile: '9000000002' },
],
}
describe('CouponForm', () => {
beforeEach(() => {
resetStaffAuthMock()
onSubmit.mockClear()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
setupApiMocks({
procedures: { 'admin.coupon.getUsersMiniInfo': usersProcedure },
})
})
it('renders the default form', () => {
renderWithProviders(<CouponForm onSubmit={onSubmit} isLoading={false} />)
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()
})
it('validates the form before calling onSubmit', async () => {
renderWithProviders(<CouponForm onSubmit={onSubmit} isLoading={false} />)
fireEvent.press(screen.getByText('Create Coupon'))
await waitFor(() => expect(screen.getByText('Create Coupon')).toBeVisible())
expect(onSubmit).not.toHaveBeenCalled()
})
it('uppercases the coupon code and submits the entered values', async () => {
renderWithProviders(<CouponForm onSubmit={onSubmit} isLoading={false} />)
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'))
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
expect(onSubmit.mock.calls[0][0]).toMatchObject({
couponCodes: ['SAVE10'],
discountPercent: 10,
isUserBased: false,
isApplyForAll: false,
isReservedCoupon: false,
})
})
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 },
})
renderWithProviders(
<CouponForm
onSubmit={onSubmit}
isLoading={false}
initialValues={validInitialValues}
/>
)
fireEvent.press(screen.getByText('Select users...'))
expect(await screen.findByText('9000000001 - Alice')).toBeVisible()
expect(lastProcedureInput(fetchMock, 'admin.coupon.getUsersMiniInfo')).toMatchObject({
search: '',
limit: 10,
offset: 0,
})
fireEvent.press(screen.getByText('9000000001 - Alice'))
fireEvent.press(screen.getByText('Done'))
await waitFor(() => expect(screen.getByText('1 users selected')).toBeVisible())
})
})

View file

@ -0,0 +1,82 @@
/**
* OrderNotesForm — empty validation, updateNotes mutation and callbacks.
*/
import React from 'react'
import { Alert } from 'react-native'
import { fireEvent, screen, waitFor } 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'
describe('OrderNotesForm', () => {
const onSuccess = jest.fn()
const onCancel = jest.fn()
beforeEach(async () => {
onSuccess.mockClear()
onCancel.mockClear()
resetStaffAuthMock()
await resetStorage()
setupApiMocks({ procedures: { 'admin.order.updateNotes': { id: 5 } } })
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('renders the initial notes and actions', () => {
renderWithProviders(
<OrderNotesForm orderId={5} initialNotes="existing" onSuccess={onSuccess} onCancel={onCancel} />
)
expect(screen.getByText('Add Order Notes')).toBeVisible()
expect(screen.getByDisplayValue('existing')).toBeVisible()
expect(screen.getByText('Save Notes')).toBeVisible()
expect(screen.getByText('Cancel')).toBeVisible()
})
it('rejects empty notes without calling the mutation', () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.order.updateNotes': { id: 5 } },
})
renderWithProviders(<OrderNotesForm orderId={5} onSuccess={onSuccess} onCancel={onCancel} />)
fireEvent.press(screen.getByText('Save Notes'))
expect(Alert.alert).toHaveBeenCalledWith('Error', 'Please enter some notes')
expect(fetchMock).not.toHaveBeenCalled()
})
it('saves trimmed notes and fires onSuccess', async () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.order.updateNotes': { id: 5 } },
})
renderWithProviders(<OrderNotesForm orderId={5} onSuccess={onSuccess} onCancel={onCancel} />)
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(onSuccess).not.toHaveBeenCalled()
})
})

View file

@ -0,0 +1,259 @@
/**
* OrderOptionsMenu — action rows, responder toggles, location attach and
* WhatsApp/Dial/Maps intents.
*/
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 { 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'
type OrderProp = React.ComponentProps<typeof OrderOptionsMenu>['order']
const baseOrder: OrderProp = {
id: 11,
readableId: 11,
isPackaged: false,
isDelivered: false,
address: '12 Main St, City, State - 500001, Phone: 9876543210',
addressId: 3,
adminNotes: null,
latitude: null,
longitude: null,
status: 'pending',
}
function renderMenu(overrides: Partial<OrderProp> = {}, handlers: Record<string, jest.Mock> = {}) {
const props = {
open: true,
onClose: jest.fn(),
order: { ...baseOrder, ...overrides },
onViewDetails: jest.fn(),
onTogglePackaged: jest.fn(),
onToggleDelivered: jest.fn(),
onOpenAdminNotes: jest.fn(),
onCancelOrder: jest.fn(),
onAttachLocation: jest.fn(),
onWhatsApp: jest.fn(),
onDial: jest.fn(),
...handlers,
}
renderWithProviders(<OrderOptionsMenu {...props} />)
return 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)
})
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 } },
})
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()
})
it('warns when location permission is denied and skips the mutation', async () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.order.updateAddressCoords': { success: true } },
})
;(Location.requestForegroundPermissionsAsync as jest.Mock).mockResolvedValueOnce({
status: 'denied',
granted: false,
})
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()
})
})

View file

@ -0,0 +1,219 @@
/**
* 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.
*/
import React from 'react'
import { Alert } from 'react-native'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import ProductForm from '@/src/components/ProductForm'
import { resetStorage, setupApiMocks } from '../mocks/api'
import { renderWithProviders } from '../helpers/render'
const validValues = (overrides: Record<string, unknown> = {}) => ({
name: 'Paneer',
shortDescription: 'Fresh',
longDescription: 'Very fresh',
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,
})
const stores = [
{ id: 1, name: 'Main Store' },
{ id: 2, name: 'Second Store' },
]
describe('ProductForm', () => {
beforeEach(async () => {
await resetStorage()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('renders the fields and the seeded variant', async () => {
setupApiMocks({
procedures: { 'common.getStoresSummary': { stores } },
})
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()
})
it('loads store options from getStoresSummary', async () => {
const api = setupApiMocks({
procedures: { 'common.getStoresSummary': { stores } },
})
renderWithProviders(
<ProductForm mode="create" initialValues={validValues()} onSubmit={jest.fn()} isLoading={false} />
)
await waitFor(() =>
expect(api.fetchMock).toHaveBeenCalled()
)
expect(screen.getByTestId('product-store-dropdown')).toBeVisible()
})
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={[[]]}
/>
)
expect(screen.getByText('Save Changes')).toBeVisible()
expect(screen.getByTestId('variant-0-suspend')).toBeVisible()
})
it('shows the saving label while isLoading is true', () => {
setupApiMocks({ procedures: { 'common.getStoresSummary': { stores } } })
renderWithProviders(
<ProductForm mode="edit" initialValues={validValues()} onSubmit={jest.fn()} isLoading />
)
expect(screen.getByText('Saving...')).toBeVisible()
})
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: [],
},
],
})}
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()
})
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} />
)
fireEvent.press(screen.getByTestId('create-product-button'))
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' },
])
// create mode passes an empty deleted-keys list.
expect(onSubmit.mock.calls[0][2]).toEqual([])
expect(api.fetchMock).toHaveBeenCalled()
})
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}
/>
)
fireEvent.press(screen.getByTestId('create-product-button'))
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Check your form', expect.any(String))
)
expect(onSubmit).not.toHaveBeenCalled()
})
})

View file

@ -0,0 +1,243 @@
/**
* ProductGroupForm (components/ProductGroupForm.tsx) — create/edit titles,
* name validation, createGroup/updateGroup payloads, product selection and the
* cancel/close handlers.
*
* 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.
*/
import React from 'react'
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import ProductGroupForm, { ProductGroup } from '@/components/ProductGroupForm'
import { resetStorage, setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { createQueryClient, renderWithProviders } from '../helpers/render'
const skusResponse = {
skus: [
{ id: 1, productId: 10, productName: 'Chicken', label: 'Chicken 1kg' },
{ id: 2, productId: 11, productName: 'Mutton', label: 'Mutton 1kg' },
],
}
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',
},
}
const existingGroup: ProductGroup = {
id: 5,
groupName: 'Beef Box',
description: 'Bundle',
createdAt: '2024-01-01T00:00:00.000Z',
products: [{ id: 10 }, { id: 11 }],
productCount: 2,
}
describe('ProductGroupForm', () => {
beforeEach(async () => {
await resetStorage()
setupApiMocks({ procedures })
jest.spyOn(console, 'error').mockImplementation(() => {})
})
it('renders in create mode', () => {
renderWithProviders(
<ProductGroupForm onClose={jest.fn()} onSuccess={jest.fn()} />
)
expect(screen.getByText('Create Product Group')).toBeVisible()
expect(screen.getByText('Group Name *')).toBeVisible()
expect(screen.getByText('Description')).toBeVisible()
expect(screen.getByText('Save')).toBeVisible()
})
it('renders in edit mode with the group seeded', () => {
renderWithProviders(
<ProductGroupForm
group={existingGroup}
onClose={jest.fn()}
onSuccess={jest.fn()}
/>
)
expect(screen.getByText('Edit Product Group')).toBeVisible()
expect(screen.getByDisplayValue('Beef Box')).toBeVisible()
expect(screen.getByDisplayValue('Bundle')).toBeVisible()
})
it('blocks submission when the group name is empty', async () => {
const { fetchMock } = setupApiMocks({ procedures })
renderWithProviders(
<ProductGroupForm onClose={jest.fn()} onSuccess={jest.fn()} />
)
fireEvent.press(screen.getByText('Save'))
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',
product_ids: [],
})
await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1))
})
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()} />
)
await waitFor(() =>
expectProcedureCalled(fetchMock, 'common.product.getAllSkusSummary')
)
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'))
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('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}
/>
)
fireEvent.changeText(screen.getByDisplayValue('Beef Box'), 'Beef Combo')
fireEvent.press(screen.getByText('Save'))
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],
})
await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1))
})
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
// 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
}
// 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',
])
})
it('calls onClose from the Cancel button', () => {
const onClose = jest.fn()
renderWithProviders(
<ProductGroupForm onClose={onClose} onSuccess={jest.fn()} />
)
fireEvent.press(screen.getByText('Cancel'))
expect(onClose).toHaveBeenCalledTimes(1)
})
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

@ -0,0 +1,46 @@
/**
* ProductListDialog (components/ProductListDialog.tsx) — a read-only bottom
* dialog listing the products passed in as props.
*/
import React from 'react'
import { screen } from '@testing-library/react-native'
import { ProductListDialog } from '@/components/ProductListDialog'
import { renderWithProviders } from '../helpers/render'
const products = [
{ id: 1, name: 'Chicken' },
{ id: 2, name: 'Mutton' },
{ id: 3, name: 'Fish' },
]
describe('ProductListDialog', () => {
it('renders the product count and each product when open', () => {
renderWithProviders(
<ProductListDialog open onClose={jest.fn()} products={products} />
)
expect(screen.getByText('Products (3)')).toBeVisible()
expect(screen.getByText('Chicken')).toBeVisible()
expect(screen.getByText('Mutton')).toBeVisible()
expect(screen.getByText('Fish')).toBeVisible()
})
it('shows a count of zero for an empty list', () => {
renderWithProviders(
<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()
})
})

View file

@ -0,0 +1,173 @@
/**
* 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

@ -0,0 +1,214 @@
/**
* SlotForm component (components/SlotForm.tsx) — create/update mutations,
* validation and vendor-snippet handling.
*/
import React from 'react'
import { Alert } from 'react-native'
import { fireEvent, screen, waitFor } 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'
const DELIVERY = new Date('2026-10-01T10:00:00.000Z')
const FREEZE = new Date('2026-10-01T06:00:00.000Z')
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',
},
}
describe('SlotForm', () => {
beforeEach(async () => {
resetStaffAuthMock()
await resetStorage()
searchParamsMock.current = {}
setupApiMocks({ procedures })
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('renders the create form', () => {
renderWithProviders(
<SlotForm initialDeliveryTime={DELIVERY} initialFreezeTime={FREEZE} />
)
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('blocks submit when a time is missing', async () => {
const { fetchMock } = setupApiMocks({ procedures })
renderWithProviders(<SlotForm />)
fireEvent.press(screen.getByTestId('create-slot-button'))
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Error', 'Please fill all fields')
)
expect(procCount(fetchMock, 'admin.slots.createSlot')).toBe(0)
})
it('blocks submit when freeze time is after delivery time', async () => {
const { fetchMock } = setupApiMocks({ procedures })
renderWithProviders(
<SlotForm
initialDeliveryTime={FREEZE}
initialFreezeTime={DELIVERY}
/>
)
fireEvent.press(screen.getByTestId('create-slot-button'))
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Error',
'Freeze time must be before or equal to delivery time'
)
)
expect(procCount(fetchMock, 'admin.slots.createSlot')).toBe(0)
})
it('creates a slot with the mapped payload and calls onSlotAdded', async () => {
const { fetchMock } = setupApiMocks({ procedures })
const onSlotAdded = jest.fn()
renderWithProviders(
<SlotForm
initialDeliveryTime={DELIVERY}
initialFreezeTime={FREEZE}
initialProductIds={[11, 12]}
initialGroupIds={[3]}
onSlotAdded={onSlotAdded}
/>
)
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 })
renderWithProviders(
<SlotForm initialDeliveryTime={DELIVERY} initialFreezeTime={FREEZE} />
)
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: '' }])
})
it('updates an existing slot in edit mode', async () => {
const { fetchMock } = setupApiMocks({ procedures })
const onSlotAdded = jest.fn()
renderWithProviders(
<SlotForm
slotId={7}
initialDeliveryTime={DELIVERY}
initialFreezeTime={FREEZE}
initialProductIds={[11]}
onSlotAdded={onSlotAdded}
/>
)
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!')
})
it('refetches the mounted slot detail after a successful update in edit mode', async () => {
const { fetchMock } = setupApiMocks({ procedures })
renderWithProviders(
<SlotForm
slotId={7}
initialDeliveryTime={DELIVERY}
initialFreezeTime={FREEZE}
initialProductIds={[11]}
/>
)
// 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)
)
// 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')
fireEvent.press(screen.getByTestId('create-slot-button'))
await waitFor(() =>
expectProcedureCalled(fetchMock, 'admin.slots.updateSlot')
)
// `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
)
)
})
})

View file

@ -0,0 +1,133 @@
/**
* 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).
*/
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 { SnippetMenu } from '@/components/SnippetMenu'
import type { VendorSnippet } from '@/types/vendor-snippets'
import { renderWithProviders } from '../helpers/render'
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',
}
const onEdit = jest.fn()
const onDelete = jest.fn()
const onViewOrders = jest.fn()
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 () => {})
})
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)
)
expect(onDelete).not.toHaveBeenCalled()
pressLastAlertButton('Delete')
expect(onDelete).toHaveBeenCalledWith(5)
})
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)
)
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)
fireEvent.press(await screen.findByText('Copy URL'))
expect(Alert.alert).toHaveBeenCalledWith('Error', 'No URL available to copy')
expect(Clipboard.setString).not.toHaveBeenCalled()
})
})

View file

@ -0,0 +1,94 @@
/**
* SnippetOrdersView (components/SnippetOrdersView.tsx) — read-only list of the
* orders matched by a vendor snippet, with per-order totals and an empty state.
*/
import React from 'react'
import { fireEvent, screen } from '@testing-library/react-native'
import SnippetOrdersView from '@/components/SnippetOrdersView'
import { renderWithProviders } from '../helpers/render'
type Order = React.ComponentProps<typeof SnippetOrdersView>['orders'][number]
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],
products: [
{
productId: 10,
productName: 'Chicken',
quantity: 2,
price: 50,
unit: 'kg',
subtotal: 100,
},
],
...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()}
/>
)
expect(screen.getByText('Orders for "VS_5"')).toBeVisible()
expect(screen.getByText('2 orders • Total: ₹150.50')).toBeVisible()
})
it('pluralises a single order', () => {
renderWithProviders(
<SnippetOrdersView orders={[order()]} snippetCode="VS_5" 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(
screen.getByText('Matched 1 product(s) from snippet "VS_5"')
).toBeVisible()
})
it('shows the empty state when there are no matching orders', () => {
renderWithProviders(
<SnippetOrdersView orders={[]} snippetCode="VS_5" onClose={jest.fn()} />
)
expect(screen.getByText('0 orders • Total: ₹0.00')).toBeVisible()
expect(screen.getByText('No matching orders')).toBeVisible()
expect(
screen.getByText("No orders found that match this snippet's criteria")
).toBeVisible()
})
it('closes via the header button', () => {
const onClose = jest.fn()
renderWithProviders(
<SnippetOrdersView orders={[order()]} snippetCode="VS_5" onClose={onClose} />
)
fireEvent.press(screen.getByText('✕'))
expect(onClose).toHaveBeenCalled()
})
})

View file

@ -0,0 +1,183 @@
/**
* StoreForm component (components/StoreForm.tsx) — validation, owner/product
* selection and the submit payload.
*/
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
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'
const CREATE_INITIAL: 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',
},
],
},
}
describe('StoreForm', () => {
beforeEach(async () => {
resetStaffAuthMock()
await resetStorage()
searchParamsMock.current = {}
setupApiMocks({ procedures })
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('renders the create form', async () => {
const onSubmit = jest.fn()
renderWithProviders(
<StoreForm
mode="create"
initialValues={CREATE_INITIAL}
onSubmit={onSubmit}
isLoading={false}
/>
)
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('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}
/>
)
fireEvent.press(screen.getByText('Create Store'))
await act(async () => {
await Promise.resolve()
await Promise.resolve()
})
// 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: '' })
)
})
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}
/>
)
fireEvent.changeText(
screen.getByPlaceholderText('Enter store name'),
'Freshyo Form'
)
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,
})
)
})
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}
/>
)
expect(screen.getByDisplayValue('Existing')).toBeVisible()
expect(screen.getByDisplayValue('Old description')).toBeVisible()
expect(screen.getByText('Update Store')).toBeVisible()
})
it('shows the pending label when isLoading', () => {
renderWithProviders(
<StoreForm
mode="create"
initialValues={CREATE_INITIAL}
onSubmit={jest.fn()}
isLoading
/>
)
expect(screen.getByText('Creating...')).toBeVisible()
})
it('loads staff and products', async () => {
const { fetchMock } = setupApiMocks({ procedures })
renderWithProviders(
<StoreForm
mode="create"
initialValues={CREATE_INITIAL}
onSubmit={jest.fn()}
isLoading={false}
/>
)
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.staffUser.getStaff'))
expectProcedureCalled(fetchMock, 'admin.product.getProducts')
})
})

View file

@ -0,0 +1,160 @@
/**
* 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.
*/
import React from 'react'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import TagForm from '@/src/components/TagForm'
import { resetStorage, setupApiMocks } from '../mocks/api'
import { expectProcedureCalled } from '../mocks/procedures'
import { renderWithProviders } from '../helpers/render'
const baseValues = {
tagName: 'Bestsellers',
tagDescription: 'Top picks',
isDashboardTag: false,
relatedStores: [],
productIds: [],
}
const stores = [
{ id: 1, name: 'Main Store' },
{ id: 2, name: 'Second Store' },
]
const skusResponse = {
skus: [
{ id: 1, productId: 10, productName: 'Chicken', label: 'Chicken 1kg' },
{ id: 2, productId: 11, productName: 'Mutton', label: 'Mutton 1kg' },
],
}
describe('TagForm', () => {
beforeEach(async () => {
await resetStorage()
})
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} />
)
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()
})
it('shows edit-mode labels', () => {
setupApiMocks({
procedures: { 'common.product.getAllSkusSummary': skusResponse },
})
renderWithProviders(
<TagForm mode="edit" initialValues={baseValues} onSubmit={jest.fn()} isLoading={false} stores={stores} />
)
expect(screen.getByText('Update Tag')).toBeVisible()
expect(screen.getByText('Tag Image (Upload new to replace)')).toBeVisible()
})
it('shows the submit-progress label', () => {
setupApiMocks({
procedures: { 'common.product.getAllSkusSummary': skusResponse },
})
renderWithProviders(
<TagForm mode="create" initialValues={baseValues} onSubmit={jest.fn()} isLoading stores={stores} />
)
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 },
})
const result = renderWithProviders(
<TagForm mode="create" initialValues={baseValues} onSubmit={onSubmit} isLoading={false} stores={stores} />
)
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])
})
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}
/>
)
await waitFor(() => expect(screen.getByText('Mutton 1kg')).toBeVisible())
expect(screen.getByText(/1 items/)).toBeVisible()
})
})

View file

@ -0,0 +1,118 @@
/**
* 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

@ -0,0 +1,249 @@
/**
* UserIncidentsView (components/UserIncidentsView.tsx) — incident list, empty
* state, add-incident dialog, validation and the addUserIncident mutation.
*
* 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.
*/
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 { 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'
const incident = {
id: 1,
userId: 3,
orderId: 7,
dateAdded: '2026-01-01T10:00:00.000Z',
adminComment: 'Abusive behaviour',
addedBy: 'shafi',
negativityScore: 5,
orderStatus: 'cancelled',
}
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 }
}
const openDialog = async () => {
fireEvent.press(screen.getByText('Add Incident'))
await screen.findByText('Add User Incident')
}
const submit = () => {
fireEvent.press(screen.getAllByText('Add Incident').pop()!)
}
describe('UserIncidentsView', () => {
beforeEach(async () => {
resetStaffAuthMock()
await resetStorage()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('renders the section header and add button', async () => {
renderView()
expect(screen.getByText('User Incidents')).toBeVisible()
expect(screen.getByText('Add Incident')).toBeVisible()
await screen.findByText('Abusive behaviour')
})
it('queries incidents for the given user', async () => {
const { fetchMock } = renderView()
await waitFor(() =>
expectProcedureCalled(fetchMock, 'admin.user.getUserIncidents')
)
expect(lastProcedureInput(fetchMock, 'admin.user.getUserIncidents')).toEqual({
userId: 3,
})
})
it('does not query when there is no user id', () => {
const { fetchMock } = renderView({ userId: 0, orderId: null })
expect(procCount(fetchMock, 'admin.user.getUserIncidents')).toBe(0)
})
it('renders each incident with its score, author and order', async () => {
renderView()
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()
})
it('renders the empty state when there are no incidents', async () => {
renderView({ userId: 3, orderId: null }, { 'admin.user.getUserIncidents': { incidents: [] } })
expect(
await screen.findByText('No incidents recorded for this user')
).toBeVisible()
})
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()
fireEvent.changeText(
screen.getByPlaceholderText('Enter details about the incident...'),
'Repeated cancellations'
)
submit()
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.user.addUserIncident'))
expect(lastProcedureInput(fetchMock, 'admin.user.addUserIncident')).toEqual({
userId: 3,
adminComment: 'Repeated cancellations',
})
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Incident added successfully')
)
})
it('adds an incident with only a negativity score', async () => {
const { fetchMock } = renderView()
await openDialog()
fireEvent.changeText(screen.getByPlaceholderText('0'), '7')
submit()
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.user.addUserIncident'))
expect(lastProcedureInput(fetchMock, 'admin.user.addUserIncident')).toEqual({
userId: 3,
negativityScore: 7,
})
})
it('adds an incident with a comment and score including the order id', async () => {
const { fetchMock } = renderView({ userId: 3, orderId: 7 })
await openDialog()
fireEvent.changeText(
screen.getByPlaceholderText('Enter details about the incident...'),
'Rude call'
)
fireEvent.changeText(screen.getByPlaceholderText('0'), '3')
submit()
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.user.addUserIncident'))
expect(lastProcedureInput(fetchMock, 'admin.user.addUserIncident')).toEqual({
userId: 3,
orderId: 7,
adminComment: 'Rude call',
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')
await openDialog()
fireEvent.changeText(
screen.getByPlaceholderText('Enter details about the incident...'),
'Late arrival'
)
submit()
await waitFor(() =>
expect(procCount(fetchMock, 'admin.user.getUserIncidents')).toBeGreaterThan(before)
)
await waitFor(() => expect(screen.queryByText('Add User Incident')).toBeNull())
})
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()
fireEvent.changeText(
screen.getByPlaceholderText('Enter details about the incident...'),
'Something'
)
submit()
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Error', 'nope')
)
expect(fetchMock).toBeTruthy()
expect(screen.getByText('Add User Incident')).toBeVisible()
})
})

View file

@ -0,0 +1,240 @@
/**
* VendorSnippetForm (components/VendorSnippetForm.tsx) — create/edit form for
* vendor snippets: snippet-code validation, slot + product selection, and the
* create/update mutations.
*/
import React from 'react'
import { Alert } from 'react-native'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import VendorSnippetForm from '@/components/VendorSnippetForm'
import { resetStorage, setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { renderWithProviders } from '../helpers/render'
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} />
)
describe('VendorSnippetForm', () => {
beforeEach(async () => {
await resetStorage()
onClose.mockClear()
onSuccess.mockClear()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
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_/)
)
})
it('validates slot and product selection before submitting', async () => {
const api = setupApiMocks({
procedures: {
'user.slots.getSlots': slotsResponse,
'common.product.getAllSkusSummary': skusResponse,
},
})
renderForm()
fireEvent.press(screen.getByText('Create Snippet'))
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)
})
it('rejects a snippet code with invalid characters', async () => {
setupApiMocks({
procedures: {
'user.slots.getSlots': slotsResponse,
'common.product.getAllSkusSummary': skusResponse,
},
})
renderForm()
fireEvent.changeText(
screen.getByPlaceholderText('Enter snippet code'),
'bad code!'
)
fireEvent.press(screen.getByText('Create Snippet'))
expect(
await screen.findByText(
'Snippet code can only contain letters, numbers, and underscores'
)
).toBeVisible()
})
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(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({
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 },
},
})
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'
)
)
})
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()
expect(screen.getByText('Choose a delivery slot')).toBeVisible()
fireEvent.press(screen.getByText('Is Permanent?'))
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()
})
})

View file

@ -0,0 +1,185 @@
/**
* 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()
})
})

View file

@ -0,0 +1,52 @@
/**
* 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,41 @@
/**
* 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

@ -0,0 +1,231 @@
/**
* 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'),
],
})
})
})

6
apps/admin-ui/tests/jest-env.d.ts vendored Normal file
View file

@ -0,0 +1,6 @@
/// <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

@ -0,0 +1,62 @@
const path = require('path')
const appRoot = path.resolve(__dirname, '..')
/**
* 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',
},
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('|') +
'))',
],
}

View file

@ -0,0 +1,37 @@
/**
* 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

@ -0,0 +1,51 @@
/**
* 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,73 @@
/**
* 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,181 @@
/**
* Module stubs for native / third-party packages that cannot run under jest.
* Registered in tests/setup.ts via jest.mock factories.
*
* Deliberately permissive: tests that assert behaviour spy on the returned
* functions or override the module themselves.
*/
import React from 'react'
import { View, Text } from 'react-native'
/** react-native-draggable-flatlist: render children as a plain list. */
export function draggableFlatListMock() {
const DraggableFlatList = ({
data,
renderItem,
keyExtractor,
ListEmptyComponent,
}: {
data?: unknown[]
renderItem?: (info: { item: unknown; index: number; drag: () => void; isActive: boolean }) => React.ReactNode
keyExtractor?: (item: unknown, index: number) => string
ListEmptyComponent?: React.ReactNode
}) => {
if (!data || data.length === 0) {
return React.createElement(View, { testID: 'mock-draggable-list' }, ListEmptyComponent ?? null)
}
return React.createElement(
View,
{ testID: 'mock-draggable-list' },
data.map((item, index) =>
React.createElement(
React.Fragment,
{ key: keyExtractor ? keyExtractor(item, index) : index },
renderItem?.({ item, index, drag: () => {}, isActive: false })
)
)
)
}
return {
__esModule: true,
default: DraggableFlatList,
ScaleDecorator: ({ children }: { children?: React.ReactNode }) =>
React.createElement(React.Fragment, null, children),
}
}
/** react-native-tab-view: render every tab label and the focused scene. */
export function tabViewMock() {
const TabView = ({
navigationState,
renderScene,
onIndexChange,
}: {
navigationState: { index: number; routes: { key: string }[] }
renderScene: (info: { route: { key: string } }) => React.ReactNode
onIndexChange?: (index: number) => void
}) => {
const route = navigationState.routes[navigationState.index]
return React.createElement(
View,
{ testID: 'mock-tab-view' },
navigationState.routes.map((r, index) =>
React.createElement(
Text,
{ key: r.key, testID: `tab-${r.key}`, onPress: () => onIndexChange?.(index) },
r.key
)
),
route ? renderScene({ route }) : null
)
}
return {
__esModule: true,
TabView,
// SceneMap must return a renderScene function, not the raw map.
SceneMap: (scenes: Record<string, React.ComponentType>) => (info: {
route: { key: string }
}) => {
const Scene = scenes[info.route.key]
return Scene ? React.createElement(Scene) : null
},
TabBar: () => null,
}
}
/** react-native-toast-message: no-op show/hide. */
export function toastMock() {
const Toast = {
show: jest.fn(),
hide: jest.fn(),
}
return { __esModule: true, default: Toast, ...Toast }
}
/** expo-location: permissions granted, a fixed position. */
export function locationMock() {
return {
__esModule: true,
Accuracy: { Lowest: 1, Low: 2, Balanced: 3, High: 4, Highest: 5 },
requestForegroundPermissionsAsync: jest.fn(async () => ({ status: 'granted', granted: true })),
getForegroundPermissionsAsync: jest.fn(async () => ({ status: 'granted', granted: true })),
hasServicesEnabledAsync: jest.fn(async () => true),
getCurrentPositionAsync: jest.fn(async () => ({
coords: { latitude: 16.75, longitude: 78.0, accuracy: 5 },
timestamp: Date.now(),
})),
reverseGeocodeAsync: jest.fn(async () => [
{ street: 'Test Street', city: 'Mahabubnagar', region: 'Telangana', postalCode: '509001' },
]),
}
}
/** expo-image-picker: one asset by default. */
export function imagePickerMock() {
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' })),
}
}
/** expo-document-picker: one document by default. */
export function documentPickerMock() {
return {
__esModule: true,
getDocumentAsync: jest.fn(async () => ({
canceled: false,
assets: [{ uri: 'file:///tmp/doc.pdf', name: 'doc.pdf', mimeType: 'application/pdf' }],
})),
}
}
/** expo-device: a physical device. */
export function deviceMock() {
return {
__esModule: true,
isDevice: true,
modelName: 'Jest Device',
osName: 'Android',
osVersion: '14',
}
}
/** expo-haptics: no-ops. */
export function hapticsMock() {
return {
__esModule: true,
impactAsync: jest.fn(async () => {}),
notificationAsync: jest.fn(async () => {}),
selectionAsync: jest.fn(async () => {}),
ImpactFeedbackStyle: { Light: 'light', Medium: 'medium', Heavy: 'heavy' },
}
}
/** expo-linear-gradient: passthrough View. */
export function linearGradientMock() {
const LinearGradient = ({ children }: { children?: React.ReactNode }) =>
React.createElement(View, { testID: 'mock-linear-gradient' }, children)
return { __esModule: true, LinearGradient }
}
/** expo-blur: passthrough View. */
export function blurMock() {
const BlurView = ({ children }: { children?: React.ReactNode }) =>
React.createElement(View, { testID: 'mock-blur-view' }, children)
return { __esModule: true, BlurView }
}
/** expo-image: passthrough Image. */
export function imageMock() {
const Image = (props: Record<string, unknown>) =>
React.createElement(View, { testID: 'mock-image', ...props })
return { __esModule: true, Image, default: Image }
}

View file

@ -0,0 +1,122 @@
/**
* Assert which tRPC procedures a screen called, and with what input.
*
* Every tRPC call goes through `global.fetch` (httpBatchLink), whose URL is
* `/api/trpc/<name>[,<name>...]?batch=1&input=<json>`. The input param is an
* object keyed by the batch index: `{ "0": { json: <input> }, ... }`.
*
* tests/mocks/api.ts installs the fetch stub; pass its returned `fetchMock` to
* these helpers.
*/
export interface ProcedureCall {
name: string
input: unknown
}
export interface FetchMockLike {
mock: { calls: unknown[][] }
}
const MARKER = '/api/trpc/'
const parseInputEnvelope = (raw: string | undefined) => {
if (!raw) return {} as Record<string, { json?: unknown }>
try {
return JSON.parse(raw) as Record<string, { json?: unknown }>
} catch {
return {} as Record<string, { json?: unknown }>
}
}
const unwrapInput = (entry: unknown): unknown => {
if (
entry != null &&
typeof entry === 'object' &&
'json' in entry &&
'meta' in entry
) {
return (entry as { json: unknown }).json
}
return entry
}
/** Split a tRPC request URL into one entry per batched procedure. */
export function parseTrpcUrl(url: string, body?: unknown): ProcedureCall[] {
const target = String(url)
const at = target.indexOf(MARKER)
if (at === -1) return []
const rest = target.slice(at + MARKER.length)
const queryAt = rest.indexOf('?')
const path = queryAt === -1 ? rest : rest.slice(0, queryAt)
const query = queryAt === -1 ? '' : rest.slice(queryAt + 1)
const names = path.split(',').filter(Boolean)
let inputsByIndex: Record<string, { json?: unknown }> = {}
const match = /(?:^|&)input=([^&]*)/.exec(query)
if (match) {
inputsByIndex = parseInputEnvelope(decodeURIComponent(match[1]))
} else if (typeof body === 'string') {
inputsByIndex = parseInputEnvelope(body)
}
return names.map((name, index) => ({
name,
input: unwrapInput(inputsByIndex[String(index)]),
}))
}
/** Every procedure call recorded by the fetch mock, in order. */
export function calledProcedures(fetchMock: FetchMockLike): ProcedureCall[] {
return fetchMock.mock.calls.flatMap(([url, options]) => {
const body = (options as { body?: unknown } | undefined)?.body
return parseTrpcUrl(String(url), body)
})
}
export function procedureCalls(
fetchMock: FetchMockLike,
name: string
): ProcedureCall[] {
return calledProcedures(fetchMock).filter((call) => call.name === name)
}
/** Assert a procedure was called (optionally exactly `times`). */
export function expectProcedureCalled(
fetchMock: FetchMockLike,
name: string,
options: { times?: number } = {}
): ProcedureCall[] {
const calls = procedureCalls(fetchMock, name)
if (options.times != null) {
expect(calls).toHaveLength(options.times)
} else {
expect(calls.length).toBeGreaterThan(0)
}
return calls
}
/** Input of the most recent call to a procedure (undefined if never called). */
export function lastProcedureInput(
fetchMock: FetchMockLike,
name: string
): unknown {
const calls = procedureCalls(fetchMock, name)
return calls.length === 0 ? undefined : calls[calls.length - 1].input
}
export function procedureInput(
fetchMock: FetchMockLike,
name: string
): unknown {
return lastProcedureInput(fetchMock, name)
}
/** Number of calls to a procedure. */
export function procCount(fetchMock: FetchMockLike, name: string): number {
return procedureCalls(fetchMock, name).length
}

View file

@ -0,0 +1,18 @@
/**
* Callbacks recorded from the mocked refresh hooks
* (common-ui/useMarkDataFetchers, common-ui/useManualRefresh) so a test can
* invoke a screen's refresh handler and assert what it refetches.
*/
export const refreshHooks: {
markDataFetchers: (() => void) | null
manualRefresh: (() => void) | null
} = {
markDataFetchers: null,
manualRefresh: null,
}
export function resetRefreshHooks() {
refreshHooks.markDataFetchers = null
refreshHooks.manualRefresh = null
}

View file

@ -0,0 +1,70 @@
/**
* Shared spies for the mocked expo-router.
*
* The mock lives in each test file rather than in tests/setup.ts, so the ones
* that want real navigation can use expo-router/testing-library. Any file that
* renders a router consumer adds:
*
* jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
*/
import React from 'react'
export const routerMock = {
push: jest.fn(),
replace: jest.fn(),
back: jest.fn(),
navigate: jest.fn(),
canGoBack: jest.fn(() => false),
dismissTo: jest.fn(),
dismissAll: jest.fn(),
setParams: jest.fn(),
}
export function resetRouterMock() {
routerMock.push.mockClear()
routerMock.replace.mockClear()
routerMock.back.mockClear()
routerMock.navigate.mockClear()
routerMock.dismissTo.mockClear()
routerMock.dismissAll.mockClear()
}
/** Local search params returned by the mocked router. */
export const searchParamsMock: { current: Record<string, unknown> } = {
current: {},
}
/** Factory for jest.mock('expo-router', ...). */
export function expoRouterMock() {
return {
useRouter: () => routerMock,
router: routerMock,
usePathname: () => '/dashboard',
useSegments: () => [],
useLocalSearchParams: () => searchParamsMock.current,
useGlobalSearchParams: () => searchParamsMock.current,
useFocusEffect: (callback: () => void | (() => void)) => {
const ran = React.useRef(false)
React.useEffect(() => {
if (ran.current) return
ran.current = true
return callback()
}, [])
},
Link: ({ children }: { children?: unknown }) => children ?? null,
Slot: ({ children }: { children?: unknown }) => children ?? null,
// Layout primitives used by route files; render children through and give
// Stack/Tabs a no-op .Screen so `<Stack.Screen />` does not crash.
Stack: Object.assign(
({ children }: { children?: unknown }) => children ?? null,
{ Screen: () => null }
),
Tabs: Object.assign(
({ children }: { children?: unknown }) => children ?? null,
{ Screen: () => null }
),
Drawer: ({ children }: { children?: unknown }) => children ?? null,
Redirect: () => null,
}
}

View file

@ -0,0 +1,52 @@
/**
* Overridable staff-auth mock with spies.
*
* tests/setup.ts stubs @/components/context/staff-auth-context with this
* factory so screens that read the staff session mount. Tests can flip the
* state in a beforeEach; reset with resetStaffAuthMock().
*/
import type { ReactNode } from 'react'
export interface StaffAuthMockState {
isLoggedIn: boolean
isLoading: boolean
staff: unknown
isLoggingIn: boolean
loginError: string | null
login: jest.Mock
logout: jest.Mock
}
export const staffAuthMock: StaffAuthMockState = {
isLoggedIn: true,
isLoading: false,
staff: { id: 1, name: 'shafi' },
isLoggingIn: false,
loginError: null,
login: jest.fn(async () => {}),
logout: jest.fn(),
}
export function resetStaffAuthMock() {
staffAuthMock.isLoggedIn = true
staffAuthMock.isLoading = false
staffAuthMock.staff = { id: 1, name: 'shafi' }
staffAuthMock.isLoggingIn = false
staffAuthMock.loginError = null
}
export function staffAuthContextMock() {
return {
StaffAuthProvider: ({ children }: { children?: ReactNode }) => children ?? null,
useStaffAuth: () => ({
isLoggedIn: staffAuthMock.isLoggedIn,
isLoading: staffAuthMock.isLoading,
staff: staffAuthMock.staff,
isLoggingIn: staffAuthMock.isLoggingIn,
loginError: staffAuthMock.loginError,
login: staffAuthMock.login,
logout: staffAuthMock.logout,
}),
}
}

View file

@ -0,0 +1,214 @@
/**
* Create banner screen (app/(drawer)/dashboard/dashboard-banners/create.tsx) —
* BannerForm wiring, image requirement, upload + createBanner mutation,
* validation, cancel and success navigation.
*
* The common-ui ImageUploader add button lives behind a separate
* `@expo/vector-icons` copy, so instead of pressing it we intercept
* common-ui's usePickImage hook (test-local module mock) and invoke a pick.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
const mockPickState: { trigger: (() => Promise<void>) | null } = { trigger: null }
jest.mock('common-ui/src/components/use-pick-image', () => ({
__esModule: true,
default: ({ setFile }: { setFile: (asset: unknown) => Promise<void> }) => {
mockPickState.trigger = () =>
setFile({
uri: 'file:///tmp/pick.jpg',
fileName: 'pick.jpg',
mimeType: 'image/jpeg',
})
return () => {}
},
}))
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import CreateBanner from '@/app/(drawer)/dashboard/dashboard-banners/create'
import { setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { routerMock, searchParamsMock } from '../mocks/router'
import { renderWithProviders } from '../helpers/render'
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?.())
}
// "Create Banner" appears as both the header title and the submit button.
const pressSubmit = () => {
const labels = screen.getAllByText('Create Banner')
fireEvent.press(labels[labels.length - 1])
}
const blur = (placeholder: string, name: string) => {
fireEvent(screen.getByPlaceholderText(placeholder), 'blur', {
target: { name },
persist: () => {},
})
}
const pickImage = async () => {
await act(async () => {
await mockPickState.trigger?.()
})
await screen.findByText('Only one image allowed')
}
/** The app GETs the picked file:// asset; the harness fetch only knows tRPC. */
const installAssetFetchShim = (fetchMock: jest.Mock) => {
;(global as unknown as { fetch: unknown }).fetch = jest.fn((url: string, opts: unknown) => {
if (String(url).startsWith('file:')) {
return Promise.resolve({ ok: true, blob: async () => ({}) })
}
return fetchMock(url, opts)
})
}
const uploadProcedures = {
'common.generateUploadUrls': {
uploadUrls: ['https://cdn.example.com/product-images/pic.jpg'],
},
}
describe('Create banner', () => {
beforeEach(() => {
resetStaffAuthMock()
searchParamsMock.current = {}
mockPickState.trigger = null
routerMock.back.mockClear()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('renders the create form', () => {
setupApiMocks()
renderWithProviders(<CreateBanner />)
expect(screen.getAllByText('Create Banner').length).toBeGreaterThan(1)
expect(screen.getByPlaceholderText('Enter banner name')).toBeVisible()
expect(screen.getByPlaceholderText('Enter banner description (optional)')).toBeVisible()
expect(screen.getByPlaceholderText('https://example.com/redirect')).toBeVisible()
})
it('shows the name validation error on blur', async () => {
setupApiMocks()
renderWithProviders(<CreateBanner />)
blur('Enter banner name', 'name')
expect(await screen.findByText('Banner name is required')).toBeVisible()
})
it('rejects a malformed redirect URL', async () => {
setupApiMocks()
renderWithProviders(<CreateBanner />)
fireEvent.changeText(screen.getByPlaceholderText('https://example.com/redirect'), 'not-a-url')
blur('https://example.com/redirect', 'redirectUrl')
expect(await screen.findByText('Please enter a valid URL')).toBeVisible()
})
it('does not create a banner without an image', async () => {
const { fetchMock } = setupApiMocks()
renderWithProviders(<CreateBanner />)
fireEvent.changeText(screen.getByPlaceholderText('Enter banner name'), 'My Banner')
pressSubmit()
await waitFor(() => expect(Alert.alert).toHaveBeenCalledWith('Error', 'Image is required'))
expect(procCount(fetchMock, 'admin.banner.createBanner')).toBe(0)
})
it('uploads the image and creates the banner', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
...uploadProcedures,
'admin.banner.createBanner': { id: 1, name: 'My Banner' },
},
})
installAssetFetchShim(fetchMock as unknown as jest.Mock)
renderWithProviders(<CreateBanner />)
fireEvent.changeText(screen.getByPlaceholderText('Enter banner name'), 'My Banner')
await pickImage()
pressSubmit()
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.banner.createBanner'))
expect(lastProcedureInput(fetchMock, 'admin.banner.createBanner')).toMatchObject({
name: 'My Banner',
imageUrl: 'https://cdn.example.com/product-images/pic.jpg',
skuIds: [],
})
})
it('alerts and navigates back on successful creation', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
...uploadProcedures,
'admin.banner.createBanner': { id: 1 },
},
})
installAssetFetchShim(fetchMock as unknown as jest.Mock)
renderWithProviders(<CreateBanner />)
fireEvent.changeText(screen.getByPlaceholderText('Enter banner name'), 'My Banner')
await pickImage()
pressSubmit()
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Success',
'Banner created successfully',
expect.any(Array)
)
)
pressLastAlertButton('OK')
expect(routerMock.back).toHaveBeenCalled()
})
it('alerts an error when createBanner fails', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
...uploadProcedures,
'admin.banner.createBanner': () => {
throw new Error('nope')
},
},
})
installAssetFetchShim(fetchMock as unknown as jest.Mock)
renderWithProviders(<CreateBanner />)
fireEvent.changeText(screen.getByPlaceholderText('Enter banner name'), 'My Banner')
await pickImage()
pressSubmit()
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Error',
'Failed to create banner. Please try again.'
)
)
})
it('cancels and navigates back', () => {
setupApiMocks()
renderWithProviders(<CreateBanner />)
fireEvent.press(screen.getByText('Cancel'))
expect(routerMock.back).toHaveBeenCalled()
})
})

View file

@ -0,0 +1,215 @@
/**
* Edit banner screen (app/(drawer)/dashboard/dashboard-banners/edit/[id].tsx) —
* getBanner hydration, updateBanner mutation, validation and navigation.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import EditBanner from '@/app/(drawer)/dashboard/dashboard-banners/edit/[id]'
import { setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { routerMock, searchParamsMock } from '../mocks/router'
import { renderWithProviders } from '../helpers/render'
const banner = {
id: 7,
name: 'Banner Seven',
imageUrl: 'https://cdn.example.com/seven.jpg',
description: 'Seven desc',
skuIds: [],
redirectUrl: null,
serialNum: 1,
isActive: true,
createdAt: '2024-01-01T00:00:00.000Z',
lastUpdated: '2024-01-01T00:00:00.000Z',
}
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('Edit banner', () => {
beforeEach(() => {
resetStaffAuthMock()
searchParamsMock.current = { id: '7' }
routerMock.back.mockClear()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('requests the banner by the route id', async () => {
const { fetchMock } = setupApiMocks({ procedures: { 'admin.banner.getBanner': banner } })
renderWithProviders(<EditBanner />)
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.banner.getBanner'))
expect(lastProcedureInput(fetchMock, 'admin.banner.getBanner')).toEqual({ id: 7 })
})
it('hydrates the form from the fetched banner', async () => {
setupApiMocks({ procedures: { 'admin.banner.getBanner': banner } })
renderWithProviders(<EditBanner />)
expect(await screen.findByDisplayValue('Banner Seven')).toBeVisible()
expect(screen.getByDisplayValue('Seven desc')).toBeVisible()
})
it('renders the not-found state when the banner is missing', async () => {
setupApiMocks({ procedures: { 'admin.banner.getBanner': null } })
renderWithProviders(<EditBanner />)
expect(await screen.findByText('Banner not found')).toBeVisible()
})
it('updates the banner with the transformed payload', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'admin.banner.getBanner': banner,
'admin.banner.updateBanner': { ...banner, name: 'Renamed Banner' },
},
})
renderWithProviders(<EditBanner />)
await screen.findByDisplayValue('Banner Seven')
fireEvent.changeText(screen.getByDisplayValue('Banner Seven'), 'Renamed Banner')
fireEvent.press(screen.getByText('Update Banner'))
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.banner.updateBanner'))
expect(lastProcedureInput(fetchMock, 'admin.banner.updateBanner')).toMatchObject({
id: 7,
name: 'Renamed Banner',
imageUrl: 'https://cdn.example.com/seven.jpg',
description: 'Seven desc',
skuIds: [],
})
})
it('refreshes the banner list and refetches the mounted banner after a successful update', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'admin.banner.getBanner': banner,
'admin.banner.updateBanner': { ...banner, name: 'Renamed Banner' },
'admin.banner.getBanners': [banner],
},
})
renderWithProviders(<EditBanner />)
await screen.findByDisplayValue('Banner Seven')
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.banner.getBanner'))
// Baselines: hydration has already pulled getBanner once, while getBanners
// is `enabled: false` — nothing fetches it until the screen calls refetch().
const getBannerBefore = procCount(fetchMock, 'admin.banner.getBanner')
const getBannersBefore = procCount(fetchMock, 'admin.banner.getBanners')
expect(getBannerBefore).toBeGreaterThan(0)
fireEvent.changeText(screen.getByDisplayValue('Banner Seven'), 'Renamed Banner')
fireEvent.press(screen.getByText('Update Banner'))
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.banner.updateBanner'))
// `await refetchBanners()` — the explicit pull of the list query.
await waitFor(() =>
expect(procCount(fetchMock, 'admin.banner.getBanners')).toBeGreaterThan(
getBannersBefore
)
)
expect(procCount(fetchMock, 'admin.banner.getBanners')).toBeGreaterThan(0)
// `utils.admin.banner.getBanner.invalidate()` refetches the mounted query.
await waitFor(() =>
expect(procCount(fetchMock, 'admin.banner.getBanner')).toBeGreaterThan(
getBannerBefore
)
)
})
it('does not update before the banner loads', () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.banner.getBanner': () => new Promise(() => {}) },
})
renderWithProviders(<EditBanner />)
expect(procCount(fetchMock, 'admin.banner.updateBanner')).toBe(0)
})
it('alerts when the update fails', async () => {
setupApiMocks({
procedures: {
'admin.banner.getBanner': banner,
'admin.banner.updateBanner': () => {
throw new Error('nope')
},
},
})
renderWithProviders(<EditBanner />)
await screen.findByDisplayValue('Banner Seven')
fireEvent.changeText(screen.getByDisplayValue('Banner Seven'), 'Renamed Banner')
fireEvent.press(screen.getByText('Update Banner'))
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Error',
'Failed to update banner. Please try again.'
)
)
})
it('alerts success and navigates back after update', async () => {
setupApiMocks({
procedures: {
'admin.banner.getBanner': banner,
'admin.banner.updateBanner': { ...banner, name: 'Renamed Banner' },
},
})
renderWithProviders(<EditBanner />)
await screen.findByDisplayValue('Banner Seven')
fireEvent.changeText(screen.getByDisplayValue('Banner Seven'), 'Renamed Banner')
fireEvent.press(screen.getByText('Update Banner'))
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Success',
'Banner updated successfully',
expect.any(Array)
)
)
routerMock.back.mockClear()
pressLastAlertButton('OK')
expect(routerMock.back).toHaveBeenCalled()
})
it('BUG: alerts "Banner not found" and navigates back on mount before getBanner resolves', async () => {
setupApiMocks({ procedures: { 'admin.banner.getBanner': banner } })
renderWithProviders(<EditBanner />)
await screen.findByDisplayValue('Banner Seven')
expect(Alert.alert).toHaveBeenCalledWith('Error', 'Banner not found')
expect(routerMock.back).toHaveBeenCalled()
})
it('cancels and navigates back', async () => {
setupApiMocks({ procedures: { 'admin.banner.getBanner': banner } })
renderWithProviders(<EditBanner />)
await screen.findByDisplayValue('Banner Seven')
routerMock.back.mockClear()
fireEvent.press(screen.getByText('Cancel'))
expect(routerMock.back).toHaveBeenCalled()
})
})

View file

@ -0,0 +1,237 @@
/**
* Dashboard banners list (app/(drawer)/dashboard/dashboard-banners/index.tsx) —
* banner rows, slot assignment/edit mode, save/empty-slot mutations, delete and
* navigation to create/edit.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import DashboardBanners from '@/app/(drawer)/dashboard/dashboard-banners/index'
import { setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { routerMock, searchParamsMock } from '../mocks/router'
import { renderWithProviders } from '../helpers/render'
const bannerOne = {
id: 1,
name: 'Banner One',
imageUrl: 'https://cdn.example.com/one.jpg',
description: 'First banner',
skuIds: [],
redirectUrl: null,
serialNum: 1,
isActive: true,
createdAt: '2024-01-01T00:00:00.000Z',
lastUpdated: '2024-01-01T00:00:00.000Z',
}
const bannerTwo = {
...bannerOne,
id: 2,
name: 'Banner Two',
imageUrl: 'https://cdn.example.com/two.jpg',
description: null,
serialNum: null,
isActive: false,
}
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?.())
}
const iconByName = (name: string) => {
const icons = screen.UNSAFE_getAllByType(MaterialIcons)
return icons.find((icon) => icon.props.name === name) as unknown as Parameters<
typeof fireEvent.press
>[0]
}
describe('Dashboard banners index', () => {
beforeEach(() => {
resetStaffAuthMock()
searchParamsMock.current = {}
routerMock.push.mockClear()
routerMock.back.mockClear()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('shows a loading state while banners are pending', () => {
setupApiMocks({ procedures: { 'admin.banner.getBanners': { banners: [bannerOne] } } })
renderWithProviders(<DashboardBanners />)
expect(screen.getByText('Loading banners...')).toBeVisible()
})
it('renders banner rows and assigns slotted banners to their slot', async () => {
setupApiMocks({
procedures: { 'admin.banner.getBanners': { banners: [bannerOne, bannerTwo] } },
})
renderWithProviders(<DashboardBanners />)
expect(await screen.findByText('First banner')).toBeVisible()
expect(screen.getByText('Banner Two')).toBeVisible()
// banner one occupies slot 1 (label appears on both the tile and the row)
expect(screen.getAllByText('Slot 1').length).toBeGreaterThan(1)
})
it('renders the empty state when there are no banners', async () => {
setupApiMocks({ procedures: { 'admin.banner.getBanners': { banners: [] } } })
renderWithProviders(<DashboardBanners />)
expect(await screen.findByText('No Banners Yet')).toBeVisible()
})
it('renders the error state when the query fails', async () => {
setupApiMocks({
procedures: {
'admin.banner.getBanners': () => {
throw new Error('boom')
},
},
})
renderWithProviders(<DashboardBanners />)
expect(await screen.findByText('Error loading banners')).toBeVisible()
})
it('navigates to create from the floating action button', async () => {
setupApiMocks({ procedures: { 'admin.banner.getBanners': { banners: [bannerOne] } } })
renderWithProviders(<DashboardBanners />)
await screen.findByText('First banner')
fireEvent.press(screen.getByLabelText('Add new banner'))
expect(routerMock.push).toHaveBeenCalledWith(
'/(drawer)/dashboard/dashboard-banners/create'
)
})
it('navigates to edit for the pressed banner', async () => {
setupApiMocks({ procedures: { 'admin.banner.getBanners': { banners: [bannerOne] } } })
renderWithProviders(<DashboardBanners />)
await screen.findByText('First banner')
fireEvent.press(iconByName('edit'))
expect(routerMock.push).toHaveBeenCalledWith(
'/(drawer)/dashboard/dashboard-banners/edit/1'
)
})
it('saves a new slot assignment through updateBanner', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'admin.banner.getBanners': { banners: [bannerOne, bannerTwo] },
'admin.banner.updateBanner': { ...bannerTwo, serialNum: 2 },
},
})
renderWithProviders(<DashboardBanners />)
await screen.findByText('Banner Two')
const fetchesBeforeSave = procCount(fetchMock, 'admin.banner.getBanners')
fireEvent.press(screen.getByText('Slot 2'))
fireEvent.press(screen.getByText('Banner Two'))
fireEvent.press(screen.getByText('Save Changes'))
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.banner.updateBanner'))
expect(lastProcedureInput(fetchMock, 'admin.banner.updateBanner')).toEqual({
id: 2,
serialNum: 2,
})
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Slot assignments saved successfully')
)
// let the post-save refetch settle before the test unmounts
await waitFor(() =>
expect(procCount(fetchMock, 'admin.banner.getBanners')).toBeGreaterThan(fetchesBeforeSave)
)
})
it('empties an occupied slot through updateBanner with serialNum null', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'admin.banner.getBanners': { banners: [bannerOne, bannerTwo] },
'admin.banner.updateBanner': { ...bannerOne, serialNum: null },
},
})
renderWithProviders(<DashboardBanners />)
await screen.findByText('First banner')
const fetchesBeforeEmptySlot = procCount(fetchMock, 'admin.banner.getBanners')
fireEvent.press(screen.getAllByText('Slot 1')[0])
fireEvent.press(screen.getByText('Empty Slot'))
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.banner.updateBanner'))
expect(lastProcedureInput(fetchMock, 'admin.banner.updateBanner')).toEqual({
id: 1,
serialNum: null,
})
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Slot 1 has been emptied')
)
// let the post-empty-slot refetch settle before the test unmounts
await waitFor(() =>
expect(procCount(fetchMock, 'admin.banner.getBanners')).toBeGreaterThan(
fetchesBeforeEmptySlot
)
)
})
it('cancels slot editing and restores assignments', async () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.banner.getBanners': { banners: [bannerOne, bannerTwo] } },
})
renderWithProviders(<DashboardBanners />)
await screen.findByText('Banner Two')
fireEvent.press(screen.getByText('Slot 2'))
fireEvent.press(screen.getByText('Banner Two'))
fireEvent.press(screen.getByText('Cancel'))
expect(screen.queryByText('Save Changes')).toBeNull()
expect(procCount(fetchMock, 'admin.banner.updateBanner')).toBe(0)
})
it('deletes a banner after confirming the alert', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'admin.banner.getBanners': { banners: [bannerOne] },
'admin.banner.deleteBanner': { success: true },
},
})
renderWithProviders(<DashboardBanners />)
await screen.findByText('First banner')
fireEvent.press(iconByName('delete'))
expect(Alert.alert).toHaveBeenCalledWith(
'Delete Banner',
'Are you sure you want to delete this banner?',
expect.any(Array)
)
pressLastAlertButton('Delete')
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.banner.deleteBanner'))
expect(lastProcedureInput(fetchMock, 'admin.banner.deleteBanner')).toEqual({ id: 1 })
await waitFor(() => expect(Alert.alert).toHaveBeenCalledWith('Success', 'Banner deleted'))
// let the post-delete refetch settle before the test unmounts
await waitFor(() =>
expect(procCount(fetchMock, 'admin.banner.getBanners')).toBeGreaterThan(1)
)
})
})

View file

@ -0,0 +1,250 @@
/**
* Complaints list (app/(drawer)/dashboard/complaints/index.tsx) — infinite list,
* rows, empty/error/loading, resolve mutation and navigation.
*
* HARNESS BUG WORKAROUND: tests/mocks/native.ts has a stray top-level `return`
* (line 89 → "'return' outside of function"), so any module that pulls in
* `common-ui` (which eagerly imports expo-image/picker/document-picker) fails to
* parse. The harness file is untouched; the three expo modules are re-mocked
* locally below with equivalent, self-contained fakes. See the final report.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
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, FlatList } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import Complaints from '@/app/(drawer)/dashboard/complaints/index'
import { resetStorage, setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
import { resetRefreshHooks } from '../mocks/refresh'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { renderWithProviders } from '../helpers/render'
const pendingComplaint = {
id: 5,
text: 'Missing item in order',
userId: 3,
userName: 'Alice',
userMobile: '9999999999',
orderId: 7,
status: 'pending',
createdAt: '2026-01-01T10:00:00.000Z',
images: ['https://assets.test/c/1.png'],
response: null,
}
const resolvedComplaint = {
...pendingComplaint,
id: 6,
text: 'Late delivery',
status: 'resolved',
response: 'We have refunded the amount',
images: [],
}
const page = (complaints: unknown[], nextCursor?: number) => ({ complaints, nextCursor })
describe('Complaints list', () => {
beforeEach(async () => {
resetStaffAuthMock()
resetRefreshHooks()
await resetStorage()
resetRouterMock()
searchParamsMock.current = {}
setupApiMocks()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('shows a loading state while the list query is pending', () => {
setupApiMocks({
procedures: { 'admin.complaint.getAll': () => new Promise(() => {}) },
})
renderWithProviders(<Complaints />)
expect(screen.getByText('Loading complaints...')).toBeVisible()
})
it('renders each complaint with status, reply and linked user/order', async () => {
setupApiMocks({
procedures: {
'admin.complaint.getAll': page([pendingComplaint, resolvedComplaint]),
},
})
renderWithProviders(<Complaints />)
await waitFor(() => expect(screen.getByText('Complaint #5')).toBeVisible())
expect(screen.getByText('Complaint #6')).toBeVisible()
expect(screen.getByText('Missing item in order')).toBeVisible()
expect(screen.getByText('Pending')).toBeVisible()
expect(screen.getByText('Resolved')).toBeVisible()
expect(screen.getByText('We have refunded the amount')).toBeVisible()
expect(screen.getAllByText('Alice').length).toBeGreaterThan(0)
expect(screen.getAllByText('Order #7').length).toBeGreaterThan(0)
})
it('only offers Resolve on pending complaints', async () => {
setupApiMocks({
procedures: {
'admin.complaint.getAll': page([pendingComplaint, resolvedComplaint]),
},
})
renderWithProviders(<Complaints />)
await waitFor(() => expect(screen.getByText('Complaint #5')).toBeVisible())
expect(screen.getAllByText('Resolve Complaint')).toHaveLength(1)
})
it('shows the empty state when there are no complaints', async () => {
setupApiMocks({ procedures: { 'admin.complaint.getAll': page([]) } })
renderWithProviders(<Complaints />)
await waitFor(() => expect(screen.getByText('No complaints')).toBeVisible())
expect(screen.getByText('All complaints will appear here')).toBeVisible()
})
it('shows the error state and refetches on Retry', async () => {
const api = setupApiMocks({
procedures: {
'admin.complaint.getAll': () => {
throw new Error('boom')
},
},
})
renderWithProviders(<Complaints />)
await waitFor(() => expect(screen.getByText('Error')).toBeVisible())
const before = procCount(api.fetchMock, 'admin.complaint.getAll')
fireEvent.press(screen.getByText('Retry'))
await waitFor(() =>
expect(procCount(api.fetchMock, 'admin.complaint.getAll')).toBeGreaterThan(before)
)
})
it('resolves a complaint with the admin response and refetches', async () => {
const api = setupApiMocks({
procedures: {
'admin.complaint.getAll': page([pendingComplaint]),
'admin.complaint.resolve': { message: 'Complaint resolved successfully' },
},
})
renderWithProviders(<Complaints />)
await waitFor(() => expect(screen.getByText('Complaint #5')).toBeVisible())
const before = procCount(api.fetchMock, 'admin.complaint.getAll')
fireEvent.press(screen.getByText('Resolve Complaint'))
fireEvent.changeText(
await screen.findByPlaceholderText('Add a comment...'),
'Refund issued'
)
fireEvent.press(screen.getByText('Resolve'))
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.complaint.resolve'))
expect(lastProcedureInput(api.fetchMock, 'admin.complaint.resolve')).toEqual({
id: '5',
response: 'Refund issued',
})
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Complaint marked as resolved')
)
await waitFor(() =>
expect(procCount(api.fetchMock, 'admin.complaint.getAll')).toBeGreaterThan(before)
)
})
it('sends an empty response when the admin confirms without a note', async () => {
const api = setupApiMocks({
procedures: {
'admin.complaint.getAll': page([pendingComplaint]),
'admin.complaint.resolve': { message: 'ok' },
},
})
renderWithProviders(<Complaints />)
await waitFor(() => expect(screen.getByText('Complaint #5')).toBeVisible())
fireEvent.press(screen.getByText('Resolve Complaint'))
fireEvent.press(await screen.findByText('Resolve'))
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.complaint.resolve'))
expect(lastProcedureInput(api.fetchMock, 'admin.complaint.resolve')).toEqual({
id: '5',
response: '',
})
})
it('navigates to the user and the order from a complaint row', async () => {
setupApiMocks({
procedures: { 'admin.complaint.getAll': page([pendingComplaint]) },
})
renderWithProviders(<Complaints />)
await waitFor(() => expect(screen.getByText('Complaint #5')).toBeVisible())
fireEvent.press(screen.getByText('Alice'))
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/user-management/3')
fireEvent.press(screen.getByText('Order #7'))
expect(routerMock.push).toHaveBeenCalledWith(
'/(drawer)/dashboard/manage-orders/order-details/7'
)
})
it('fetches the next page when the list end is reached', async () => {
const api = setupApiMocks({
procedures: {
'admin.complaint.getAll': (input: { cursor?: number }) =>
input?.cursor
? page([{ ...pendingComplaint, id: 9, text: 'Second page' }])
: page([pendingComplaint], 100),
},
})
renderWithProviders(<Complaints />)
await screen.findByText('Complaint #5')
const list = screen.UNSAFE_getByType(FlatList as never)
act(() => list.props.onEndReached())
expect(await screen.findByText('Second page')).toBeVisible()
expect(lastProcedureInput(api.fetchMock, 'admin.complaint.getAll')).toMatchObject({
limit: 20,
cursor: 100,
})
})
})

View file

@ -0,0 +1,199 @@
/**
* Create coupon screen (app/(drawer)/dashboard/coupons/create.tsx) — CouponForm
* wiring, payload shaping (targetUsers->targetUser, flat->maxValue) and the
* create / createReservedCoupon mutations.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import CreateCoupon from '@/app/(drawer)/dashboard/coupons/create'
import { setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { routerMock, searchParamsMock } from '../mocks/router'
import { createQueryClient, renderWithProviders } from '../helpers/render'
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?.())
}
const fillPercentageCoupon = (code = 'save10', percent = '10') => {
fireEvent.changeText(screen.getByPlaceholderText('e.g., SECRET10'), code)
fireEvent.press(screen.getByText('Percentage'))
fireEvent.changeText(screen.getByPlaceholderText('e.g., 10'), percent)
}
describe('Create coupon', () => {
beforeEach(() => {
resetStaffAuthMock()
searchParamsMock.current = {}
routerMock.back.mockClear()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('renders the coupon form', () => {
setupApiMocks()
renderWithProviders(<CreateCoupon />)
expect(screen.getByText('Coupon Codes')).toBeVisible()
expect(screen.getByText('Discount Type *')).toBeVisible()
expect(screen.getByText('Create Coupon')).toBeVisible()
})
it('does not submit when the form is invalid', async () => {
const { fetchMock } = setupApiMocks()
renderWithProviders(<CreateCoupon />)
fireEvent.press(screen.getByText('Create Coupon'))
await waitFor(() => expect(screen.getByText('Code 1')).toBeVisible())
expect(procCount(fetchMock, 'admin.coupon.create')).toBe(0)
expect(procCount(fetchMock, 'admin.coupon.createReservedCoupon')).toBe(0)
})
it('uppercases the coupon code as it is typed', () => {
setupApiMocks()
renderWithProviders(<CreateCoupon />)
fireEvent.changeText(screen.getByPlaceholderText('e.g., SECRET10'), 'save10')
expect(screen.getByDisplayValue('SAVE10')).toBeVisible()
})
it('creates a percentage coupon with the expected payload', async () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.coupon.create': [{ id: 1, couponCode: 'SAVE10' }] },
})
renderWithProviders(<CreateCoupon />)
fillPercentageCoupon()
fireEvent.press(screen.getByText('Create Coupon'))
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.coupon.create'))
expect(lastProcedureInput(fetchMock, 'admin.coupon.create')).toMatchObject({
couponCodes: ['SAVE10'],
discountPercent: 10,
isUserBased: false,
isApplyForAll: false,
exclusiveApply: false,
isFirstOrderOnly: false,
})
expect(procCount(fetchMock, 'admin.coupon.createReservedCoupon')).toBe(0)
})
it('invalidates both coupon list queries by path after a create', async () => {
setupApiMocks({
procedures: { 'admin.coupon.create': [{ id: 1, couponCode: 'SAVE10' }] },
})
// The list queries behind this form are not mounted here, so a fetch-count
// assertion cannot see the refresh. Spy on the injected query client
// instead; jest.spyOn keeps calling through, so invalidation still happens.
const client = createQueryClient()
const invalidateSpy = jest.spyOn(client, 'invalidateQueries')
renderWithProviders(<CreateCoupon />, { queryClient: client })
fillPercentageCoupon()
fireEvent.press(screen.getByText('Create Coupon'))
await waitFor(() => expect(invalidateSpy).toHaveBeenCalled())
// tRPC keys are [pathArray, ...]; assert the ARRAY path was used, so a
// differently-filtered list (any search term) still matches the refresh.
const paths = invalidateSpy.mock.calls.map((call) => {
const key = (call[0] as { queryKey?: unknown[] } | undefined)?.queryKey
return Array.isArray(key) ? key[0] : null
})
expect(paths).toContainEqual(['admin', 'coupon', 'getAll'])
expect(paths).toContainEqual(['admin', 'coupon', 'getReservedCoupons'])
})
it('creates a flat-discount coupon and mirrors it into maxValue', async () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.coupon.create': [{ id: 1 }] },
})
renderWithProviders(<CreateCoupon />)
fireEvent.changeText(screen.getByPlaceholderText('e.g., SECRET10'), 'flat50')
fireEvent.press(screen.getByText('Flat Amount'))
fireEvent.changeText(screen.getByPlaceholderText('e.g., 50'), '50')
fireEvent.press(screen.getByText('Create Coupon'))
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.coupon.create'))
const input = lastProcedureInput(fetchMock, 'admin.coupon.create') as Record<string, unknown>
expect(input).toMatchObject({ couponCodes: ['FLAT50'], flatDiscount: 50, maxValue: 50 })
expect(input.discountPercent).toBeUndefined()
})
it('creates a reserved coupon when the checkbox is set', async () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.coupon.createReservedCoupon': [{ id: 1 }] },
})
renderWithProviders(<CreateCoupon />)
fillPercentageCoupon('secret20', '20')
fireEvent.press(screen.getByRole('checkbox'))
fireEvent.press(screen.getByText('Create Coupon'))
await waitFor(() =>
expectProcedureCalled(fetchMock, 'admin.coupon.createReservedCoupon')
)
expect(lastProcedureInput(fetchMock, 'admin.coupon.createReservedCoupon')).toMatchObject({
couponCodes: ['SECRET20'],
discountPercent: 20,
})
expect(procCount(fetchMock, 'admin.coupon.create')).toBe(0)
})
it('alerts success and navigates back when the form is confirmed', async () => {
setupApiMocks({
procedures: { 'admin.coupon.create': [{ id: 1 }] },
})
renderWithProviders(<CreateCoupon />)
fillPercentageCoupon()
fireEvent.press(screen.getByText('Create Coupon'))
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Success',
'1 coupon created successfully',
expect.any(Array)
)
)
pressLastAlertButton('OK')
expect(routerMock.back).toHaveBeenCalled()
})
it('alerts the mutation error message', async () => {
setupApiMocks({
procedures: {
'admin.coupon.create': () => {
throw new Error('Coupon code already exists: SAVE10')
},
},
})
renderWithProviders(<CreateCoupon />)
fillPercentageCoupon()
fireEvent.press(screen.getByText('Create Coupon'))
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Error',
'Coupon code already exists: SAVE10'
)
)
})
})

View file

@ -0,0 +1,218 @@
/**
* Edit coupon screen (app/(drawer)/dashboard/coupons/edit/[id].tsx) — hydrates
* CouponForm from getById and dispatches the update mutation.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import EditCoupon from '@/app/(drawer)/dashboard/coupons/edit/[id]'
import { setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { routerMock, searchParamsMock } from '../mocks/router'
import { createQueryClient, renderWithProviders } from '../helpers/render'
const coupon = {
id: 5,
couponCode: 'EDIT10',
isUserBased: false,
discountPercent: '10',
flatDiscount: null,
minOrder: '100',
skuIds: [],
maxValue: '50',
isApplyForAll: true,
validTill: '2099-01-01T00:00:00.000Z',
maxLimitForUser: 2,
exclusiveApply: false,
isFirstOrderOnly: false,
isInvalidated: false,
createdBy: 1,
targetUser: { id: 3, name: 'shafi', mobile: '9999999999' },
applicableUsers: [],
applicableProducts: [],
}
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('Edit coupon', () => {
beforeEach(() => {
resetStaffAuthMock()
searchParamsMock.current = { id: '5' }
routerMock.back.mockClear()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('shows loading while getById is pending', () => {
setupApiMocks({ procedures: { 'admin.coupon.getById': coupon } })
renderWithProviders(<EditCoupon />)
expect(screen.getByText('Loading...')).toBeVisible()
})
it('requests the coupon by the route id', async () => {
const { fetchMock } = setupApiMocks({ procedures: { 'admin.coupon.getById': coupon } })
renderWithProviders(<EditCoupon />)
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.coupon.getById'))
expect(lastProcedureInput(fetchMock, 'admin.coupon.getById')).toEqual({ id: 5 })
})
it('prefills the form from the fetched coupon', async () => {
setupApiMocks({ procedures: { 'admin.coupon.getById': coupon } })
renderWithProviders(<EditCoupon />)
expect(await screen.findByDisplayValue('EDIT10')).toBeVisible()
expect(screen.getByDisplayValue('10')).toBeVisible()
expect(screen.getByDisplayValue('100')).toBeVisible()
})
it('shows a not-found state when the coupon does not exist', async () => {
setupApiMocks({ procedures: { 'admin.coupon.getById': null } })
renderWithProviders(<EditCoupon />)
expect(await screen.findByText('Coupon not found')).toBeVisible()
})
it('dispatches update with the transformed payload', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'admin.coupon.getById': coupon,
'admin.coupon.update': { ...coupon },
},
})
renderWithProviders(<EditCoupon />)
await screen.findByDisplayValue('EDIT10')
fireEvent.press(screen.getByText('Create Coupon'))
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.coupon.update'))
const input = lastProcedureInput(fetchMock, 'admin.coupon.update') as {
id: number
updates: Record<string, unknown>
}
expect(input.id).toBe(5)
expect(input.updates).toMatchObject({
couponCodes: ['EDIT10'],
discountPercent: 10,
minOrder: 100,
maxValue: 50,
isApplyForAll: true,
isUserBased: false,
targetUser: 3,
isReservedCoupon: false,
})
expect(input.updates.targetUsers).toBeUndefined()
})
it('does not call update before the coupon loads', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'admin.coupon.getById': () => new Promise(() => {}),
},
})
renderWithProviders(<EditCoupon />)
expect(procCount(fetchMock, 'admin.coupon.update')).toBe(0)
})
it('alerts the update error message', async () => {
setupApiMocks({
procedures: {
'admin.coupon.getById': coupon,
'admin.coupon.update': () => {
throw new Error('Cannot have both discountPercent and flatDiscount')
},
},
})
renderWithProviders(<EditCoupon />)
await screen.findByDisplayValue('EDIT10')
fireEvent.press(screen.getByText('Create Coupon'))
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Error',
'Cannot have both discountPercent and flatDiscount'
)
)
})
it('alerts success and navigates back after update', async () => {
setupApiMocks({
procedures: {
'admin.coupon.getById': coupon,
'admin.coupon.update': { ...coupon },
},
})
renderWithProviders(<EditCoupon />)
await screen.findByDisplayValue('EDIT10')
fireEvent.press(screen.getByText('Create Coupon'))
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Success',
'Coupon updated successfully',
expect.any(Array)
)
)
pressLastAlertButton('OK')
expect(routerMock.back).toHaveBeenCalled()
})
it('refetches the mounted coupon and invalidates both coupon lists by path after update', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'admin.coupon.getById': coupon,
'admin.coupon.update': { ...coupon },
},
})
const client = createQueryClient()
const invalidateSpy = jest.spyOn(client, 'invalidateQueries')
renderWithProviders(<EditCoupon />, { queryClient: client })
await screen.findByDisplayValue('EDIT10')
// These suites share a module-singleton tRPC client, so baseline the count
// right before the interaction and assert a delta, never an absolute number.
const before = procCount(fetchMock, 'admin.coupon.getById')
fireEvent.press(screen.getByText('Create Coupon'))
// (a) the mounted getById query really refetches.
await waitFor(() =>
expect(procCount(fetchMock, 'admin.coupon.getById')).toBeGreaterThan(before)
)
// (b) the two list invalidations used the ARRAY path, not a dotted string.
const invalidatedPaths = () =>
invalidateSpy.mock.calls.map((call) => {
const key = (call[0] as { queryKey?: unknown[] } | undefined)?.queryKey
return Array.isArray(key) ? key[0] : null
})
await waitFor(() =>
expect(invalidatedPaths()).toContainEqual(['admin', 'coupon', 'getAll'])
)
expect(invalidatedPaths()).toContainEqual([
'admin',
'coupon',
'getReservedCoupons',
])
})
})

View file

@ -0,0 +1,290 @@
/**
* Coupons list screen (app/(drawer)/dashboard/coupons/index.tsx) — the two
* TabView tabs (General / Reserved), infinite pagination, search, delete and
* navigation to create/edit.
*
* HARNESS BUG WORKAROUND: tests/mocks/native.ts `tabViewMock` is internally
* inconsistent — its `SceneMap` returns the scenes object while `TabView`
* invokes `renderScene({ route })` as a function, so rendering this screen
* throws `TypeError: renderScene is not a function`. Its tab press also
* hardcodes `onIndexChange(0)`. We override the module locally with a corrected
* copy (the harness file itself is untouched). See the final report.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
jest.mock('react-native-tab-view', () => {
const React = require('react')
const { View, Text } = require('react-native')
const TabView = ({
navigationState,
renderScene,
onIndexChange,
}: {
navigationState: { index: number; routes: { key: string }[] }
renderScene: (info: { route: { key: string } }) => React.ReactNode
onIndexChange?: (index: number) => void
}) => {
const route = navigationState.routes[navigationState.index]
return React.createElement(
View,
{ testID: 'mock-tab-view' },
navigationState.routes.map((r, i) =>
React.createElement(
Text,
{ key: r.key, testID: `tab-${r.key}`, onPress: () => onIndexChange?.(i) },
r.key
)
),
route ? renderScene({ route }) : null
)
}
return {
__esModule: true,
TabView,
SceneMap: (scenes: Record<string, React.ComponentType>) => ({ route }: { route: { key: string } }) => {
const Scene = scenes[route.key]
return React.createElement(Scene)
},
TabBar: () => null,
}
})
import React from 'react'
import { Alert, FlatList } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import Coupons from '@/app/(drawer)/dashboard/coupons/index'
import { setupApiMocks } from '../mocks/api'
import { lastProcedureInput, expectProcedureCalled, procCount } from '../mocks/procedures'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { searchParamsMock, routerMock } from '../mocks/router'
import { renderWithProviders } from '../helpers/render'
const activeCoupon = {
id: 1,
couponCode: 'SAVE10',
isUserBased: false,
discountPercent: '10',
flatDiscount: null,
minOrder: null,
skuIds: null,
maxValue: null,
isApplyForAll: true,
validTill: '2099-01-01T00:00:00.000Z',
maxLimitForUser: null,
exclusiveApply: false,
isFirstOrderOnly: false,
isInvalidated: false,
createdBy: 1,
applicableUsers: [],
applicableProducts: [],
}
const expiredCoupon = {
...activeCoupon,
id: 2,
couponCode: 'OLDCODE',
flatDiscount: '50',
discountPercent: null,
validTill: '2000-01-01T00:00:00.000Z',
}
const reservedCoupon = {
id: 9,
secretCode: 'SECRET9',
couponCode: 'SECRET9',
discountPercent: '20',
flatDiscount: null,
minOrder: null,
maxValue: null,
validTill: '2099-01-01T00:00:00.000Z',
isRedeemed: false,
redeemedUser: null,
redeemedAt: null,
creator: { id: 1, name: 'shafi' },
}
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 }[]
const button = buttons.find((b) => b.text === label)
act(() => button?.onPress?.())
}
describe('Coupons index', () => {
beforeEach(() => {
resetStaffAuthMock()
searchParamsMock.current = {}
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
routerMock.push.mockClear()
})
it('shows a loading state while the list query is pending', () => {
setupApiMocks({ procedures: { 'admin.coupon.getAll': { coupons: [activeCoupon] } } })
renderWithProviders(<Coupons />)
expect(screen.getByText('Loading Coupons...')).toBeVisible()
})
it('renders coupon rows from the getAll infinite query', async () => {
setupApiMocks({
procedures: { 'admin.coupon.getAll': { coupons: [activeCoupon, expiredCoupon] } },
})
renderWithProviders(<Coupons />)
expect(await screen.findByText('SAVE10')).toBeVisible()
expect(screen.getByText('OLDCODE')).toBeVisible()
expect(screen.getByText('Discount: 10% off')).toBeVisible()
expect(screen.getByText('Discount: ₹50 off')).toBeVisible()
expect(screen.getAllByText('Expired').length).toBeGreaterThan(0)
})
it('renders the empty state when there are no coupons', async () => {
setupApiMocks({ procedures: { 'admin.coupon.getAll': { coupons: [] } } })
renderWithProviders(<Coupons />)
expect(await screen.findByText('No Coupons Found')).toBeVisible()
})
it('renders the error state and retries on press', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'admin.coupon.getAll': () => {
throw new Error('boom')
},
},
})
renderWithProviders(<Coupons />)
expect(await screen.findByText('Failed to load coupons')).toBeVisible()
const before = procCount(fetchMock, 'admin.coupon.getAll')
fireEvent.press(screen.getByText('Retry'))
await waitFor(() =>
expect(procCount(fetchMock, 'admin.coupon.getAll')).toBeGreaterThan(before)
)
})
it('fetches the next page when the list end is reached', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'admin.coupon.getAll': (input: any) =>
input?.cursor
? { coupons: [{ ...activeCoupon, id: 3, couponCode: 'PAGE2' }] }
: { coupons: [activeCoupon], nextCursor: 100 },
},
})
renderWithProviders(<Coupons />)
await screen.findByText('SAVE10')
const list = screen.UNSAFE_getByType(FlatList as any)
act(() => list.props.onEndReached())
expect(await screen.findByText('PAGE2')).toBeVisible()
expect(lastProcedureInput(fetchMock, 'admin.coupon.getAll')).toMatchObject({
limit: 20,
cursor: 100,
})
})
it('sends the search term to getAll', async () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.coupon.getAll': { coupons: [activeCoupon] } },
})
renderWithProviders(<Coupons />)
await screen.findByText('SAVE10')
fireEvent.changeText(screen.getByPlaceholderText('Search coupons...'), 'SAVE')
await waitFor(() =>
expect(lastProcedureInput(fetchMock, 'admin.coupon.getAll')).toMatchObject({
limit: 20,
search: 'SAVE',
})
)
})
it('navigates to the create screen from the floating action button', async () => {
setupApiMocks({ procedures: { 'admin.coupon.getAll': { coupons: [activeCoupon] } } })
renderWithProviders(<Coupons />)
await screen.findByText('SAVE10')
fireEvent.press(screen.getByTestId('mock-linear-gradient'))
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/coupons/create')
})
it('navigates to the edit screen for the pressed coupon', async () => {
setupApiMocks({ procedures: { 'admin.coupon.getAll': { coupons: [activeCoupon] } } })
renderWithProviders(<Coupons />)
await screen.findByText('SAVE10')
fireEvent.press(screen.getByText('Edit'))
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/coupons/edit/1')
})
it('deletes a coupon after confirming the alert', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'admin.coupon.getAll': { coupons: [activeCoupon] },
'admin.coupon.delete': { message: 'Coupon invalidated successfully' },
},
})
renderWithProviders(<Coupons />)
await screen.findByText('SAVE10')
fireEvent.press(screen.getByText('Delete'))
expect(Alert.alert).toHaveBeenCalledWith(
'Delete Coupon',
'Are you sure you want to delete this coupon?',
expect.any(Array)
)
pressLastAlertButton('Delete')
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.coupon.delete'))
expect(lastProcedureInput(fetchMock, 'admin.coupon.delete')).toEqual({ id: 1 })
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Coupon deleted successfully')
)
})
it('switches to the Reserved tab and lists reserved coupons', async () => {
setupApiMocks({
procedures: {
'admin.coupon.getAll': { coupons: [activeCoupon] },
'admin.coupon.getReservedCoupons': { coupons: [reservedCoupon] },
},
})
renderWithProviders(<Coupons />)
await screen.findByText('SAVE10')
fireEvent.press(screen.getByTestId('tab-reserved'))
expect(await screen.findByText('SECRET9')).toBeVisible()
expect(screen.getByTestId('tab-reserved')).toBeVisible()
})
it('shows the reserved empty state', async () => {
setupApiMocks({
procedures: {
'admin.coupon.getAll': { coupons: [activeCoupon] },
'admin.coupon.getReservedCoupons': { coupons: [] },
},
})
renderWithProviders(<Coupons />)
fireEvent.press(screen.getByTestId('tab-reserved'))
expect(await screen.findByText('No Reserved Coupons Found')).toBeVisible()
})
})

View file

@ -0,0 +1,220 @@
/**
* All items order editor
* (app/(drawer)/dashboard/customize-app/all-items-order.tsx) — sorts the
* catalogue by the `allItemsOrder` constant, supports drag reordering and saves
* the full ordered id list back to the constant.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import AllItemsOrder from '@/app/(drawer)/dashboard/customize-app/all-items-order'
import { resetStorage, setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { routerMock } from '../mocks/router'
import { createQueryClient, renderWithProviders } from '../helpers/render'
const productsResponse = {
products: [
{ id: 1, name: 'Chicken', images: ['chicken.jpg'], isOutOfStock: false },
{ id: 2, name: 'Mutton', images: ['mutton.jpg'], isOutOfStock: true },
{ id: 3, name: 'Fish', images: [], isOutOfStock: false },
],
count: 3,
}
describe('All items order editor', () => {
beforeEach(async () => {
await resetStorage()
setupApiMocks()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('shows the loading state while constants load', () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': () => new Promise(() => {}),
'common.product.getAllProductsSummary': productsResponse,
},
})
renderWithProviders(<AllItemsOrder />)
expect(screen.getByText('Loading order...')).toBeVisible()
})
it('shows the error state when constants fail', async () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': () => {
throw new Error('boom')
},
'common.product.getAllProductsSummary': productsResponse,
},
})
renderWithProviders(<AllItemsOrder />)
await waitFor(() => expect(screen.getByText('Failed to load order')).toBeVisible())
})
it('sorts products by the constant and appends the rest', async () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': [{ key: 'allItemsOrder', value: [2, 1] }],
'common.product.getAllProductsSummary': productsResponse,
},
})
const result = renderWithProviders(<AllItemsOrder />)
await waitFor(() => expect(screen.getByText('Mutton')).toBeVisible())
const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default)
expect(list.props.data.map((p: { id: number }) => p.id)).toEqual([2, 1, 3])
expect(screen.getByText(/3 items/)).toBeVisible()
})
it('accepts a comma-separated order string', async () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': [{ key: 'allItemsOrder', value: '3' }],
'common.product.getAllProductsSummary': productsResponse,
},
})
const result = renderWithProviders(<AllItemsOrder />)
await waitFor(() => expect(screen.getByText('Fish')).toBeVisible())
const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default)
expect(list.props.data.map((p: { id: number }) => p.id)).toEqual([3, 1, 2])
})
it('shows the empty state when there are no products', async () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': [{ key: 'allItemsOrder', value: [] }],
'common.product.getAllProductsSummary': { products: [], count: 0 },
},
})
renderWithProviders(<AllItemsOrder />)
await waitFor(() => expect(screen.getByText('No products available')).toBeVisible())
})
it('disables Save until the order changes, then saves the full list', async () => {
const api = setupApiMocks({
procedures: {
'admin.const.getConstants': [{ key: 'allItemsOrder', value: [1, 2, 3] }],
'common.product.getAllProductsSummary': productsResponse,
'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['allItemsOrder'] },
},
})
const result = renderWithProviders(<AllItemsOrder />)
await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible())
fireEvent.press(screen.getByText('Save'))
expect(procCount(api.fetchMock, 'admin.const.updateConstants')).toBe(0)
const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default)
act(() => {
list.props.onDragEnd({ data: [list.props.data[2], list.props.data[0], list.props.data[1]] })
})
fireEvent.press(screen.getByText('Save'))
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.const.updateConstants'))
expect(lastProcedureInput(api.fetchMock, 'admin.const.updateConstants')).toEqual({
constants: [{ key: 'allItemsOrder', value: [3, 1, 2] }],
})
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Success',
'All items order updated successfully!'
)
)
})
it('refetches the constants after saving', async () => {
const api = setupApiMocks({
procedures: {
'admin.const.getConstants': [{ key: 'allItemsOrder', value: [1, 2, 3] }],
'common.product.getAllProductsSummary': productsResponse,
'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['allItemsOrder'] },
},
})
const client = createQueryClient()
const invalidateSpy = jest.spyOn(client, 'invalidateQueries')
const result = renderWithProviders(<AllItemsOrder />, { queryClient: client })
await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible())
const before = procCount(api.fetchMock, 'admin.const.getConstants')
// Delta, not an absolute: the suite shares one httpBatchLink client, so a prior test's
// request can land in this test's fetchMock.
expect(before).toBeGreaterThan(0)
const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default)
act(() => {
list.props.onDragEnd({ data: [list.props.data[2], list.props.data[0], list.props.data[1]] })
})
fireEvent.press(screen.getByText('Save'))
await waitFor(() =>
expect(procCount(api.fetchMock, 'admin.const.getConstants')).toBeGreaterThan(before)
)
// The refetch is driven by the path-based invalidation, not by updateConstants itself.
// Asserting the ARRAY path is the point: the old dotted string matched no query at all.
await waitFor(() => expect(invalidateSpy).toHaveBeenCalled())
expect(
invalidateSpy.mock.calls
.map((call) => (call[0] as { queryKey?: unknown[] } | undefined)?.queryKey)
.map((key) => (Array.isArray(key) ? key[0] : null))
).toContainEqual(['admin', 'const', 'getConstants'])
// Same client, same cache: the array path matches the live query, the dotted form matches none.
expect(
client.getQueryCache().findAll({ queryKey: [['admin', 'const', 'getConstants']] }).length
).toBeGreaterThan(0)
expect(
client.getQueryCache().findAll({ queryKey: ['admin.const.getConstants'] })
).toHaveLength(0)
})
it('shows the saving label while the update is pending', async () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': [{ key: 'allItemsOrder', value: [1, 2, 3] }],
'common.product.getAllProductsSummary': productsResponse,
'admin.const.updateConstants': () => new Promise(() => {}),
},
})
const result = renderWithProviders(<AllItemsOrder />)
await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible())
const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default)
act(() => {
list.props.onDragEnd({ data: [list.props.data[1], list.props.data[0], list.props.data[2]] })
})
fireEvent.press(screen.getByText('Save'))
await waitFor(() => expect(screen.getByText('Saving...')).toBeVisible())
})
it('goes back from the header and the error state', async () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': () => {
throw new Error('boom')
},
'common.product.getAllProductsSummary': productsResponse,
},
})
renderWithProviders(<AllItemsOrder />)
await waitFor(() => expect(screen.getByText('Failed to load order')).toBeVisible())
fireEvent.press(screen.getByText('Go Back'))
expect(routerMock.back).toHaveBeenCalled()
})
})

View file

@ -0,0 +1,171 @@
/**
* Customize App hub (app/(drawer)/dashboard/customize-app/index.tsx) — renders
* the visible constants, links to the popular-items / all-items-order editors,
* and saves only the constants that changed.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import CustomizeApp from '@/app/(drawer)/dashboard/customize-app/index'
import { resetStorage, setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { routerMock } from '../mocks/router'
import { renderWithProviders } from '../helpers/render'
const constants = [
{ key: 'deliveryCharge', value: 10 },
{ key: 'supportMobile', value: '9999999999' },
{ key: 'isFlashDeliveryEnabled', value: false },
{ key: 'popularItems', value: [1, 2] },
{ key: 'allItemsOrder', value: [3] },
]
const renderHub = () =>
renderWithProviders(<CustomizeApp />)
describe('Customize App hub', () => {
beforeEach(async () => {
await resetStorage()
setupApiMocks()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('shows the loading state while constants load', () => {
setupApiMocks({
procedures: { 'admin.const.getConstants': () => new Promise(() => {}) },
})
renderHub()
expect(screen.getByText('Loading constants...')).toBeVisible()
})
it('shows the failed state when constants are missing', async () => {
renderHub()
await waitFor(() => expect(screen.getByText('Failed to load constants')).toBeVisible())
})
it('renders the visible constants and section links', async () => {
setupApiMocks({
procedures: { 'admin.const.getConstants': constants },
})
renderHub()
expect(await screen.findByText('Customize App Constants')).toBeVisible()
expect(screen.getByText('Delivery Charge')).toBeVisible()
expect(screen.getByText('Support Mobile')).toBeVisible()
expect(screen.getByText('Enable Flash Delivery')).toBeVisible()
expect(screen.getByText('Manage Popular Items (2 items)')).toBeVisible()
expect(screen.getByText('Manage All Visible Items (1 items)')).toBeVisible()
expect(screen.getByText('Save Changes')).toBeVisible()
})
it('navigates to the popular items editor', async () => {
setupApiMocks({
procedures: { 'admin.const.getConstants': constants },
})
renderHub()
fireEvent.press(await screen.findByText('Manage Popular Items (2 items)'))
expect(routerMock.push).toHaveBeenCalledWith(
'/(drawer)/dashboard/customize-app/popular-items'
)
})
it('navigates to the all items order editor', async () => {
setupApiMocks({
procedures: { 'admin.const.getConstants': constants },
})
renderHub()
fireEvent.press(await screen.findByText('Manage All Visible Items (1 items)'))
expect(routerMock.push).toHaveBeenCalledWith(
'/(drawer)/dashboard/customize-app/all-items-order'
)
})
it('alerts when saving without changes and skips the mutation', async () => {
const api = setupApiMocks({
procedures: { 'admin.const.getConstants': constants },
})
renderHub()
fireEvent.press(await screen.findByText('Save Changes'))
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('No Changes', 'No constants were modified.')
)
expect(procCount(api.fetchMock, 'admin.const.updateConstants')).toBe(0)
})
it('saves only the changed constant', async () => {
const api = setupApiMocks({
procedures: {
'admin.const.getConstants': constants,
'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['deliveryCharge'] },
},
})
renderHub()
await screen.findByText('Delivery Charge')
fireEvent.changeText(screen.getAllByPlaceholderText('Enter number')[0], '25')
fireEvent.press(screen.getByText('Save Changes'))
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.const.updateConstants'))
expect(lastProcedureInput(api.fetchMock, 'admin.const.updateConstants')).toEqual({
constants: [{ key: 'deliveryCharge', value: 25 }],
})
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Success',
'Updated 1 constants successfully.'
)
)
})
it('toggles a boolean constant and saves it', async () => {
const api = setupApiMocks({
procedures: {
'admin.const.getConstants': constants,
'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['isFlashDeliveryEnabled'] },
},
})
renderHub()
await screen.findByText('Enable Flash Delivery')
expect(screen.getByText('Disabled')).toBeVisible()
fireEvent.press(screen.getByRole('checkbox'))
await waitFor(() => expect(screen.getByText('Enabled')).toBeVisible())
fireEvent.press(screen.getByText('Save Changes'))
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.const.updateConstants'))
expect(lastProcedureInput(api.fetchMock, 'admin.const.updateConstants')).toEqual({
constants: [{ key: 'isFlashDeliveryEnabled', value: true }],
})
})
it('shows the updating label while the mutation is pending', async () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': constants,
'admin.const.updateConstants': () => new Promise(() => {}),
},
})
renderHub()
await screen.findByText('Delivery Charge')
fireEvent.changeText(screen.getAllByPlaceholderText('Enter number')[0], '25')
fireEvent.press(screen.getByText('Save Changes'))
await waitFor(() => expect(screen.getByText('Updating...')).toBeVisible())
})
})

View file

@ -0,0 +1,298 @@
/**
* Popular items editor
* (app/(drawer)/dashboard/customize-app/popular-items.tsx) — resolves the
* `popularItems` constant against the product catalogue, supports removing /
* adding items and saves the ordered product ids back to the constant.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import PopularItems from '@/app/(drawer)/dashboard/customize-app/popular-items'
import { resetStorage, setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { routerMock } from '../mocks/router'
import { createQueryClient, renderWithProviders } from '../helpers/render'
const product = (id: number, name: string, price: number) => ({
id,
name,
price,
marketPrice: null,
images: [`${name}.jpg`],
storeId: null,
nextDeliveryDate: null,
isOutOfStock: false,
})
const productsResponse = {
products: [product(1, 'Chicken', 100), product(2, 'Mutton', 200), product(3, 'Fish', 50)],
count: 3,
}
// SKU ids intentionally match product ids so the selector's ids resolve against
// the product catalogue (see the reported popular-items add-flow bug).
const skusResponse = {
skus: [
{ id: 3, productId: 3, productName: 'Fish', label: 'Fish 1kg' },
],
}
const constants = [{ key: 'popularItems', value: [1, 2] }]
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?.())
}
const pressIcon = (result: ReturnType<typeof renderWithProviders>, name: string, index = 0) => {
const icons = result.UNSAFE_getAllByType(MaterialIcons).filter((n) => n.props.name === name)
fireEvent.press(icons[index])
}
describe('Popular items editor', () => {
beforeEach(async () => {
await resetStorage()
setupApiMocks()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('shows the loading state while constants load', () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': () => new Promise(() => {}),
'common.product.getAllProductsSummary': productsResponse,
},
})
renderWithProviders(<PopularItems />)
expect(screen.getByText('Loading constants...')).toBeVisible()
})
it('shows the error state when constants fail', async () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': () => {
throw new Error('boom')
},
'common.product.getAllProductsSummary': productsResponse,
},
})
renderWithProviders(<PopularItems />)
await waitFor(() => expect(screen.getByText('Failed to load constants')).toBeVisible())
})
it('renders the popular items resolved from the constant', async () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': constants,
'common.product.getAllProductsSummary': productsResponse,
},
})
renderWithProviders(<PopularItems />)
expect(await screen.findByText('Chicken')).toBeVisible()
expect(screen.getByText('Mutton')).toBeVisible()
expect(screen.getByText('₹100')).toBeVisible()
expect(screen.queryByText('Fish')).toBeNull()
})
it('shows the empty state when nothing is configured', async () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': [{ key: 'popularItems', value: [] }],
'common.product.getAllProductsSummary': productsResponse,
},
})
renderWithProviders(<PopularItems />)
await waitFor(() =>
expect(screen.getByText('No popular items configured')).toBeVisible()
)
})
it('removes a product and saves the remaining ids', async () => {
const api = setupApiMocks({
procedures: {
'admin.const.getConstants': constants,
'common.product.getAllProductsSummary': productsResponse,
'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['popularItems'] },
},
})
const result = renderWithProviders(<PopularItems />)
await screen.findByText('Chicken')
pressIcon(result, 'delete', 0)
pressLastAlertButton('Remove')
await waitFor(() => expect(screen.queryByText('Chicken')).toBeNull())
fireEvent.press(screen.getByText('Save'))
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.const.updateConstants'))
expect(lastProcedureInput(api.fetchMock, 'admin.const.updateConstants')).toEqual({
constants: [{ key: 'popularItems', value: [2] }],
})
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Success',
'Popular items updated successfully!'
)
)
})
it('saves a reordered list', async () => {
const api = setupApiMocks({
procedures: {
'admin.const.getConstants': constants,
'common.product.getAllProductsSummary': productsResponse,
'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['popularItems'] },
},
})
const result = renderWithProviders(<PopularItems />)
await screen.findByText('Chicken')
const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default)
act(() => {
list.props.onDragEnd({ data: [list.props.data[1], list.props.data[0]] })
})
fireEvent.press(screen.getByText('Save'))
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.const.updateConstants'))
expect(lastProcedureInput(api.fetchMock, 'admin.const.updateConstants')).toEqual({
constants: [{ key: 'popularItems', value: [2, 1] }],
})
})
it('refetches the constants after saving', async () => {
const api = setupApiMocks({
procedures: {
'admin.const.getConstants': constants,
'common.product.getAllProductsSummary': productsResponse,
'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['popularItems'] },
},
})
const client = createQueryClient()
const invalidateSpy = jest.spyOn(client, 'invalidateQueries')
const result = renderWithProviders(<PopularItems />, { queryClient: client })
await screen.findByText('Chicken')
const before = procCount(api.fetchMock, 'admin.const.getConstants')
// Delta, not an absolute: the suite shares one httpBatchLink client, so a prior test's
// request can land in this test's fetchMock.
expect(before).toBeGreaterThan(0)
const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default)
act(() => {
list.props.onDragEnd({ data: [list.props.data[1], list.props.data[0]] })
})
fireEvent.press(screen.getByText('Save'))
await waitFor(() =>
expect(procCount(api.fetchMock, 'admin.const.getConstants')).toBeGreaterThan(before)
)
// The refetch is driven by the path-based invalidation, not by updateConstants itself.
// Asserting the ARRAY path is the point: the old dotted string matched no query at all.
await waitFor(() => expect(invalidateSpy).toHaveBeenCalled())
expect(
invalidateSpy.mock.calls
.map((call) => (call[0] as { queryKey?: unknown[] } | undefined)?.queryKey)
.map((key) => (Array.isArray(key) ? key[0] : null))
).toContainEqual(['admin', 'const', 'getConstants'])
// Same client, same cache: the array path matches the live query, the dotted form matches none.
expect(
client.getQueryCache().findAll({ queryKey: [['admin', 'const', 'getConstants']] }).length
).toBeGreaterThan(0)
expect(
client.getQueryCache().findAll({ queryKey: ['admin.const.getConstants'] })
).toHaveLength(0)
})
it('does not save while nothing changed', async () => {
const api = setupApiMocks({
procedures: {
'admin.const.getConstants': constants,
'common.product.getAllProductsSummary': productsResponse,
},
})
renderWithProviders(<PopularItems />)
await screen.findByText('Chicken')
fireEvent.press(screen.getByText('Save'))
expect(procCount(api.fetchMock, 'admin.const.updateConstants')).toBe(0)
})
it('adds a product through the add dialog and saves it', async () => {
const api = setupApiMocks({
procedures: {
'admin.const.getConstants': constants,
'common.product.getAllProductsSummary': productsResponse,
'common.product.getAllSkusSummary': skusResponse,
'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['popularItems'] },
},
})
const result = renderWithProviders(<PopularItems />)
await screen.findByText('Chicken')
pressIcon(result, 'add')
expect(await screen.findByText('Add Popular Items')).toBeVisible()
fireEvent.press(screen.getByText('Choose products...'))
fireEvent.press(await screen.findByTestId('undefined-option-3'))
fireEvent.press(screen.getByText('Done'))
fireEvent.press(await screen.findByText('Add 1 Product'))
await waitFor(() => expect(screen.getByText('Fish')).toBeVisible())
fireEvent.press(screen.getByText('Save'))
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.const.updateConstants'))
expect(lastProcedureInput(api.fetchMock, 'admin.const.updateConstants')).toEqual({
constants: [{ key: 'popularItems', value: [1, 2, 3] }],
})
})
it('shows the saving label while the update is pending', async () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': constants,
'common.product.getAllProductsSummary': productsResponse,
'admin.const.updateConstants': () => new Promise(() => {}),
},
})
const result = renderWithProviders(<PopularItems />)
await screen.findByText('Chicken')
pressIcon(result, 'delete', 0)
pressLastAlertButton('Remove')
fireEvent.press(screen.getByText('Save'))
await waitFor(() => expect(screen.getByText('Saving...')).toBeVisible())
})
it('goes back from the header and the error state', async () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': () => {
throw new Error('boom')
},
'common.product.getAllProductsSummary': productsResponse,
},
})
renderWithProviders(<PopularItems />)
await waitFor(() => expect(screen.getByText('Failed to load constants')).toBeVisible())
fireEvent.press(screen.getByText('Go Back'))
expect(routerMock.back).toHaveBeenCalled()
})
})

View file

@ -0,0 +1,116 @@
/**
* Dashboard hub (app/(drawer)/dashboard/index.tsx) — quick actions, the
* complaints badge from getEssentials, and navigation (incl. the navigation
* target set for the manage-orders flow).
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Text } from 'react-native'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import Dashboard from '@/app/(drawer)/dashboard/index'
import { useNavigationTarget } from 'common-ui/hooks/useNavigationTarget'
import { resetStorage, setupApiMocks } from '../mocks/api'
import { expectProcedureCalled } from '../mocks/procedures'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
import { renderWithProviders } from '../helpers/render'
const TargetProbe = () => {
const { navigationTarget } = useNavigationTarget()
return <Text testID="target-probe">{navigationTarget ?? 'none'}</Text>
}
describe('Dashboard hub', () => {
beforeEach(async () => {
resetStaffAuthMock()
await resetStorage()
resetRouterMock()
searchParamsMock.current = {}
setupApiMocks({
procedures: { 'admin.user.getEssentials': { unresolvedComplaints: 3 } },
})
})
it('renders the quick actions and grouped menu items', async () => {
renderWithProviders(<Dashboard />)
expect(screen.getByText('Quick Actions')).toBeVisible()
expect(screen.getByText('Delivery Slots')).toBeVisible()
expect(screen.getByText('Add Product')).toBeVisible()
expect(screen.getByText('Complaints')).toBeVisible()
expect(screen.getByText('Orders')).toBeVisible()
expect(screen.getByText('Manage Orders')).toBeVisible()
expect(screen.getByText('Delivery Sequences')).toBeVisible()
expect(screen.getByText('Products & Inventory')).toBeVisible()
expect(screen.getByText('Prices Overview')).toBeVisible()
expect(screen.getByText('Product Groupings')).toBeVisible()
expect(screen.getByText('Settings & Configuration')).toBeVisible()
// Both the category header and its menu tile say "User Management".
expect(screen.getAllByText('User Management').length).toBeGreaterThan(0)
})
it('shows the unresolved-complaints badge from getEssentials', async () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.user.getEssentials': { unresolvedComplaints: 3 } },
})
renderWithProviders(<Dashboard />)
await waitFor(() => expect(screen.getByText('3')).toBeVisible())
expectProcedureCalled(fetchMock, 'admin.user.getEssentials')
})
it('navigates to manage orders and sets the nested navigation target', () => {
renderWithProviders(
<>
<Dashboard />
<TargetProbe />
</>
)
fireEvent.press(screen.getByText('Manage Orders'))
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/manage-orders')
expect(screen.getByTestId('target-probe')).toHaveTextContent(
'/(drawer)/dashboard/manage-orders/orders'
)
})
it('navigates to delivery sequences with its nested navigation target', () => {
renderWithProviders(
<>
<Dashboard />
<TargetProbe />
</>
)
fireEvent.press(screen.getByText('Delivery Sequences'))
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/manage-orders')
expect(screen.getByTestId('target-probe')).toHaveTextContent(
'/(drawer)/dashboard/manage-orders/delivery-sequences'
)
})
it('navigates from the quick-action tiles by testID', () => {
renderWithProviders(<Dashboard />)
fireEvent.press(screen.getByTestId('delivery-slots-menu-item'))
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/slots')
fireEvent.press(screen.getByTestId('add-product-menu-item'))
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/products/add')
})
it('navigates to prices overview', () => {
renderWithProviders(<Dashboard />)
fireEvent.press(screen.getByText('Prices Overview'))
expect(routerMock.push).toHaveBeenCalledWith(
'/(drawer)/dashboard/prices-overview'
)
})
})

View file

@ -0,0 +1,390 @@
/**
* Delivery sequences
* (app/(drawer)/dashboard/manage-orders/delivery-sequences/index.tsx) — slot
* picker, unassigned/all-users filtering, assigning & unassigning orders,
* packaged/delivered toggles, notes, cancel and order intents.
*
* NOTE: the "save sequence" FAB only appears after a drag (`hasSequenceChanged`).
* The mocked draggable list never fires onDragEnd on its own, but the prop is
* still on the rendered element and can be invoked through
* UNSAFE_getByType(...).props.onDragEnd({ data }) inside act(), which is how the
* reorder-save path (`handleSaveSequence`) is covered below. Assignment changes
* persist via updateDeliverySequence directly.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert, Linking } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import dayjs from 'dayjs'
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import Entypo from '@expo/vector-icons/Entypo'
import Ionicons from '@expo/vector-icons/Ionicons'
import DeliverySequences from '@/app/(drawer)/dashboard/manage-orders/delivery-sequences'
import { setupApiMocks, resetStorage } from '../mocks/api'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
import { lastProcedureInput, procCount } from '../mocks/procedures'
import { refreshHooks, resetRefreshHooks } from '../mocks/refresh'
import { renderWithProviders } from '../helpers/render'
const SLOTS = [
{ id: 3, deliveryTime: '2026-01-01T09:00:00.000Z' },
{ id: 4, deliveryTime: '2026-01-02T09:00:00.000Z' },
]
const LABEL_3 = dayjs(SLOTS[0].deliveryTime).format('ddd DD MMM, h:mm a')
const LABEL_4 = dayjs(SLOTS[1].deliveryTime).format('ddd DD MMM, h:mm a')
const slotOrder = (overrides: Record<string, unknown> = {}) => ({
id: 21,
readableId: 21,
customerName: 'Bob',
address: '12 Main St, Phone: 9876543210',
addressId: 5,
latitude: null,
longitude: null,
totalAmount: 300,
items: [],
deliveryTime: null,
status: 'pending',
isPackaged: false,
isDelivered: false,
isCod: true,
paymentMode: 'COD',
paymentStatus: 'cod',
slotId: 3,
adminNotes: 'fragile',
userNotes: null,
...overrides,
})
const defaultProcedures = (overrides: Record<string, unknown> = {}) => ({
'admin.slots.getAll': { slots: SLOTS, count: 2 },
'admin.order.getSlotOrders': { success: true, data: [slotOrder()] },
'admin.slots.getDeliverySequence': { deliverySequence: {} },
'admin.staffUser.getStaff': { staff: [{ id: 7, name: 'Ravi' }, { id: 8, name: 'Sita' }] },
'admin.slots.updateDeliverySequence': { slot: { id: 3, deliverySequence: {} }, message: 'ok' },
'admin.order.updatePackaged': { success: true, userId: 1 },
'admin.order.updateDelivered': { success: true, userId: 1 },
'admin.order.updateNotes': { id: 21 },
'admin.order.cancelOrder': { success: true, message: 'cancelled' },
'admin.order.updateAddressCoords': { success: true },
...overrides,
})
const renderScreen = (overrides: Record<string, unknown> = {}) => {
const { fetchMock } = setupApiMocks({ procedures: defaultProcedures(overrides) })
// `view` is returned so tests can reach props of the mocked DraggableFlatList
// (its `onDragEnd` prop is not fired by the mock component itself).
const view = renderWithProviders(<DeliverySequences />)
return { fetchMock, view }
}
const openOrderMenu = async () => {
const dots = screen.UNSAFE_getAllByType(Entypo)[0]
fireEvent.press(dots)
await screen.findByText('Select an action to perform')
}
const openUserDropdown = async () => {
fireEvent.press(await screen.findByText('Unassigned'))
await screen.findByText('All Users')
}
const toggleMenuResponder = async (name: 'square-outline' | 'checkbox') => {
const icon = screen.UNSAFE_getAllByType(Ionicons).find((node) => node.props.name === name)!
fireEvent(icon, 'responderEnd', { stopPropagation: jest.fn() })
}
const openAssignDropdown = async () => {
const icon = screen
.UNSAFE_getAllByType(MaterialIcons)
.find((node) => node.props.name === 'person-add')!
fireEvent.press(icon)
await screen.findByText('Assign To')
}
describe('Delivery sequences', () => {
beforeEach(async () => {
resetStaffAuthMock()
await resetStorage()
resetRouterMock()
resetRefreshHooks()
searchParamsMock.current = { slotId: '3' }
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
jest.spyOn(Linking, 'openURL').mockResolvedValue(true)
})
it('shows a loading message while slots load', () => {
renderScreen()
expect(screen.getByText('Loading slots...')).toBeVisible()
})
it('reports when there are no slots', async () => {
renderScreen({ 'admin.slots.getAll': { slots: [], count: 0 } })
expect(await screen.findByText('No slots available')).toBeVisible()
})
it('auto-selects the first slot and prompts when no slot is given', async () => {
searchParamsMock.current = {}
renderScreen()
expect(
await screen.findByText('No slot selected. Please select a slot to view delivery sequence.')
).toBeVisible()
await waitFor(() =>
expect(routerMock.replace).toHaveBeenCalledWith(
'/(drawer)/dashboard/manage-orders/delivery-sequences?slotId=3'
)
)
})
it('queries slot orders and sequence with the route slot id', async () => {
const { fetchMock } = renderScreen()
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
expect(lastProcedureInput(fetchMock, 'admin.order.getSlotOrders')).toEqual({ slotId: '3' })
expect(lastProcedureInput(fetchMock, 'admin.slots.getDeliverySequence')).toEqual({ id: '3' })
})
it('renders the order card details', async () => {
renderScreen()
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
expect(screen.getByText('₹300')).toBeVisible()
expect(screen.getByText('fragile')).toBeVisible()
})
it('renders an empty state when there are no orders', async () => {
renderScreen({ 'admin.order.getSlotOrders': { success: true, data: [] } })
expect(await screen.findByText('No orders found for this slot')).toBeVisible()
})
it('filters to a user with no sequence and reports empty', async () => {
renderScreen()
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
await openUserDropdown()
fireEvent.press(screen.getByText('Ravi'))
expect(await screen.findByText('No orders found for this slot')).toBeVisible()
})
it('shows assignment info in the All Users view', async () => {
renderScreen({ 'admin.slots.getDeliverySequence': { deliverySequence: { '7': [21] } } })
await openUserDropdown()
fireEvent.press(screen.getByText('All Users'))
expect(await screen.findByText('Assigned to')).toBeVisible()
expect(screen.getByText('Ravi')).toBeVisible()
expect(screen.getByText('#21')).toBeVisible()
})
it('assigns selected orders to a user', async () => {
const { fetchMock } = renderScreen()
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
fireEvent.press(screen.getAllByRole('checkbox')[0])
await openAssignDropdown()
fireEvent.press(screen.getByText('Ravi'))
await waitFor(() =>
expect(lastProcedureInput(fetchMock, 'admin.slots.updateDeliverySequence')).toEqual({
id: 3,
deliverySequence: { '7': [21] },
})
)
})
it('unassigns selected orders from all users', async () => {
const { fetchMock } = renderScreen({
'admin.slots.getDeliverySequence': { deliverySequence: { '7': [21] } },
})
await openUserDropdown()
fireEvent.press(screen.getByText('All Users'))
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
fireEvent.press(screen.getAllByRole('checkbox')[0])
await openAssignDropdown()
fireEvent.press(screen.getByText('None'))
await waitFor(() =>
expect(lastProcedureInput(fetchMock, 'admin.slots.updateDeliverySequence')).toEqual({
id: 3,
deliverySequence: { '7': [] },
})
)
})
it('marks an order packaged from the options menu', async () => {
const { fetchMock } = renderScreen({
'admin.order.getSlotOrders': { success: true, data: [slotOrder({ isDelivered: true })] },
})
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
const beforeOrders = procCount(fetchMock, 'admin.order.getSlotOrders')
const beforeSequence = procCount(fetchMock, 'admin.slots.getDeliverySequence')
await openOrderMenu()
await toggleMenuResponder('square-outline')
await waitFor(() => expect(lastProcedureInput(fetchMock, 'admin.order.updatePackaged')).toEqual({
orderId: '21',
isPackaged: true,
}))
// onSuccess refetches both the slot orders and the delivery sequence.
await waitFor(() => {
expect(procCount(fetchMock, 'admin.order.getSlotOrders')).toBeGreaterThan(beforeOrders)
expect(procCount(fetchMock, 'admin.slots.getDeliverySequence')).toBeGreaterThan(beforeSequence)
})
})
it('marks an order delivered from the options menu', async () => {
const { fetchMock } = renderScreen({
'admin.order.getSlotOrders': { success: true, data: [slotOrder({ isPackaged: true })] },
})
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
await openOrderMenu()
await toggleMenuResponder('square-outline')
await waitFor(() => expect(lastProcedureInput(fetchMock, 'admin.order.updateDelivered')).toEqual({
orderId: '21',
isDelivered: true,
}))
})
it('saves admin notes from the options menu', async () => {
const { fetchMock } = renderScreen()
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
await openOrderMenu()
fireEvent.press(screen.getByText('Admin Notes'))
fireEvent.changeText(
await screen.findByPlaceholderText('Enter notes for this order...'),
'fragile item'
)
fireEvent.press(screen.getByText('Save Notes'))
await waitFor(() =>
expect(lastProcedureInput(fetchMock, 'admin.order.updateNotes')).toEqual({
orderId: 21,
adminNotes: 'fragile item',
})
)
})
it('opens the cancel dialog from the options menu', async () => {
renderScreen()
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
await openOrderMenu()
fireEvent.press(screen.getByText('Cancel Order'))
expect(await screen.findByPlaceholderText('Enter reason for cancellation...')).toBeVisible()
})
it('navigates to order details from View Details', async () => {
renderScreen()
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
await openOrderMenu()
fireEvent.press(screen.getByText('View Details'))
expect(routerMock.push).toHaveBeenCalledWith(
'/(drawer)/dashboard/manage-orders/order-details/21'
)
})
it('switches slots through the slot picker', async () => {
renderScreen()
await waitFor(() => expect(screen.getByText(LABEL_3)).toBeVisible())
fireEvent.press(screen.getByText(LABEL_3))
fireEvent.press(await screen.findByText(LABEL_4))
expect(routerMock.replace).toHaveBeenCalledWith(
'/(drawer)/dashboard/manage-orders/delivery-sequences?slotId=4'
)
})
it('opens a Google Maps link for orders with coordinates', async () => {
renderScreen({
'admin.order.getSlotOrders': {
success: true,
data: [slotOrder({ latitude: 16.75, longitude: 78.0 })],
},
})
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
const mapIcon = screen
.UNSAFE_getAllByType(MaterialIcons)
.find((node) => node.props.name === 'map')!
fireEvent.press(mapIcon)
expect(Linking.openURL).toHaveBeenCalledWith('https://www.google.com/maps?q=16.75,78')
})
it('goes back from the header', async () => {
renderScreen()
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
fireEvent.press(screen.getByLabelText('Go back'))
expect(routerMock.back).toHaveBeenCalled()
})
it('refetches orders and sequence after saving a reordered sequence', async () => {
const { fetchMock, view } = renderScreen({
'admin.order.getSlotOrders': {
success: true,
data: [slotOrder({ id: 21, readableId: 21 }), slotOrder({ id: 22, readableId: 22 })],
},
'admin.slots.getDeliverySequence': { deliverySequence: { '7': [21, 22] } },
})
// A real user must be selected: handleDragEnd/handleSaveSequence no-op for
// the Unassigned (-1) view.
await openUserDropdown()
fireEvent.press(screen.getByText('Ravi'))
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
const beforeOrders = procCount(fetchMock, 'admin.order.getSlotOrders')
const beforeSequence = procCount(fetchMock, 'admin.slots.getDeliverySequence')
// The mocked list renders its data but never drags by itself.
const list = view.UNSAFE_getByType(require('react-native-draggable-flatlist').default)
act(() => {
list.props.onDragEnd({ data: [list.props.data[1], list.props.data[0]] })
})
fireEvent.press(await screen.findByLabelText('Save sequence'))
// handleSaveSequence's onSuccess refetches both the slot orders and the
// delivery sequence.
await waitFor(() => {
expect(procCount(fetchMock, 'admin.order.getSlotOrders')).toBeGreaterThan(beforeOrders)
expect(procCount(fetchMock, 'admin.slots.getDeliverySequence')).toBeGreaterThan(beforeSequence)
})
})
it('refetches on mark-data-fetchers', async () => {
const { fetchMock } = renderScreen()
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
const before = procCount(fetchMock, 'admin.order.getSlotOrders')
refreshHooks.markDataFetchers?.()
await waitFor(() =>
expect(procCount(fetchMock, 'admin.order.getSlotOrders')).toBeGreaterThan(before)
)
})
})

View file

@ -0,0 +1,181 @@
/**
* Drawer layout (app/(drawer)/_layout.tsx) — auth gate, the custom drawer
* content (staff name, nav items, logout) and the header buttons.
*
* expo-router/drawer and @react-navigation/drawer are stubbed so the custom
* drawer content and the screenOptions header callbacks are reachable.
*/
const mockRedirects: string[] = []
jest.mock('expo-router', () => {
const React = require('react')
const { Text } = require('react-native')
const base = require('../mocks/router').expoRouterMock()
return {
...base,
Redirect: ({ href }: { href: string }) => {
mockRedirects.push(href)
return React.createElement(Text, { testID: 'redirect' }, String(href))
},
}
})
const mockNavigation = {
getState: () => ({ routes: [], index: 0 }),
openDrawer: jest.fn(),
}
jest.mock('expo-router/drawer', () => {
const React = require('react')
const { View } = require('react-native')
const Drawer = ({
drawerContent: DrawerContent,
screenOptions,
children,
}: {
drawerContent?: React.ComponentType
screenOptions?: (args: { navigation: unknown }) => Record<string, any>
children?: React.ReactNode
}) => {
const options =
typeof screenOptions === 'function'
? screenOptions({ navigation: mockNavigation })
: {}
return React.createElement(
View,
null,
options.headerLeft ? options.headerLeft() : null,
options.headerRight ? options.headerRight() : null,
DrawerContent ? React.createElement(DrawerContent) : null,
children
)
}
Drawer.Screen = () => null
return { Drawer }
})
jest.mock('@react-navigation/drawer', () => {
const React = require('react')
const { View, TouchableOpacity, Text } = require('react-native')
return {
DrawerContentScrollView: ({ children }: { children?: React.ReactNode }) =>
React.createElement(View, null, children),
DrawerItem: ({
label,
onPress,
}: {
label: string
onPress?: () => void
}) =>
React.createElement(
TouchableOpacity,
{ onPress, accessibilityLabel: label },
React.createElement(Text, null, label)
),
}
})
import React from 'react'
import { ActivityIndicator, DeviceEventEmitter } from 'react-native'
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import { fireEvent, screen } from '@testing-library/react-native'
import { REFRESH_EVENT } from 'common-ui/src/lib/const-strs'
import Layout from '@/app/(drawer)/_layout'
import { resetStorage, setupApiMocks } from '../mocks/api'
import { resetStaffAuthMock, staffAuthMock } from '../mocks/staff-auth'
import { resetRouterMock, routerMock } from '../mocks/router'
import { renderWithProviders } from '../helpers/render'
const iconByName = (name: string) =>
screen.UNSAFE_getAllByType(MaterialIcons).find((i) => i.props.name === name) as
| Parameters<typeof fireEvent.press>[0]
| undefined
describe('Drawer layout', () => {
beforeEach(async () => {
resetStaffAuthMock()
mockRedirects.length = 0
mockNavigation.openDrawer.mockClear()
resetRouterMock()
await resetStorage()
setupApiMocks()
jest.spyOn(DeviceEventEmitter, 'emit')
})
it('shows a spinner while the session is loading', () => {
staffAuthMock.isLoading = true
renderWithProviders(<Layout />)
expect(screen.UNSAFE_getByType(ActivityIndicator)).toBeTruthy()
expect(screen.queryByText('Logout')).toBeNull()
})
it('redirects to login when logged out', () => {
staffAuthMock.isLoggedIn = false
staffAuthMock.isLoading = false
renderWithProviders(<Layout />)
expect(screen.getByTestId('redirect')).toHaveTextContent('/login')
expect(mockRedirects).toEqual(['/login'])
})
it('renders the staff name and navigation items', () => {
renderWithProviders(<Layout />)
expect(screen.getByText('shafi')).toBeVisible()
expect(screen.getByText('Staff Member')).toBeVisible()
expect(screen.getByText('Dashboard')).toBeVisible()
expect(screen.getByText('Products')).toBeVisible()
expect(screen.getByText('Prices Overview')).toBeVisible()
expect(screen.getByText('Product Groupings')).toBeVisible()
expect(screen.getByText('Manage Orders')).toBeVisible()
expect(screen.getByText('User Management')).toBeVisible()
expect(screen.getByText('Send Notifications')).toBeVisible()
expect(screen.getByText('Logout')).toBeVisible()
})
it('navigates from a drawer item', () => {
renderWithProviders(<Layout />)
fireEvent.press(screen.getByText('Prices Overview'))
expect(routerMock.push).toHaveBeenCalledWith(
'/(drawer)/dashboard/prices-overview'
)
})
it('dismisses to the dashboard from the Dashboard item', () => {
renderWithProviders(<Layout />)
fireEvent.press(screen.getByText('Dashboard'))
expect(routerMock.dismissTo).toHaveBeenCalledWith('/(drawer)/dashboard')
})
it('logs out from the Logout item', () => {
renderWithProviders(<Layout />)
fireEvent.press(screen.getByText('Logout'))
expect(staffAuthMock.logout).toHaveBeenCalledTimes(1)
})
it('emits the refresh event from the header refresh button', () => {
renderWithProviders(<Layout />)
fireEvent.press(iconByName('refresh')!)
expect(DeviceEventEmitter.emit).toHaveBeenCalledWith(REFRESH_EVENT)
})
it('opens the drawer from the header menu button when there is no back stack', () => {
renderWithProviders(<Layout />)
fireEvent.press(iconByName('menu')!)
expect(mockNavigation.openDrawer).toHaveBeenCalledTimes(1)
expect(routerMock.back).not.toHaveBeenCalled()
})
})

View file

@ -0,0 +1,65 @@
/**
* Root entry (app/index.tsx) — loading spinner while auth resolves, then a
* Redirect to the dashboard or to /login depending on the staff session.
*/
const mockRedirects: string[] = []
jest.mock('expo-router', () => {
const React = require('react')
const { Text } = require('react-native')
const base = require('../mocks/router').expoRouterMock()
return {
...base,
Redirect: ({ href }: { href: string }) => {
mockRedirects.push(href)
return React.createElement(Text, { testID: 'redirect' }, String(href))
},
}
})
import React from 'react'
import { ActivityIndicator } from 'react-native'
import { screen } from '@testing-library/react-native'
import Index from '@/app/index'
import { resetStorage, setupApiMocks } from '../mocks/api'
import { resetStaffAuthMock, staffAuthMock } from '../mocks/staff-auth'
import { renderWithProviders } from '../helpers/render'
describe('Root index redirect', () => {
beforeEach(async () => {
resetStaffAuthMock()
mockRedirects.length = 0
await resetStorage()
setupApiMocks()
})
it('shows a spinner while the session is loading', () => {
staffAuthMock.isLoading = true
renderWithProviders(<Index />)
expect(screen.UNSAFE_getByType(ActivityIndicator)).toBeTruthy()
expect(screen.queryByTestId('redirect')).toBeNull()
})
it('redirects to the dashboard when logged in', () => {
staffAuthMock.isLoggedIn = true
staffAuthMock.isLoading = false
renderWithProviders(<Index />)
expect(screen.getByTestId('redirect')).toHaveTextContent(
'/(drawer)/dashboard'
)
expect(mockRedirects).toEqual(['/(drawer)/dashboard'])
})
it('redirects to login when logged out', () => {
staffAuthMock.isLoggedIn = false
staffAuthMock.isLoading = false
renderWithProviders(<Index />)
expect(screen.getByTestId('redirect')).toHaveTextContent('/login')
expect(mockRedirects).toEqual(['/login'])
})
})

View file

@ -0,0 +1,65 @@
/**
* Admin login screen (app/login.tsx) — validation and the staff-auth login call.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import LoginScreen from '@/app/login'
import { setupApiMocks } from '../mocks/api'
import { resetStaffAuthMock, staffAuthMock } from '../mocks/staff-auth'
import { renderWithProviders } from '../helpers/render'
describe('Admin login', () => {
beforeEach(() => {
resetStaffAuthMock()
setupApiMocks()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('renders the login form', () => {
renderWithProviders(<LoginScreen />)
expect(screen.getByText('Admin Login')).toBeVisible()
expect(screen.getByTestId('login-name-input')).toBeVisible()
expect(screen.getByTestId('login-password-input')).toBeVisible()
expect(screen.getByTestId('login-button')).toBeVisible()
})
it('rejects an empty name or password without calling login', () => {
renderWithProviders(<LoginScreen />)
fireEvent.press(screen.getByTestId('login-button'))
expect(Alert.alert).toHaveBeenCalledWith('Error', 'Please enter both name and password')
expect(staffAuthMock.login).not.toHaveBeenCalled()
})
it('trims the credentials and calls login', async () => {
renderWithProviders(<LoginScreen />)
fireEvent.changeText(screen.getByTestId('login-name-input'), ' shafi ')
fireEvent.changeText(screen.getByTestId('login-password-input'), 'secret')
fireEvent.press(screen.getByTestId('login-button'))
await waitFor(() => expect(staffAuthMock.login).toHaveBeenCalledWith('shafi', 'secret'))
})
it('shows the login error from the context', () => {
staffAuthMock.loginError = 'Invalid credentials'
renderWithProviders(<LoginScreen />)
expect(screen.getByText('Invalid credentials')).toBeVisible()
})
it('disables the button while logging in', () => {
staffAuthMock.isLoggingIn = true
renderWithProviders(<LoginScreen />)
expect(screen.getByText('Logging in...')).toBeVisible()
expect(screen.getByTestId('login-button')).toBeDisabled()
})
})

View file

@ -0,0 +1,127 @@
/**
* Manage Orders hub (app/(drawer)/dashboard/manage-orders/index.tsx) — slot
* picker plus navigation into Orders / Delivery Sequences.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import dayjs from 'dayjs'
import ManageOrders from '@/app/(drawer)/dashboard/manage-orders'
import { setupApiMocks, resetStorage } from '../mocks/api'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
import { refreshHooks, resetRefreshHooks } from '../mocks/refresh'
import { procCount } from '../mocks/procedures'
import { renderWithProviders } from '../helpers/render'
const SLOT = { id: 3, deliveryTime: '2026-01-01T10:00:00.000Z' }
const SLOT_LABEL = dayjs(SLOT.deliveryTime).format('ddd DD MMM, h:mm a')
const slotsResult = { slots: [SLOT], count: 1 }
describe('Manage Orders hub', () => {
beforeEach(async () => {
resetStaffAuthMock()
await resetStorage()
resetRouterMock()
resetRefreshHooks()
searchParamsMock.current = {}
setupApiMocks({ procedures: { 'admin.slots.getAll': slotsResult } })
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('renders the slot picker and both menu tiles', async () => {
renderWithProviders(<ManageOrders />)
await waitFor(() => expect(screen.getByText('Delivery Sequences')).toBeVisible())
expect(screen.getByText('Orders')).toBeVisible()
expect(screen.getByText('Select Slot')).toBeVisible()
})
it('loads the slot options into the dropdown', async () => {
renderWithProviders(<ManageOrders />)
await waitFor(() => expect(screen.getByText('Select Slot')).toBeVisible())
fireEvent.press(screen.getByText('Select Slot'))
expect(await screen.findByText('⚡ Flash Deliveries')).toBeVisible()
expect(await screen.findByText(SLOT_LABEL)).toBeVisible()
})
it('navigates to Orders without a filter when no slot is selected', async () => {
renderWithProviders(<ManageOrders />)
await waitFor(() => expect(screen.getByText('Orders')).toBeVisible())
fireEvent.press(screen.getByText('Orders'))
expect(routerMock.push).toHaveBeenCalledWith(
'/(drawer)/dashboard/manage-orders/orders'
)
})
it('navigates to Orders with filter=flash after picking flash deliveries', async () => {
renderWithProviders(<ManageOrders />)
await waitFor(() => expect(screen.getByText('Select Slot')).toBeVisible())
fireEvent.press(screen.getByText('Select Slot'))
fireEvent.press(await screen.findByText('⚡ Flash Deliveries'))
fireEvent.press(screen.getByText('Orders'))
expect(routerMock.push).toHaveBeenCalledWith(
'/(drawer)/dashboard/manage-orders/orders?filter=flash'
)
})
it('navigates to Delivery Sequences for the selected slot', async () => {
renderWithProviders(<ManageOrders />)
await waitFor(() => expect(screen.getByText('Select Slot')).toBeVisible())
fireEvent.press(screen.getByText('Select Slot'))
fireEvent.press(await screen.findByText(SLOT_LABEL))
fireEvent.press(screen.getByText('Delivery Sequences'))
expect(routerMock.push).toHaveBeenCalledWith(
'/(drawer)/dashboard/manage-orders/delivery-sequences?slotId=3'
)
})
it('warns that flash deliveries have no delivery sequences', async () => {
renderWithProviders(<ManageOrders />)
await waitFor(() => expect(screen.getByText('Select Slot')).toBeVisible())
fireEvent.press(screen.getByText('Select Slot'))
fireEvent.press(await screen.findByText('⚡ Flash Deliveries'))
fireEvent.press(screen.getByText('Delivery Sequences'))
expect(Alert.alert).toHaveBeenCalledWith(
'Flash Deliveries',
'Flash deliveries do not have delivery sequences. Use the Orders menu to manage flash deliveries.'
)
expect(routerMock.push).not.toHaveBeenCalled()
})
it('refetches slots when mark-data-fetchers fires', async () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.slots.getAll': slotsResult },
})
renderWithProviders(<ManageOrders />)
await waitFor(() => expect(screen.getByText('Orders')).toBeVisible())
expect(typeof refreshHooks.markDataFetchers).toBe('function')
act(() => {
refreshHooks.markDataFetchers?.()
})
await waitFor(() =>
expect(procCount(fetchMock, 'admin.slots.getAll')).toBeGreaterThanOrEqual(2)
)
})
})

View file

@ -0,0 +1,338 @@
/**
* Orders list (app/(drawer)/dashboard/manage-orders/orders/index.tsx) — rows,
* loading/empty/error, delivered toggle, item packaging, admin notes, filters,
* pagination and navigation.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert, FlatList } from 'react-native'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import Entypo from '@expo/vector-icons/Entypo'
import Orders from '@/app/(drawer)/dashboard/manage-orders/orders'
import { setupApiMocks, resetStorage } from '../mocks/api'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
import { lastProcedureInput, procCount } from '../mocks/procedures'
import { renderWithProviders } from '../helpers/render'
const makeOrder = (overrides: Record<string, unknown> = {}) => ({
id: 11,
orderId: '11',
readableId: 11,
customerName: 'Alice',
customerMobile: '9999999999',
address: '12 Main St, City, State - 500001, Phone: 9876543210',
addressId: 3,
latitude: null,
longitude: null,
totalAmount: 500,
deliveryCharge: 20,
items: [
{
id: 101,
name: 'Chicken',
quantity: 2,
price: 100,
amount: 200,
unit: 'kg',
skuName: 'Chicken',
features: [],
productSize: 1,
isPackaged: false,
isPackageVerified: false,
},
],
createdAt: '2026-01-01T10:00:00.000Z',
deliveryTime: null,
status: 'pending',
isPackaged: false,
isDelivered: false,
isCod: true,
isFlashDelivery: false,
userNotes: null,
adminNotes: 'call before delivery',
userNegativityScore: 0,
...overrides,
})
const mutateProcedures = {
'admin.order.updateDelivered': { success: true, userId: 1 },
'admin.order.updatePackaged': { success: true, userId: 1 },
'admin.order.updateOrderItemPackaging': { success: true, updated: true },
'admin.order.updateNotes': { id: 11 },
'admin.order.cancelOrder': { success: true, message: 'cancelled' },
}
const renderOrders = (procedures: Record<string, unknown> = {}) => {
const { fetchMock } = setupApiMocks({
procedures: {
'admin.slots.getAll': { slots: [], count: 0 },
'admin.order.getAll': { orders: [makeOrder()], nextCursor: null },
...procedures,
},
})
renderWithProviders(<Orders />)
return { fetchMock }
}
// Checkboxes render in tree order: row [Packaged, Delivered] then the filter
// dialog rows [Packaged, Not Packaged, Delivered, Not Delivered, Cancelled,
// Not Cancelled, ⚡ 1 Hr, Regular].
const checkboxAt = (index: number) => screen.getAllByRole('checkbox')[index]
const openFilter = () => {
const icon = screen
.UNSAFE_getAllByType(MaterialIcons)
.find((node) => node.props.name === 'filter-list')!
fireEvent.press(icon)
}
const FILTER_INDEX = {
packaged: 2,
notPackaged: 3,
delivered: 4,
notDelivered: 5,
cancelled: 6,
notCancelled: 7,
flash: 8,
regular: 9,
} as const
describe('Orders list', () => {
beforeEach(async () => {
resetStaffAuthMock()
await resetStorage()
resetRouterMock()
searchParamsMock.current = {}
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('shows a loading indicator while the list is pending', () => {
renderOrders()
expect(screen.getByText('Loading orders...')).toBeVisible()
})
it('renders a populated row', async () => {
renderOrders()
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
expect(screen.getByText('#11')).toBeVisible()
expect(screen.getByText('1 item')).toBeVisible()
expect(screen.getByText('₹500')).toBeVisible()
expect(screen.getByText('₹20')).toBeVisible()
expect(screen.getByText('Admin Notes')).toBeVisible()
})
it('renders an empty list when there are no orders', async () => {
renderOrders({ 'admin.order.getAll': { orders: [], nextCursor: null } })
await waitFor(() => expect(screen.queryByText('Loading orders...')).toBeNull())
expect(screen.queryByText('Alice')).toBeNull()
})
it('renders flash and cancelled order badges', async () => {
renderOrders({
'admin.order.getAll': {
orders: [
makeOrder({ isFlashDelivery: true, status: 'cancelled', readableId: 42, id: 42, orderId: '42' }),
],
nextCursor: null,
},
})
await waitFor(() => expect(screen.getByText('FLASH')).toBeVisible())
expect(screen.getByText('CANCELLED')).toBeVisible()
})
it('marks an order delivered from the row checkbox', async () => {
const { fetchMock } = renderOrders(mutateProcedures)
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
fireEvent.press(checkboxAt(1))
await waitFor(() => expect(lastProcedureInput(fetchMock, 'admin.order.updateDelivered')).toEqual({
orderId: '11',
isDelivered: true,
}))
})
it('does not toggle packaged from the (inert) inline row checkbox', async () => {
const { fetchMock } = renderOrders(mutateProcedures)
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
fireEvent.press(checkboxAt(0))
expect(procCount(fetchMock, 'admin.order.updatePackaged')).toBe(0)
})
it('updates per-item packaging from the items dialog', async () => {
const { fetchMock } = renderOrders(mutateProcedures)
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
fireEvent.press(screen.getByText('1 item'))
fireEvent.press(checkboxAt(2))
await waitFor(() =>
expect(lastProcedureInput(fetchMock, 'admin.order.updateOrderItemPackaging')).toEqual({
orderItemId: 101,
isPackaged: true,
})
)
})
it('applies the packaged filter to the query input', async () => {
const { fetchMock } = renderOrders(mutateProcedures)
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
openFilter()
fireEvent.press(checkboxAt(FILTER_INDEX.packaged))
await waitFor(() => {
const input = lastProcedureInput(fetchMock, 'admin.order.getAll') as Record<string, unknown>
expect(input.packagedFilter).toBe('packaged')
})
})
it('applies the delivered and cancellation filters', async () => {
const { fetchMock } = renderOrders(mutateProcedures)
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
openFilter()
fireEvent.press(checkboxAt(FILTER_INDEX.delivered))
await waitFor(() => {
const input = lastProcedureInput(fetchMock, 'admin.order.getAll') as Record<string, unknown>
expect(input.deliveredFilter).toBe('delivered')
})
})
it('applies the flash delivery type filter', async () => {
const { fetchMock } = renderOrders(mutateProcedures)
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
openFilter()
fireEvent.press(checkboxAt(FILTER_INDEX.flash))
await waitFor(() => {
const input = lastProcedureInput(fetchMock, 'admin.order.getAll') as Record<string, unknown>
expect(input.flashDeliveryFilter).toBe('flash')
})
})
it('saves admin notes through the notes dialog', async () => {
const { fetchMock } = renderOrders(mutateProcedures)
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
fireEvent.press(screen.getByText('Admin Notes'))
fireEvent.changeText(
screen.getByPlaceholderText('Enter admin notes...'),
'leave at gate'
)
fireEvent.press(screen.getByText('Save'))
await waitFor(() =>
expect(lastProcedureInput(fetchMock, 'admin.order.updateNotes')).toEqual({
orderId: 11,
adminNotes: 'leave at gate',
})
)
})
it('opens the user notes dialog', async () => {
renderOrders({
'admin.order.getAll': {
orders: [makeOrder({ userNotes: 'ring the bell' })],
nextCursor: null,
},
})
await waitFor(() => expect(screen.getByText('User Notes')).toBeVisible())
fireEvent.press(screen.getByText('User Notes'))
expect(await screen.findByText('ring the bell')).toBeVisible()
})
it('navigates to order details when a row is pressed', async () => {
renderOrders()
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
fireEvent.press(screen.getByText('Alice'))
expect(routerMock.push).toHaveBeenCalledWith(
'/(drawer)/dashboard/manage-orders/order-details/11'
)
})
it('opens the options menu and navigates via View Details', async () => {
renderOrders()
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
const dots = screen.UNSAFE_getAllByType(Entypo)[0]
fireEvent.press(dots)
expect(await screen.findByText('Select an action to perform')).toBeVisible()
fireEvent.press(screen.getByText('View Details'))
expect(routerMock.push).toHaveBeenCalledWith(
'/(drawer)/dashboard/manage-orders/order-details/11'
)
})
it('opens the cancel dialog from the options menu', async () => {
renderOrders()
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
fireEvent.press(screen.UNSAFE_getAllByType(Entypo)[0])
fireEvent.press(await screen.findByText('Cancel Order'))
expect(await screen.findByPlaceholderText('Enter reason for cancellation...')).toBeVisible()
})
it('loads the next page when the list end is reached', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'admin.slots.getAll': { slots: [], count: 0 },
'admin.order.getAll': (input: unknown) => {
const cursor = (input as { cursor?: number } | undefined)?.cursor
if (cursor) {
return {
orders: [makeOrder({ id: 5, orderId: '5', readableId: 5, customerName: 'Fish Order' })],
nextCursor: null,
}
}
return { orders: [makeOrder()], nextCursor: 5 }
},
},
})
renderWithProviders(<Orders />)
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
fireEvent(screen.UNSAFE_getByType(FlatList), 'endReached')
await waitFor(() => expect(screen.getByText('Fish Order')).toBeVisible())
const input = lastProcedureInput(fetchMock, 'admin.order.getAll') as Record<string, unknown>
expect(input.cursor).toBe(5)
})
it('falls back to an empty list when the query fails', async () => {
setupApiMocks({
procedures: {
'admin.slots.getAll': { slots: [], count: 0 },
'admin.order.getAll': () => {
throw new Error('boom')
},
},
})
renderWithProviders(<Orders />)
await waitFor(() => expect(screen.queryByText('Loading orders...')).toBeNull())
expect(screen.queryByText('Alice')).toBeNull()
})
})

View file

@ -0,0 +1,278 @@
/**
* Order details (app/(drawer)/dashboard/manage-orders/order-details/[id].tsx) —
* detail rendering, packaging toggles, delivery-charge removal, cancellation
* and navigation.
*
* NOTE: the "Initiate Refund" / "Generate Refund Coupon" action block is
* commented out in the source (lines ~697-769) and the state setters that open
* those dialogs are never invoked, so those two mutations are not reachable
* through the UI and cannot be integration-tested.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import OrderDetails from '@/app/(drawer)/dashboard/manage-orders/order-details/[id]'
import { setupApiMocks, resetStorage } from '../mocks/api'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures'
import { renderWithProviders } from '../helpers/render'
const makeDetails = (overrides: Record<string, unknown> = {}) => ({
id: 11,
readableId: 11,
userId: 5,
customerName: 'Alice',
customerEmail: 'alice@example.com',
customerMobile: '9999999999',
address: {
name: 'Alice',
line1: '12 Main St',
line2: null,
city: 'City',
state: 'State',
pincode: '500001',
phone: '9876543210',
},
slotInfo: { time: '2026-01-02T10:00:00.000Z', sequence: null },
isCod: false,
isOnlinePayment: true,
totalAmount: 500,
deliveryCharge: 20,
adminNotes: 'handle with care',
userNotes: null,
createdAt: '2026-01-01T10:00:00.000Z',
status: 'pending',
isPackaged: false,
isDelivered: false,
items: [
{
id: 101,
name: 'Chicken',
amount: 200,
isPackaged: false,
isPackageVerified: false,
quantity: '2',
price: '100',
productSize: 1,
unit: 'kg',
},
],
payment: null,
paymentInfo: null,
cancelReason: null,
cancellationReviewed: false,
isRefundDone: false,
refundStatus: null,
refundAmount: null,
couponData: null,
couponCode: null,
couponDescription: null,
discountAmount: 0,
orderStatus: null,
refundRecord: null,
isFlashDelivery: false,
...overrides,
})
const procedures = (overrides: Record<string, unknown> = {}) => ({
'admin.order.getOrderDetails': makeDetails(),
'admin.order.updateOrderItemPackaging': { success: true, updated: true },
'admin.order.removeDeliveryCharge': { message: 'removed' },
'admin.order.cancelOrder': { success: true, message: 'cancelled' },
'admin.user.getUserIncidents': { incidents: [] },
...overrides,
})
const renderDetails = (overrides: Record<string, unknown> = {}) => {
const { fetchMock } = setupApiMocks({ procedures: procedures(overrides) })
renderWithProviders(<OrderDetails />)
return { fetchMock }
}
describe('Order details', () => {
beforeEach(async () => {
resetStaffAuthMock()
await resetStorage()
resetRouterMock()
searchParamsMock.current = { id: '11' }
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('shows a loading message while the order is pending', () => {
renderDetails()
expect(screen.getByText('Loading order details...')).toBeVisible()
})
it('queries the order with the route id', async () => {
const { fetchMock } = renderDetails()
await waitFor(() => expect(screen.getByText('#11')).toBeVisible())
expect(lastProcedureInput(fetchMock, 'admin.order.getOrderDetails')).toEqual({ orderId: 11 })
})
it('renders the order, customer, items and totals', async () => {
renderDetails()
await waitFor(() => expect(screen.getByText('#11')).toBeVisible())
expect(screen.getByText('Alice')).toBeVisible()
expect(screen.getByText('9999999999')).toBeVisible()
expect(screen.getByText('Chicken')).toBeVisible()
expect(screen.getByText('Subtotal (1 items)')).toBeVisible()
expect(screen.getByText('handle with care')).toBeVisible()
expect(screen.getByText('Manage Orders')).toBeVisible()
})
it('renders an error state with a back action when the order is missing', async () => {
renderDetails({ 'admin.order.getOrderDetails': null })
await waitFor(() => expect(screen.getByText('Oops!')).toBeVisible())
expect(screen.getByText('Failed to load order details')).toBeVisible()
fireEvent.press(screen.getByText('Go Back'))
expect(routerMock.back).toHaveBeenCalled()
})
it('toggles item packaged state', async () => {
const { fetchMock } = renderDetails()
await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible())
fireEvent.press(screen.getAllByText('Packaged').pop()!)
await waitFor(() =>
expect(lastProcedureInput(fetchMock, 'admin.order.updateOrderItemPackaging')).toEqual({
orderItemId: 101,
isPackaged: true,
})
)
})
it('toggles item verified state', async () => {
const { fetchMock } = renderDetails()
await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible())
fireEvent.press(screen.getByText('Pkg Verified'))
await waitFor(() =>
expect(lastProcedureInput(fetchMock, 'admin.order.updateOrderItemPackaging')).toEqual({
orderItemId: 101,
isPackageVerified: true,
})
)
})
it('removes the delivery charge after confirmation', async () => {
const { fetchMock } = renderDetails()
await waitFor(() => expect(screen.getByText('Remove')).toBeVisible())
fireEvent.press(screen.getByText('Remove'))
const call = (Alert.alert as jest.Mock).mock.calls.find((c) => c[0] === 'Remove Delivery Cost')
expect(call).toBeTruthy()
const buttons = call![2] as { text: string; onPress?: () => void }[]
await act(async () => {
buttons.find((b) => b.text === 'Remove')!.onPress?.()
})
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.order.removeDeliveryCharge'))
expect(lastProcedureInput(fetchMock, 'admin.order.removeDeliveryCharge')).toEqual({ orderId: 11 })
})
it('opens the cancel order dialog', async () => {
renderDetails()
await waitFor(() => expect(screen.getByText('Cancel Order')).toBeVisible())
fireEvent.press(screen.getByText('Cancel Order'))
expect(await screen.findByPlaceholderText('Enter reason for cancellation...')).toBeVisible()
})
it('renders the cancellation reason and hides the cancel button when cancelled', async () => {
renderDetails({
'admin.order.getOrderDetails': makeDetails({
status: 'cancelled',
cancelReason: 'Customer requested',
}),
})
await waitFor(() => expect(screen.getByText('Cancellation Reason')).toBeVisible())
expect(screen.getByText('Customer requested')).toBeVisible()
expect(screen.queryByText('Cancel Order')).toBeNull()
})
it('renders the flash delivery notice', async () => {
renderDetails({
'admin.order.getOrderDetails': makeDetails({ isFlashDelivery: true }),
})
await waitFor(() => expect(screen.getByText('1 Hr Delivery Order')).toBeVisible())
expect(screen.getByText(/high-priority flash delivery order/)).toBeVisible()
})
it('renders the applied coupon block', async () => {
renderDetails({
'admin.order.getOrderDetails': makeDetails({
couponCode: 'SAVE50',
couponDescription: 'Flat ₹50 off',
discountAmount: 50,
}),
})
await waitFor(() => expect(screen.getByText('Coupon Applied')).toBeVisible())
expect(screen.getByText('SAVE50')).toBeVisible()
expect(screen.getAllByText('-₹50').length).toBeGreaterThan(0)
})
it('renders the refund coupon block when one exists', async () => {
renderDetails({
'admin.order.getOrderDetails': makeDetails({
couponCode: 'REF10',
couponData: { couponCode: 'REF10', couponDescription: '', discountAmount: 100 },
orderStatus: {
id: 1,
orderTime: '2026-01-01T10:00:00.000Z',
userId: 5,
orderId: 11,
isPackaged: false,
isDelivered: false,
isCancelled: true,
cancelReason: 'x',
isCancelledByAdmin: true,
paymentStatus: 'success',
cancellationUserNotes: null,
cancellationAdminNotes: null,
cancellationReviewed: false,
cancellationReviewedAt: null,
refundCouponId: 9,
},
}),
})
await waitFor(() => expect(screen.getByText('Refund Coupon')).toBeVisible())
expect(screen.getByText('₹100')).toBeVisible()
})
it('navigates to user management from customer details', async () => {
renderDetails()
await waitFor(() => expect(screen.getByText('Customer Details')).toBeVisible())
fireEvent.press(screen.getByText('Customer Details'))
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/user-management/5')
})
it('navigates back to Manage Orders from the bottom bar', async () => {
renderDetails()
await waitFor(() => expect(screen.getByText('Manage Orders')).toBeVisible())
fireEvent.press(screen.getByText('Manage Orders'))
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/manage-orders')
})
})

View file

@ -0,0 +1,319 @@
/**
* Prices overview (app/(drawer)/dashboard/prices-overview/index.tsx) — SKU
* price grid, store filter, edit-dialog validation, flash toggle, the
* updateProductPrices mutation and navigation to rebalance orders.
*
* NOTE: the screen collects SKUs but sends `productId: sku.id`. The backend
* (admin-apis/product.ts:436 + db_helper_postgres updateProductPrices:410)
* treats `productId` as a productInfo id, so this is asserted as-is and
* reported as an app bug.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import { Entypo } from '@expo/vector-icons'
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import PricesOverview from '@/app/(drawer)/dashboard/prices-overview/index'
import { resetStorage, setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { routerMock } from '../mocks/router'
import { renderWithProviders } from '../helpers/render'
const chickenSku = {
id: 11,
productId: 1,
name: 'Chicken 1kg',
displayName: '1 kg pack',
price: '100',
marketPrice: '120',
flashPrice: '90',
isFlashAvailable: false,
images: ['https://cdn.freshyo.in/chicken.jpg'],
features: [{ featureValue: '1kg' }],
}
const muttonSku = {
id: 22,
productId: 2,
name: 'Mutton 1kg',
displayName: '1 kg pack',
price: '200',
marketPrice: null,
flashPrice: null,
isFlashAvailable: false,
images: [],
features: [],
}
const product = (id: number, name: string, storeId: number, skus: unknown[]) => ({
id,
name,
shortDescription: null,
longDescription: null,
storeId,
incrementStep: 1,
productType: 'item',
store: null,
skus,
})
const productsResponse = {
products: [
product(1, 'Chicken', 1, [chickenSku]),
product(2, 'Mutton', 2, [muttonSku]),
],
count: 2,
}
const storesResponse = {
stores: [
{ id: 1, name: 'Main Store' },
{ id: 2, name: 'Other Store' },
],
count: 2,
}
const baseProcedures = {
'admin.product.getProducts': productsResponse,
'admin.store.getStores': storesResponse,
'admin.product.updateProductPrices': {
message: 'Updated prices for 1 product(s)',
updatedCount: 1,
},
}
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 }[]
buttons.find((b) => b.text === label)?.onPress?.()
}
const editIcon = () =>
screen.UNSAFE_getAllByType(MaterialIcons).find((i) => i.props.name === 'edit') as
| Parameters<typeof fireEvent.press>[0]
| undefined
const openEditDialog = () => {
fireEvent.press(editIcon()!)
}
describe('Prices overview', () => {
beforeEach(async () => {
resetStaffAuthMock()
await resetStorage()
routerMock.push.mockClear()
setupApiMocks({ procedures: baseProcedures })
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('shows a loading state while products or stores are pending', () => {
setupApiMocks({
procedures: {
'admin.product.getProducts': () => new Promise(() => {}),
'admin.store.getStores': () => new Promise(() => {}),
},
})
renderWithProviders(<PricesOverview />)
expect(screen.getByText('Loading...')).toBeVisible()
})
it('renders the SKU price grid', async () => {
renderWithProviders(<PricesOverview />)
expect(await screen.findByText('Chicken')).toBeVisible()
expect(screen.getByText('Mutton')).toBeVisible()
expect(screen.getByText('₹100')).toBeVisible()
expect(screen.getByText('₹120')).toBeVisible()
expect(screen.getByText('₹90')).toBeVisible()
expect(screen.getByText('1kg')).toBeVisible()
// Mutton has no market/flash price.
expect(screen.getAllByText('N/A')).toHaveLength(2)
expect(screen.getByText('Save (0)')).toBeVisible()
})
it('renders without rows when there are no products', async () => {
setupApiMocks({
procedures: {
...baseProcedures,
'admin.product.getProducts': { products: [], count: 0 },
},
})
renderWithProviders(<PricesOverview />)
await waitFor(() => expect(screen.getByText('Save (0)')).toBeVisible())
expect(screen.queryByText('Chicken')).toBeNull()
})
it('filters SKUs by store', async () => {
renderWithProviders(<PricesOverview />)
await screen.findByText('Chicken')
fireEvent.press(screen.getByText('Main Store, Other Store'))
fireEvent.press(await screen.findByText('Main Store'))
fireEvent.press(screen.getByText('Done'))
await waitFor(() => expect(screen.queryByText('Chicken')).toBeNull())
expect(screen.getByText('Mutton')).toBeVisible()
})
it('rejects an invalid price in the edit dialog', async () => {
renderWithProviders(<PricesOverview />)
await screen.findByText('Chicken')
openEditDialog()
fireEvent.changeText(screen.getByPlaceholderText('Enter price'), '0')
fireEvent.press(screen.getByText('Update Price'))
expect(Alert.alert).toHaveBeenCalledWith('Error', 'Please enter a valid price')
expect(screen.getByText('Save (0)')).toBeVisible()
})
it('rejects an invalid market price in the edit dialog', async () => {
renderWithProviders(<PricesOverview />)
await screen.findByText('Chicken')
openEditDialog()
fireEvent.changeText(screen.getByPlaceholderText('Enter price'), '150')
fireEvent.changeText(screen.getByPlaceholderText('Enter market price'), '0')
fireEvent.press(screen.getByText('Update Price'))
expect(Alert.alert).toHaveBeenCalledWith(
'Error',
'Please enter a valid market price'
)
})
it('rejects an invalid flash price in the edit dialog', async () => {
renderWithProviders(<PricesOverview />)
await screen.findByText('Chicken')
openEditDialog()
fireEvent.changeText(screen.getByPlaceholderText('Enter price'), '150')
fireEvent.changeText(screen.getByPlaceholderText('Enter flash price'), '0')
fireEvent.press(screen.getByText('Update Price'))
expect(Alert.alert).toHaveBeenCalledWith(
'Error',
'Please enter a valid flash price'
)
})
it('saves an edited price through updateProductPrices', async () => {
const { fetchMock } = setupApiMocks({ procedures: baseProcedures })
renderWithProviders(<PricesOverview />)
await screen.findByText('Chicken')
openEditDialog()
fireEvent.changeText(screen.getByPlaceholderText('Enter price'), '150')
fireEvent.press(screen.getByText('Update Price'))
expect(screen.getByText('Save (1)')).toBeVisible()
fireEvent.press(screen.getByText('Save (1)'))
await waitFor(() =>
expectProcedureCalled(fetchMock, 'admin.product.updateProductPrices')
)
// BUG: productId is the SKU id (11), but the backend expects the product id.
expect(lastProcedureInput(fetchMock, 'admin.product.updateProductPrices')).toEqual({
updates: [{ productId: 11, price: 150 }],
})
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Prices updated successfully')
)
await waitFor(() =>
expect(procCount(fetchMock, 'admin.product.getProducts')).toBeGreaterThan(1)
)
})
it('saves the flash-availability toggle through updateProductPrices', async () => {
const { fetchMock } = setupApiMocks({ procedures: baseProcedures })
renderWithProviders(<PricesOverview />)
await screen.findByText('Chicken')
fireEvent.press(screen.getAllByRole('checkbox')[0])
expect(screen.getByText('Save (1)')).toBeVisible()
fireEvent.press(screen.getByText('Save (1)'))
await waitFor(() =>
expectProcedureCalled(fetchMock, 'admin.product.updateProductPrices')
)
expect(lastProcedureInput(fetchMock, 'admin.product.updateProductPrices')).toEqual({
updates: [{ productId: 11, isFlashAvailable: true }],
})
})
it('shows an error alert when the update fails', async () => {
setupApiMocks({
procedures: {
...baseProcedures,
'admin.product.updateProductPrices': () => {
throw new Error('boom')
},
},
})
renderWithProviders(<PricesOverview />)
await screen.findByText('Chicken')
openEditDialog()
fireEvent.changeText(screen.getByPlaceholderText('Enter price'), '150')
fireEvent.press(screen.getByText('Update Price'))
fireEvent.press(screen.getByText('Save (1)'))
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Error',
expect.stringContaining('Failed to update prices')
)
)
})
it('does not submit while no change was made', async () => {
const { fetchMock } = setupApiMocks({ procedures: baseProcedures })
renderWithProviders(<PricesOverview />)
await screen.findByText('Chicken')
fireEvent.press(screen.getByText('Save (0)'))
expect(procCount(fetchMock, 'admin.product.updateProductPrices')).toBe(0)
})
it('navigates to rebalance orders from the options menu', async () => {
renderWithProviders(<PricesOverview />)
await screen.findByText('Chicken')
const dots = screen.UNSAFE_getAllByType(Entypo)[0]
fireEvent.press(dots)
fireEvent.press(await screen.findByText('Re-Balance Orders'))
expect(routerMock.push).toHaveBeenCalledWith(
'/(drawer)/dashboard/rebalance-orders'
)
})
it('acknowledges the success alert', async () => {
renderWithProviders(<PricesOverview />)
await screen.findByText('Chicken')
openEditDialog()
fireEvent.changeText(screen.getByPlaceholderText('Enter price'), '150')
fireEvent.press(screen.getByText('Update Price'))
fireEvent.press(screen.getByText('Save (1)'))
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Prices updated successfully')
)
pressLastAlertButton('OK')
expect(routerMock.push).not.toHaveBeenCalled()
})
})

View file

@ -0,0 +1,74 @@
/**
* Create product group (app/(drawer)/dashboard/product-groupings/create.tsx) —
* renders ProductGroupForm in create mode and wires onClose/onSuccess to
* router.back().
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import CreateProductGroup from '@/app/(drawer)/dashboard/product-groupings/create'
import { resetStorage, setupApiMocks } from '../mocks/api'
import { expectProcedureCalled, procCount } from '../mocks/procedures'
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
import { renderWithProviders } from '../helpers/render'
const procedures = {
'common.product.getAllProductsSummary': { products: [] },
'common.product.getAllSkusSummary': {
skus: [{ id: 1, productId: 10, productName: 'Chicken', label: 'Chicken 1kg' }],
},
'admin.product.createGroup': {
group: { id: 1, groupName: 'Meat', description: null, createdAt: '2024-01-01' },
message: 'Group created successfully',
},
}
describe('Create product group', () => {
beforeEach(async () => {
await resetStorage()
resetRouterMock()
searchParamsMock.current = {}
setupApiMocks({ procedures })
jest.spyOn(console, 'error').mockImplementation(() => {})
})
it('renders the create form', () => {
renderWithProviders(<CreateProductGroup />)
expect(screen.getByText('Create Product Group')).toBeVisible()
expect(screen.getByPlaceholderText('Enter group name')).toBeVisible()
expect(screen.getByText('Save')).toBeVisible()
})
it('does not create a group when the name is empty', async () => {
const { fetchMock } = setupApiMocks({ procedures })
renderWithProviders(<CreateProductGroup />)
fireEvent.press(screen.getByText('Save'))
expect(await screen.findByText('Group name is required')).toBeVisible()
expect(procCount(fetchMock, 'admin.product.createGroup')).toBe(0)
})
it('creates the group then navigates back', async () => {
const { fetchMock } = setupApiMocks({ procedures })
renderWithProviders(<CreateProductGroup />)
fireEvent.changeText(screen.getByPlaceholderText('Enter group name'), 'Meat')
fireEvent.press(screen.getByText('Save'))
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.product.createGroup'))
await waitFor(() => expect(routerMock.back).toHaveBeenCalled())
})
it('navigates back when cancelled', () => {
renderWithProviders(<CreateProductGroup />)
fireEvent.press(screen.getByText('Cancel'))
expect(routerMock.back).toHaveBeenCalled()
})
})

View file

@ -0,0 +1,98 @@
/**
* Edit product group (app/(drawer)/dashboard/product-groupings/edit/[id].tsx) —
* loads getGroups, finds the group by the route id, and wires the form to
* updateGroup() + router.back().
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import EditProductGroup from '@/app/(drawer)/dashboard/product-groupings/edit/[id]'
import { resetStorage, setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
} from '../mocks/procedures'
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
import { renderWithProviders } from '../helpers/render'
const group = (overrides: Record<string, unknown> = {}) => ({
id: 5,
groupName: 'Beef Box',
description: 'Bundle',
createdAt: '2024-01-01T00:00:00.000Z',
products: [{ id: 10 }, { id: 11 }],
productCount: 2,
...overrides,
})
const procedures = (groups: unknown[]) => ({
'admin.product.getGroups': { groups },
'common.product.getAllProductsSummary': { products: [] },
'common.product.getAllSkusSummary': {
skus: [
{ id: 1, productId: 10, productName: 'Chicken', label: 'Chicken 1kg' },
{ id: 2, productId: 11, productName: 'Mutton', label: 'Mutton 1kg' },
],
},
'admin.product.updateGroup': {
group: { id: 5, groupName: 'Beef Combo', description: 'Bundle', createdAt: '2024-01-01' },
message: 'Group updated successfully',
},
})
describe('Edit product group', () => {
beforeEach(async () => {
await resetStorage()
resetRouterMock()
searchParamsMock.current = { id: '5' }
setupApiMocks({ procedures: procedures([group()]) })
jest.spyOn(console, 'error').mockImplementation(() => {})
})
it('shows the loading state while groups are pending', () => {
searchParamsMock.current = { id: '5' }
setupApiMocks({
procedures: { ...procedures([group()]), 'admin.product.getGroups': () => new Promise(() => {}) },
})
renderWithProviders(<EditProductGroup />)
expect(screen.getByText('Loading group...')).toBeVisible()
})
it('shows a not-found state when the id does not match a group', async () => {
searchParamsMock.current = { id: '99' }
setupApiMocks({ procedures: procedures([group()]) })
renderWithProviders(<EditProductGroup />)
expect(await screen.findByText('Group not found')).toBeVisible()
})
it('renders the edit form seeded with the group', async () => {
renderWithProviders(<EditProductGroup />)
expect(await screen.findByText('Edit Product Group')).toBeVisible()
expect(screen.getByDisplayValue('Beef Box')).toBeVisible()
expect(screen.getByDisplayValue('Bundle')).toBeVisible()
})
it('updates the group and navigates back', async () => {
const { fetchMock } = setupApiMocks({ procedures: procedures([group()]) })
renderWithProviders(<EditProductGroup />)
await screen.findByDisplayValue('Beef Box')
fireEvent.changeText(screen.getByDisplayValue('Beef Box'), 'Beef Combo')
fireEvent.press(screen.getByText('Save'))
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],
})
await waitFor(() => expect(routerMock.back).toHaveBeenCalled())
})
})

View file

@ -0,0 +1,201 @@
/**
* Product groupings list (app/(drawer)/dashboard/product-groupings/index.tsx) —
* group rows, empty/loading/error states, create/edit navigation, delete via
* the confirm alert and the manual-refresh hooks.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import dayjs from 'dayjs'
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import ProductGroupings from '@/app/(drawer)/dashboard/product-groupings/index'
import { resetStorage, setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
import { refreshHooks, resetRefreshHooks } from '../mocks/refresh'
import { renderWithProviders } from '../helpers/render'
const group = (overrides: Record<string, unknown> = {}) => ({
id: 1,
groupName: 'Meat Box',
description: 'Protein bundle',
createdAt: '2024-05-01T00:00:00.000Z',
products: [{ id: 10 }, { id: 11 }],
productCount: 2,
...overrides,
})
const groupsResponse = (groups: unknown[]) => ({ groups })
const iconByName = (name: string) =>
screen.UNSAFE_getAllByType(MaterialIcons).find((i) => i.props.name === name) as
| Parameters<typeof fireEvent.press>[0]
| undefined
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('Product groupings list', () => {
beforeEach(async () => {
resetStaffAuthMock()
await resetStorage()
resetRouterMock()
resetRefreshHooks()
searchParamsMock.current = {}
setupApiMocks({ procedures: { 'admin.product.getGroups': groupsResponse([group()]) } })
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('shows the loading state', () => {
setupApiMocks({
procedures: { 'admin.product.getGroups': () => new Promise(() => {}) },
})
renderWithProviders(<ProductGroupings />)
expect(screen.getByText('Loading product groups...')).toBeVisible()
})
it('shows the error state when the query fails', async () => {
const { fetchMock } = setupApiMocks()
fetchMock.mockRejectedValue(new Error('network down'))
renderWithProviders(<ProductGroupings />)
expect(await screen.findByText('Error loading groups')).toBeVisible()
})
it('shows the empty state', async () => {
setupApiMocks({
procedures: { 'admin.product.getGroups': groupsResponse([]) },
})
renderWithProviders(<ProductGroupings />)
expect(await screen.findByText('No Groups Yet')).toBeVisible()
expect(
screen.getByText('Start by creating your first product group using the button below.')
).toBeVisible()
})
it('renders a group row with description, product count and date', async () => {
setupApiMocks({
procedures: {
'admin.product.getGroups': groupsResponse([
group(),
group({ id: 2, groupName: 'Fish Box', description: null, productCount: 1 }),
]),
},
})
renderWithProviders(<ProductGroupings />)
expect(await screen.findByText('Meat Box')).toBeVisible()
expect(screen.getByText('Protein bundle')).toBeVisible()
expect(screen.getByText('2 Products')).toBeVisible()
expect(screen.getByText('Fish Box')).toBeVisible()
expect(screen.getByText('1 Products')).toBeVisible()
expect(
screen.getAllByText(dayjs('2024-05-01T00:00:00.000Z').format('MMM DD, YYYY'))
).toHaveLength(2)
})
it('navigates to create from the floating action button', async () => {
renderWithProviders(<ProductGroupings />)
await screen.findByText('Meat Box')
fireEvent.press(iconByName('add')!)
expect(routerMock.push).toHaveBeenCalledWith(
'/(drawer)/dashboard/product-groupings/create'
)
})
it('navigates to edit for the pressed group', async () => {
renderWithProviders(<ProductGroupings />)
await screen.findByText('Meat Box')
fireEvent.press(iconByName('edit')!)
expect(routerMock.push).toHaveBeenCalledWith(
'/(drawer)/dashboard/product-groupings/edit/1'
)
})
it('deletes a group after confirming the alert and refetches', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'admin.product.getGroups': groupsResponse([group()]),
'admin.product.deleteGroup': { message: 'Group deleted successfully' },
},
})
renderWithProviders(<ProductGroupings />)
await screen.findByText('Meat Box')
fireEvent.press(iconByName('delete')!)
expect(Alert.alert).toHaveBeenCalledWith(
'Delete Group',
'Are you sure you want to delete this group?',
expect.any(Array)
)
pressLastAlertButton('Delete')
await waitFor(() =>
expectProcedureCalled(fetchMock, 'admin.product.deleteGroup')
)
expect(lastProcedureInput(fetchMock, 'admin.product.deleteGroup')).toEqual({
id: 1,
})
await waitFor(() =>
expect(procCount(fetchMock, 'admin.product.getGroups')).toBeGreaterThan(1)
)
})
it('does not delete when the alert is cancelled', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'admin.product.getGroups': groupsResponse([group()]),
'admin.product.deleteGroup': { message: 'Group deleted successfully' },
},
})
renderWithProviders(<ProductGroupings />)
await screen.findByText('Meat Box')
fireEvent.press(iconByName('delete')!)
pressLastAlertButton('Cancel')
expect(procCount(fetchMock, 'admin.product.deleteGroup')).toBe(0)
})
it('refetches through the manual-refresh and mark-data-fetchers hooks', async () => {
const { fetchMock } = setupApiMocks({
procedures: { 'admin.product.getGroups': groupsResponse([group()]) },
})
renderWithProviders(<ProductGroupings />)
await screen.findByText('Meat Box')
const before = procCount(fetchMock, 'admin.product.getGroups')
expect(refreshHooks.manualRefresh).toBeTruthy()
refreshHooks.manualRefresh?.()
await waitFor(() =>
expect(procCount(fetchMock, 'admin.product.getGroups')).toBeGreaterThan(before)
)
const afterManual = procCount(fetchMock, 'admin.product.getGroups')
expect(refreshHooks.markDataFetchers).toBeTruthy()
refreshHooks.markDataFetchers?.()
await waitFor(() =>
expect(procCount(fetchMock, 'admin.product.getGroups')).toBeGreaterThan(afterManual)
)
})
})

View file

@ -0,0 +1,125 @@
/**
* Add product tag (app/(drawer)/dashboard/product-tags/add.tsx) — creates a tag
* (with optional image upload) then navigates back on success.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import AddTag from '@/app/(drawer)/dashboard/product-tags/add'
import { resetStorage, setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { routerMock } from '../mocks/router'
import { renderWithProviders } from '../helpers/render'
const storesResponse = {
stores: [{ id: 1, name: 'Main Store' }],
count: 1,
}
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('Add product tag', () => {
beforeEach(async () => {
await resetStorage()
setupApiMocks()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('renders the create form', () => {
setupApiMocks({
procedures: {
'admin.store.getStores': storesResponse,
'common.product.getAllSkusSummary': { skus: [] },
},
})
renderWithProviders(<AddTag />)
expect(screen.getByText('Create Tag')).toBeVisible()
})
it('creates the tag with the entered values', async () => {
const api = setupApiMocks({
procedures: {
'admin.store.getStores': storesResponse,
'common.product.getAllSkusSummary': { skus: [] },
'admin.product.createProductTag': {
tag: { id: 3, tagName: 'Featured' },
message: 'Tag created successfully',
},
'admin.product.getProductTags': { tags: [], message: 'ok' },
},
})
renderWithProviders(<AddTag />)
fireEvent.changeText(screen.getByPlaceholderText('Enter tag name'), 'Featured')
fireEvent.press(screen.getByText('Create Tag'))
await waitFor(() =>
expectProcedureCalled(api.fetchMock, 'admin.product.createProductTag')
)
expect(lastProcedureInput(api.fetchMock, 'admin.product.createProductTag')).toMatchObject({
tagName: 'Featured',
isDashboardTag: false,
relatedStores: [],
productIds: [],
uploadUrls: [],
})
})
it('navigates back after the success alert is acknowledged', async () => {
setupApiMocks({
procedures: {
'admin.store.getStores': storesResponse,
'common.product.getAllSkusSummary': { skus: [] },
'admin.product.createProductTag': {
tag: { id: 3, tagName: 'Featured' },
message: 'Tag created successfully',
},
'admin.product.getProductTags': { tags: [], message: 'ok' },
},
})
renderWithProviders(<AddTag />)
fireEvent.changeText(screen.getByPlaceholderText('Enter tag name'), 'Featured')
fireEvent.press(screen.getByText('Create Tag'))
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Success',
'Tag created successfully',
expect.any(Array)
)
)
pressLastAlertButton('OK')
expect(routerMock.back).toHaveBeenCalled()
})
it('does not create the tag when the name is empty', async () => {
const api = setupApiMocks({
procedures: {
'admin.store.getStores': storesResponse,
'common.product.getAllSkusSummary': { skus: [] },
},
})
renderWithProviders(<AddTag />)
fireEvent.press(screen.getByText('Create Tag'))
await waitFor(() =>
expect(procCount(api.fetchMock, 'admin.product.createProductTag')).toBe(0)
)
})
})

View file

@ -0,0 +1,226 @@
/**
* Edit product tag (app/(drawer)/dashboard/product-tags/edit/index.tsx) —
* loads the tag by route param, seeds TagForm, and updates it.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import EditTag from '@/app/(drawer)/dashboard/product-tags/edit/index'
import { resetStorage, setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { routerMock, searchParamsMock } from '../mocks/router'
import { renderWithProviders } from '../helpers/render'
const tag = {
id: 7,
tagName: 'Bestsellers',
tagDescription: 'Top picks',
imageUrl: null,
isDashboardTag: true,
relatedStores: [1],
sortOrder: [11, 10],
createdAt: '2024-01-01T00:00:00.000Z',
products: [
{ productId: 10, tagId: 7, assignedAt: '2024-01-01T00:00:00.000Z', product: {} },
{ productId: 11, tagId: 7, assignedAt: '2024-01-01T00:00:00.000Z', product: {} },
],
productIds: [10, 11],
}
const storesResponse = { stores: [{ id: 1, name: 'Main Store' }], count: 1 }
const skusResponse = {
skus: [
{ id: 1, productId: 10, productName: 'Chicken', label: 'Chicken 1kg' },
{ id: 2, productId: 11, productName: 'Mutton', label: 'Mutton 1kg' },
],
}
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('Edit product tag', () => {
beforeEach(async () => {
await resetStorage()
searchParamsMock.current = { tagId: '7' }
setupApiMocks()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('shows the loading state while the tag is fetched', () => {
setupApiMocks({
procedures: {
'admin.product.getProductTagById': () => new Promise(() => {}),
},
})
renderWithProviders(<EditTag />)
expect(screen.getByText('Loading tag...')).toBeVisible()
})
it('shows "Tag not found" when the query errors', async () => {
setupApiMocks({
procedures: {
'admin.product.getProductTagById': () => {
throw new Error('404')
},
},
})
renderWithProviders(<EditTag />)
await waitFor(() => expect(screen.getByText('Tag not found')).toBeVisible())
})
it('seeds the form from the fetched tag', async () => {
const api = setupApiMocks({
procedures: {
'admin.product.getProductTagById': { tag, message: 'ok' },
'admin.store.getStores': storesResponse,
'common.product.getAllSkusSummary': skusResponse,
},
})
renderWithProviders(<EditTag />)
await waitFor(() => expect(screen.getByDisplayValue('Bestsellers')).toBeVisible())
expect(screen.getByDisplayValue('Top picks')).toBeVisible()
expect(screen.getByText('Update Tag')).toBeVisible()
expect(lastProcedureInput(api.fetchMock, 'admin.product.getProductTagById')).toEqual({ id: 7 })
})
it('orders the seeded products by sortOrder', async () => {
setupApiMocks({
procedures: {
'admin.product.getProductTagById': { tag, message: 'ok' },
'admin.store.getStores': storesResponse,
'common.product.getAllSkusSummary': skusResponse,
},
})
renderWithProviders(<EditTag />)
// sortOrder [11, 10] puts Mutton (product 11) before Chicken (product 10).
await waitFor(() => expect(screen.getByText('Mutton 1kg')).toBeVisible())
expect(screen.getByText('Chicken 1kg')).toBeVisible()
})
it('updates the tag with the expected payload', async () => {
const api = setupApiMocks({
procedures: {
'admin.product.getProductTagById': { tag, message: 'ok' },
'admin.store.getStores': storesResponse,
'common.product.getAllSkusSummary': skusResponse,
'admin.product.updateProductTag': { tag: { id: 7 }, message: 'Tag updated successfully' },
'admin.product.getProductTags': { tags: [], message: 'ok' },
},
})
renderWithProviders(<EditTag />)
await waitFor(() => expect(screen.getByDisplayValue('Bestsellers')).toBeVisible())
fireEvent.press(screen.getByText('Update Tag'))
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.product.updateProductTag'))
expect(lastProcedureInput(api.fetchMock, 'admin.product.updateProductTag')).toMatchObject({
id: 7,
tagName: 'Bestsellers',
isDashboardTag: true,
relatedStores: [1],
productIds: [11, 10],
})
})
it('navigates back after the success alert is acknowledged', async () => {
setupApiMocks({
procedures: {
'admin.product.getProductTagById': { tag, message: 'ok' },
'admin.store.getStores': storesResponse,
'common.product.getAllSkusSummary': skusResponse,
'admin.product.updateProductTag': { tag: { id: 7 }, message: 'Tag updated successfully' },
'admin.product.getProductTags': { tags: [], message: 'ok' },
},
})
renderWithProviders(<EditTag />)
await waitFor(() => expect(screen.getByDisplayValue('Bestsellers')).toBeVisible())
fireEvent.press(screen.getByText('Update Tag'))
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Success',
'Tag updated successfully',
expect.any(Array)
)
)
pressLastAlertButton('OK')
expect(routerMock.back).toHaveBeenCalled()
})
it('refetches the tag list after a successful update', async () => {
const api = setupApiMocks({
procedures: {
'admin.product.getProductTagById': { tag, message: 'ok' },
'admin.store.getStores': storesResponse,
'common.product.getAllSkusSummary': skusResponse,
'admin.product.updateProductTag': { tag: { id: 7 }, message: 'Tag updated successfully' },
'admin.product.getProductTags': { tags: [], message: 'ok' },
},
})
renderWithProviders(<EditTag />)
await waitFor(() => expect(screen.getByDisplayValue('Bestsellers')).toBeVisible())
const before = procCount(api.fetchMock, 'admin.product.getProductTags')
fireEvent.press(screen.getByText('Update Tag'))
await waitFor(() =>
expect(procCount(api.fetchMock, 'admin.product.getProductTags')).toBeGreaterThan(before)
)
})
it('refetches the tag by id after a successful update', async () => {
const api = setupApiMocks({
procedures: {
'admin.product.getProductTagById': { tag, message: 'ok' },
'admin.store.getStores': storesResponse,
'common.product.getAllSkusSummary': skusResponse,
'admin.product.updateProductTag': { tag: { id: 7 }, message: 'Tag updated successfully' },
'admin.product.getProductTags': { tags: [], message: 'ok' },
},
})
renderWithProviders(<EditTag />)
await waitFor(() => expect(screen.getByDisplayValue('Bestsellers')).toBeVisible())
const before = procCount(api.fetchMock, 'admin.product.getProductTagById')
expect(before).toBeGreaterThan(0)
fireEvent.press(screen.getByText('Update Tag'))
await waitFor(() =>
expect(procCount(api.fetchMock, 'admin.product.getProductTagById')).toBeGreaterThan(before)
)
})
it('shows the updating label while the mutation is pending', async () => {
setupApiMocks({
procedures: {
'admin.product.getProductTagById': { tag, message: 'ok' },
'admin.store.getStores': storesResponse,
'common.product.getAllSkusSummary': skusResponse,
'admin.product.updateProductTag': () => new Promise(() => {}),
},
})
renderWithProviders(<EditTag />)
await waitFor(() => expect(screen.getByDisplayValue('Bestsellers')).toBeVisible())
fireEvent.press(screen.getByText('Update Tag'))
await waitFor(() => expect(screen.getByText('Updating...')).toBeVisible())
})
})

View file

@ -0,0 +1,141 @@
/**
* Product tags list (app/(drawer)/dashboard/product-tags/index.tsx) — list,
* dashboard-tag badge, empty/error states, navigation and delete via TagMenu.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import ProductTags from '@/app/(drawer)/dashboard/product-tags/index'
import { resetStorage, setupApiMocks } from '../mocks/api'
import { procCount } from '../mocks/procedures'
import { routerMock } from '../mocks/router'
import { refreshHooks, resetRefreshHooks } from '../mocks/refresh'
import { renderWithProviders } from '../helpers/render'
const tag = (overrides: Record<string, unknown> = {}) => ({
id: 1,
tagName: 'Bestsellers',
tagDescription: 'Top picks',
imageUrl: null,
isDashboardTag: true,
relatedStores: [],
createdAt: '2024-01-01T00:00:00.000Z',
...overrides,
})
const tagsResponse = (tags: unknown[]) => ({ tags, message: 'ok' })
describe('Product tags list', () => {
beforeEach(async () => {
resetRefreshHooks()
await resetStorage()
setupApiMocks()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('shows the loading state while the query is pending', () => {
setupApiMocks({
procedures: { 'admin.product.getProductTags': () => new Promise(() => {}) },
})
renderWithProviders(<ProductTags />)
expect(screen.getByText('Loading tags...')).toBeVisible()
})
it('renders the tags with the dashboard badge', async () => {
setupApiMocks({
procedures: {
'admin.product.getProductTags': tagsResponse([
tag(),
tag({ id: 2, tagName: 'New', tagDescription: null, isDashboardTag: false }),
]),
},
})
renderWithProviders(<ProductTags />)
await waitFor(() => expect(screen.getByText('Bestsellers')).toBeVisible())
expect(screen.getByText('New')).toBeVisible()
expect(screen.getByText('Top picks')).toBeVisible()
expect(screen.getByText('Dashboard Tag')).toBeVisible()
})
it('shows the empty state', async () => {
setupApiMocks({
procedures: { 'admin.product.getProductTags': tagsResponse([]) },
})
renderWithProviders(<ProductTags />)
await waitFor(() => expect(screen.getByText('No tags yet')).toBeVisible())
})
it('shows the error state and retries', async () => {
const api = setupApiMocks({
procedures: {
'admin.product.getProductTags': () => {
throw new Error('boom')
},
},
})
renderWithProviders(<ProductTags />)
await waitFor(() => expect(screen.getByText('Error')).toBeVisible())
const before = procCount(api.fetchMock, 'admin.product.getProductTags')
fireEvent.press(screen.getByText('Retry'))
await waitFor(() =>
expect(procCount(api.fetchMock, 'admin.product.getProductTags')).toBeGreaterThan(before)
)
})
it('navigates to add and order screens', async () => {
setupApiMocks({
procedures: { 'admin.product.getProductTags': tagsResponse([tag()]) },
})
renderWithProviders(<ProductTags />)
await waitFor(() => expect(screen.getByText('Bestsellers')).toBeVisible())
fireEvent.press(screen.getByText('Add New Tag'))
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/product-tags/add')
fireEvent.press(screen.getByText('Tag Orders'))
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/product-tags/order')
})
it('renders a TagMenu per row that opens the tag options', async () => {
setupApiMocks({
procedures: { 'admin.product.getProductTags': tagsResponse([tag()]) },
})
const { UNSAFE_getAllByType } = renderWithProviders(<ProductTags />)
await waitFor(() => expect(screen.getByText('Bestsellers')).toBeVisible())
const TouchableOpacity = require('react-native').TouchableOpacity
// One trigger per rendered tag row.
expect(UNSAFE_getAllByType(TouchableOpacity).length).toBeGreaterThan(0)
})
it('refetches through the manual-refresh and mark-data-fetchers hooks', async () => {
const api = setupApiMocks({
procedures: { 'admin.product.getProductTags': tagsResponse([tag()]) },
})
renderWithProviders(<ProductTags />)
await waitFor(() => expect(screen.getByText('Bestsellers')).toBeVisible())
const before = procCount(api.fetchMock, 'admin.product.getProductTags')
expect(refreshHooks.manualRefresh).toBeTruthy()
refreshHooks.manualRefresh?.()
await waitFor(() =>
expect(procCount(api.fetchMock, 'admin.product.getProductTags')).toBeGreaterThan(before)
)
const afterManual = procCount(api.fetchMock, 'admin.product.getProductTags')
expect(refreshHooks.markDataFetchers).toBeTruthy()
refreshHooks.markDataFetchers?.()
await waitFor(() =>
expect(procCount(api.fetchMock, 'admin.product.getProductTags')).toBeGreaterThan(afterManual)
)
})
})

View file

@ -0,0 +1,231 @@
/**
* Tag orders (app/(drawer)/dashboard/product-tags/order.tsx) — orders tags by
* the `tagsOrder` constant, supports save via updateConstants and shows
* loading/empty/error states.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import TagOrders from '@/app/(drawer)/dashboard/product-tags/order'
import { resetStorage, setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { routerMock, searchParamsMock } from '../mocks/router'
import { createQueryClient, renderWithProviders } from '../helpers/render'
const tagsResponse = {
tags: [
{ id: 1, tagName: 'Chicken Tag', tagDescription: null, imageUrl: null, isDashboardTag: false, relatedStores: [], createdAt: '2024-01-01T00:00:00.000Z' },
{ id: 2, tagName: 'Mutton Tag', tagDescription: null, imageUrl: null, isDashboardTag: false, relatedStores: [], createdAt: '2024-01-01T00:00:00.000Z' },
],
message: 'ok',
}
describe('Tag orders', () => {
beforeEach(async () => {
await resetStorage()
searchParamsMock.current = {}
setupApiMocks()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('shows the loading state while constants load', () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': () => new Promise(() => {}),
'admin.product.getProductTags': tagsResponse,
},
})
renderWithProviders(<TagOrders />)
expect(screen.getByText('Loading order...')).toBeVisible()
})
it('shows the error state when the constants query fails', async () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': () => {
throw new Error('boom')
},
'admin.product.getProductTags': tagsResponse,
},
})
renderWithProviders(<TagOrders />)
await waitFor(() => expect(screen.getByText('Failed to load order')).toBeVisible())
})
it('orders the tags by the tagsOrder constant', async () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': [{ key: 'tagsOrder', value: [2, 1] }],
'admin.product.getProductTags': tagsResponse,
},
})
const result = renderWithProviders(<TagOrders />)
await waitFor(() => expect(screen.getByText('Mutton Tag')).toBeVisible())
const list = result.UNSAFE_getByType(
require('react-native-draggable-flatlist').default
)
expect(list.props.data.map((t: { id: number }) => t.id)).toEqual([2, 1])
expect(screen.getByText(/2 items/)).toBeVisible()
})
it('appends tags missing from the order and accepts comma lists', async () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': [{ key: 'tagsOrder', value: '2' }],
'admin.product.getProductTags': tagsResponse,
},
})
const result = renderWithProviders(<TagOrders />)
await waitFor(() => expect(screen.getByText('Mutton Tag')).toBeVisible())
const list = result.UNSAFE_getByType(
require('react-native-draggable-flatlist').default
)
expect(list.props.data.map((t: { id: number }) => t.id)).toEqual([2, 1])
})
it('shows the empty state when there are no tags', async () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': [{ key: 'tagsOrder', value: [] }],
'admin.product.getProductTags': { tags: [], message: 'ok' },
},
})
renderWithProviders(<TagOrders />)
await waitFor(() => expect(screen.getByText('No tags available')).toBeVisible())
})
it('disables Save until the order changes, then saves', async () => {
const api = setupApiMocks({
procedures: {
'admin.const.getConstants': [{ key: 'tagsOrder', value: [1, 2] }],
'admin.product.getProductTags': tagsResponse,
'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['tagsOrder'] },
},
})
const result = renderWithProviders(<TagOrders />)
await waitFor(() => expect(screen.getByText('Chicken Tag')).toBeVisible())
// Save is disabled before any drag.
fireEvent.press(screen.getByText('Save'))
expect(procCount(api.fetchMock, 'admin.const.updateConstants')).toBe(0)
// Reorder and save.
const list = result.UNSAFE_getByType(
require('react-native-draggable-flatlist').default
)
act(() => {
list.props.onDragEnd({ data: [list.props.data[1], list.props.data[0]] })
})
await waitFor(() => expect(screen.getByText('Save')).toBeVisible())
fireEvent.press(screen.getByText('Save'))
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.const.updateConstants'))
expect(lastProcedureInput(api.fetchMock, 'admin.const.updateConstants')).toEqual({
constants: [{ key: 'tagsOrder', value: [2, 1] }],
})
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Tag order updated successfully!')
)
expect(routerMock.back).not.toHaveBeenCalled()
})
it('refetches the constants after saving', async () => {
const api = setupApiMocks({
procedures: {
'admin.const.getConstants': [{ key: 'tagsOrder', value: [1, 2] }],
'admin.product.getProductTags': tagsResponse,
'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['tagsOrder'] },
},
})
const client = createQueryClient()
const invalidateSpy = jest.spyOn(client, 'invalidateQueries')
const result = renderWithProviders(<TagOrders />, { queryClient: client })
await waitFor(() => expect(screen.getByText('Chicken Tag')).toBeVisible())
const before = procCount(api.fetchMock, 'admin.const.getConstants')
// Delta, not an absolute: the suite shares one httpBatchLink client, so a prior test's
// request can land in this test's fetchMock.
expect(before).toBeGreaterThan(0)
const list = result.UNSAFE_getByType(
require('react-native-draggable-flatlist').default
)
act(() => {
list.props.onDragEnd({ data: [list.props.data[1], list.props.data[0]] })
})
fireEvent.press(screen.getByText('Save'))
await waitFor(() =>
expect(procCount(api.fetchMock, 'admin.const.getConstants')).toBeGreaterThan(before)
)
// The refetch is driven by the path-based invalidation, not by updateConstants itself.
// Asserting the ARRAY path is the point: the old dotted string matched no query at all.
await waitFor(() => expect(invalidateSpy).toHaveBeenCalled())
expect(
invalidateSpy.mock.calls
.map((call) => (call[0] as { queryKey?: unknown[] } | undefined)?.queryKey)
.map((key) => (Array.isArray(key) ? key[0] : null))
).toContainEqual(['admin', 'const', 'getConstants'])
// Same client, same cache: the array path matches the live query, the dotted form matches none.
expect(
client.getQueryCache().findAll({ queryKey: [['admin', 'const', 'getConstants']] }).length
).toBeGreaterThan(0)
expect(
client.getQueryCache().findAll({ queryKey: ['admin.const.getConstants'] })
).toHaveLength(0)
})
it('shows the saving label while the update is pending', async () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': [{ key: 'tagsOrder', value: [1, 2] }],
'admin.product.getProductTags': tagsResponse,
'admin.const.updateConstants': () => new Promise(() => {}),
},
})
const result = renderWithProviders(<TagOrders />)
await waitFor(() => expect(screen.getByText('Chicken Tag')).toBeVisible())
const list = result.UNSAFE_getByType(
require('react-native-draggable-flatlist').default
)
act(() => {
list.props.onDragEnd({ data: [list.props.data[1], list.props.data[0]] })
})
fireEvent.press(screen.getByText('Save'))
await waitFor(() => expect(screen.getByText('Saving...')).toBeVisible())
})
it('goes back from the header and the error state', async () => {
setupApiMocks({
procedures: {
'admin.const.getConstants': () => {
throw new Error('boom')
},
'admin.product.getProductTags': tagsResponse,
},
})
renderWithProviders(<TagOrders />)
await waitFor(() => expect(screen.getByText('Failed to load order')).toBeVisible())
fireEvent.press(screen.getByText('Go Back'))
expect(routerMock.back).toHaveBeenCalled()
})
})

View file

@ -0,0 +1,58 @@
/**
* Add product (app/(drawer)/dashboard/products/add.tsx) — create-mode screen.
*
* KNOWN APP BUG (src/components/ProductForm.tsx:80): `variantSignature` calls
* `a.featureValue.trim()` unguarded. The create form starts every variant with
* an empty `quantity` value, so any keystroke / variant add makes Yup throw
* `TypeError: Cannot read properties of undefined (reading 'trim')`,
* `validateForm()` never resolves, and the form cannot be submitted. This
* screen therefore can only be asserted for render/loading; the submit payload
* is covered against ProductForm with valid seeded values (see
* tests/components/product-form.test.tsx). See the final report.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import { fireEvent, screen } from '@testing-library/react-native'
import AddProduct from '@/app/(drawer)/dashboard/products/add'
import { resetStorage, setupApiMocks } from '../mocks/api'
import { procCount } from '../mocks/procedures'
import { searchParamsMock } from '../mocks/router'
import { renderWithProviders } from '../helpers/render'
describe('Add product', () => {
beforeEach(async () => {
await resetStorage()
searchParamsMock.current = {}
setupApiMocks()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('renders the create form with a single seeded variant', () => {
renderWithProviders(<AddProduct />)
expect(screen.getByText('Create Product')).toBeVisible()
expect(screen.getByTestId('product-name-input')).toBeVisible()
expect(screen.getByTestId('variant-0-price')).toBeVisible()
expect(screen.getByTestId('variant-0-attr-0-name').props.value).toBe('quantity')
expect(screen.queryByTestId('variant-1-price')).toBeNull()
})
it('starts the form empty', () => {
renderWithProviders(<AddProduct />)
expect(screen.getByTestId('product-name-input').props.value).toBe('')
expect(screen.getByTestId('variant-0-price').props.value).toBe('')
expect(screen.getByTestId('variant-0-attr-0-value').props.value).toBe('')
})
it('does not call createProduct on mount', () => {
const api = setupApiMocks()
renderWithProviders(<AddProduct />)
expect(procCount(api.fetchMock, 'admin.product.createProduct')).toBe(0)
})
})

View file

@ -0,0 +1,273 @@
/**
* Product detail (app/(drawer)/dashboard/products/detail/[id].tsx) — product
* fetch, variants/deals/reviews render, empty reviews, edit/back navigation and
* the respondToReview flow.
*
* HARNESS GAP: tests/mocks/router.ts `expoRouterMock()` (admin-ui) does not
* expose a `Stack`/`Tabs` primitive, but this screen renders
* `<Stack.Screen options={{ headerShown: false }} />`. Without a stub the render
* hangs indefinitely. We spread the harness mock and add a `Stack.Screen`
* no-op locally (the harness file itself is untouched). See the final report.
*/
jest.mock('expo-router', () => {
const base = require('../mocks/router').expoRouterMock()
return {
...base,
Stack: Object.assign(() => null, { Screen: () => null }),
}
})
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import ProductDetail from '@/app/(drawer)/dashboard/products/detail/[id]'
import { resetStorage, setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { routerMock, searchParamsMock } from '../mocks/router'
import { refreshHooks, resetRefreshHooks } from '../mocks/refresh'
import { renderWithProviders } from '../helpers/render'
const product = {
id: 5,
name: 'Chicken Breast',
shortDescription: 'Boneless',
longDescription: 'Farm fresh boneless breast',
incrementStep: 1,
skus: [
{
id: 51,
price: '215',
marketPrice: '220',
flashPrice: '199',
isFlashAvailable: true,
isOutOfStock: false,
images: ['https://assets.test/p/1.png'],
features: [{ id: 1, featureName: 'quantity', featureValue: '0.5 kg' }],
},
],
deals: [
{ quantity: 3, price: 600, validTill: '2099-01-01T00:00:00.000Z' },
],
}
const review = {
id: 91,
userName: 'Asha',
ratings: 5,
reviewBody: 'Great meat',
imageUrls: [],
signedImageUrls: [],
adminResponse: null,
adminResponseImages: [],
signedAdminImageUrls: [],
}
const reviewsResponse = (reviews: unknown[]) => ({ reviews, hasMore: false })
describe('Product detail', () => {
beforeEach(async () => {
resetRefreshHooks()
await resetStorage()
searchParamsMock.current = { id: '5' }
setupApiMocks()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('shows the loading state while the product is fetched', () => {
setupApiMocks({
procedures: { 'admin.product.getProductById': () => new Promise(() => {}) },
})
renderWithProviders(<ProductDetail />)
expect(screen.getByText('Loading...')).toBeVisible()
})
it('shows Product Not Found when the query errors', async () => {
setupApiMocks({
procedures: {
'admin.product.getProductById': () => {
throw new Error('404')
},
},
})
renderWithProviders(<ProductDetail />)
await waitFor(() => expect(screen.getByText('Product Not Found')).toBeVisible())
})
it('renders the product, variants, deals and reviews', async () => {
const api = setupApiMocks({
procedures: {
'admin.product.getProductById': { product },
'admin.product.getProductReviews': reviewsResponse([review]),
},
})
renderWithProviders(<ProductDetail />)
await waitFor(() => expect(screen.getByText('Chicken Breast')).toBeVisible())
expect(screen.getByText('Boneless')).toBeVisible()
expect(screen.getByText('1 Variant')).toBeVisible()
expect(screen.getByText('₹215')).toBeVisible()
expect(screen.getByText('₹220')).toBeVisible()
expect(screen.getByText('0.5 kg')).toBeVisible()
expect(screen.getByText('Special Deals')).toBeVisible()
expect(screen.getByText('Buy 3')).toBeVisible()
expect(screen.getByText('Great meat')).toBeVisible()
expect(screen.getByText('Asha')).toBeVisible()
await waitFor(() =>
expect(lastProcedureInput(api.fetchMock, 'admin.product.getProductById')).toEqual({ id: 5 })
)
await waitFor(() =>
expect(lastProcedureInput(api.fetchMock, 'admin.product.getProductReviews')).toMatchObject({
productId: 5,
})
)
})
it('shows the no-reviews state', async () => {
setupApiMocks({
procedures: {
'admin.product.getProductById': { product },
'admin.product.getProductReviews': reviewsResponse([]),
},
})
renderWithProviders(<ProductDetail />)
await waitFor(() => expect(screen.getByText('No reviews yet')).toBeVisible())
})
it('shows an existing admin response', async () => {
setupApiMocks({
procedures: {
'admin.product.getProductById': { product },
'admin.product.getProductReviews': reviewsResponse([
{ ...review, adminResponse: 'Thanks for the feedback!' },
]),
},
})
renderWithProviders(<ProductDetail />)
await waitFor(() => expect(screen.getByText('Admin Response')).toBeVisible())
expect(screen.getByText('Thanks for the feedback!')).toBeVisible()
expect(screen.queryByText('Reply')).toBeNull()
})
it('navigates to edit and back', async () => {
setupApiMocks({
procedures: {
'admin.product.getProductById': { product },
'admin.product.getProductReviews': reviewsResponse([]),
},
})
renderWithProviders(<ProductDetail />)
await waitFor(() => expect(screen.getByText('Chicken Breast')).toBeVisible())
fireEvent.press(screen.getByText('Edit'))
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/products/edit?id=5')
})
it('goes back from the error state', async () => {
setupApiMocks({
procedures: {
'admin.product.getProductById': () => {
throw new Error('404')
},
},
})
renderWithProviders(<ProductDetail />)
await waitFor(() => expect(screen.getByText('Product Not Found')).toBeVisible())
fireEvent.press(screen.getByText('Go Back'))
expect(routerMock.back).toHaveBeenCalled()
})
it('opens the reply dialog and submits a review response', async () => {
const api = setupApiMocks({
procedures: {
'admin.product.getProductById': { product },
'admin.product.getProductReviews': reviewsResponse([review]),
'admin.product.respondToReview': { success: true, review: { id: 91 } },
},
})
renderWithProviders(<ProductDetail />)
await waitFor(() => expect(screen.getByText('Great meat')).toBeVisible())
fireEvent.press(screen.getByText('Reply'))
// The reply form opens inside a bottom dialog; its placeholder identifies it.
const input = await screen.findByPlaceholderText('Write your response here...')
fireEvent.changeText(input, 'Thank you!')
act(() => {
fireEvent.press(screen.getByText('Submit Response'))
})
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.product.respondToReview'))
expect(lastProcedureInput(api.fetchMock, 'admin.product.respondToReview')).toMatchObject({
reviewId: 91,
adminResponse: 'Thank you!',
adminResponseImages: [],
})
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Response submitted')
)
})
it('refetches the reviews after a review response is submitted', async () => {
const api = setupApiMocks({
procedures: {
'admin.product.getProductById': { product },
'admin.product.getProductReviews': reviewsResponse([review]),
'admin.product.respondToReview': { success: true, review: { id: 91 } },
},
})
renderWithProviders(<ProductDetail />)
// The mounted reviews query (fed by `reviewsResponse([review])`) has loaded.
await waitFor(() => expect(screen.getByText('Great meat')).toBeVisible())
const before = procCount(api.fetchMock, 'admin.product.getProductReviews')
fireEvent.press(screen.getByText('Reply'))
const input = await screen.findByPlaceholderText('Write your response here...')
fireEvent.changeText(input, 'Thank you!')
// Opening the dialog and typing do not refetch the reviews, so any increase
// below can only come from the submit handler invalidating the query.
expect(procCount(api.fetchMock, 'admin.product.getProductReviews')).toBe(before)
act(() => {
fireEvent.press(screen.getByText('Submit Response'))
})
// Submitting invalidates admin.product.getProductReviews, which refetches
// the mounted reviews query this screen renders.
await waitFor(() =>
expect(procCount(api.fetchMock, 'admin.product.getProductReviews')).toBeGreaterThan(before)
)
})
it('refetches the product through useMarkDataFetchers', async () => {
const api = setupApiMocks({
procedures: {
'admin.product.getProductById': { product },
'admin.product.getProductReviews': reviewsResponse([]),
},
})
renderWithProviders(<ProductDetail />)
await waitFor(() => expect(screen.getByText('Chicken Breast')).toBeVisible())
const before = procCount(api.fetchMock, 'admin.product.getProductById')
expect(refreshHooks.markDataFetchers).toBeTruthy()
refreshHooks.markDataFetchers?.()
await waitFor(() =>
expect(procCount(api.fetchMock, 'admin.product.getProductById')).toBeGreaterThan(before)
)
})
})

View file

@ -0,0 +1,216 @@
/**
* Edit product (app/(drawer)/dashboard/products/edit.tsx) — loads a product by
* route id, seeds ProductForm, loads/refetches, validation and the
* updateProduct payload.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import EditProduct from '@/app/(drawer)/dashboard/products/edit'
import { resetStorage, setupApiMocks } from '../mocks/api'
import {
expectProcedureCalled,
lastProcedureInput,
procCount,
} from '../mocks/procedures'
import { searchParamsMock } from '../mocks/router'
import { refreshHooks, resetRefreshHooks } from '../mocks/refresh'
import { renderWithProviders } from '../helpers/render'
const product = {
id: 7,
name: 'Chicken',
shortDescription: 'Fresh',
longDescription: 'Very fresh',
storeId: 1,
productType: 'item',
incrementStep: 1,
skus: [
{
id: 71,
name: null,
price: '250',
marketPrice: '300',
flashPrice: null,
isFlashAvailable: false,
isOffer: false,
isComboOnly: false,
isDeleted: false,
isSuspended: false,
images: ['https://assets.test/p/1.png'],
imageKeys: ['product-images/1.png'],
features: [{ id: 1, featureName: 'quantity', featureValue: '1 kg' }],
comboItems: [],
},
],
}
const updateResponse = { product: { id: 7 }, message: 'Product updated successfully' }
const listResponse = { products: [], count: 0 }
describe('Edit product', () => {
beforeEach(async () => {
resetRefreshHooks()
await resetStorage()
searchParamsMock.current = { id: '7' }
setupApiMocks()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('shows the loading state while the product is fetched', () => {
setupApiMocks({
procedures: {
'admin.product.getProductById': () => new Promise(() => {}),
},
})
renderWithProviders(<EditProduct />)
expect(screen.getByText('Loading product...')).toBeVisible()
})
it('shows "Product not found" when the query resolves without a product', async () => {
setupApiMocks({
procedures: { 'admin.product.getProductById': { product: null } },
})
renderWithProviders(<EditProduct />)
await waitFor(() => expect(screen.getByText('Product not found')).toBeVisible())
})
it('seeds the form from the fetched product', async () => {
const api = setupApiMocks({
procedures: {
'admin.product.getProductById': { product },
'common.getStoresSummary': { stores: [{ id: 1, name: 'Main Store' }] },
},
})
renderWithProviders(<EditProduct />)
await waitFor(() => expect(screen.getByTestId('product-name-input').props.value).toBe('Chicken'))
expect(screen.getByTestId('variant-0-price').props.value).toBe('250')
expect(screen.getByTestId('variant-0-attr-0-value').props.value).toBe('1 kg')
expect(screen.getByText('Save Changes')).toBeVisible()
await waitFor(() =>
expect(lastProcedureInput(api.fetchMock, 'admin.product.getProductById')).toEqual({ id: 7 })
)
})
it('routes the product id from the URL params', async () => {
searchParamsMock.current = { id: '42' }
const api = setupApiMocks({
procedures: {
'admin.product.getProductById': { product: { ...product, id: 42 } },
'common.getStoresSummary': { stores: [] },
},
})
renderWithProviders(<EditProduct />)
await waitFor(() =>
expect(lastProcedureInput(api.fetchMock, 'admin.product.getProductById')).toEqual({ id: 42 })
)
})
it('updates the product with the expected payload', async () => {
const api = setupApiMocks({
procedures: {
'admin.product.getProductById': { product },
'admin.product.updateProduct': updateResponse,
'admin.product.getProducts': listResponse,
'common.getStoresSummary': { stores: [{ id: 1, name: 'Main Store' }] },
},
})
renderWithProviders(<EditProduct />)
await waitFor(() => expect(screen.getByTestId('product-name-input').props.value).toBe('Chicken'))
fireEvent.press(screen.getByTestId('create-product-button'))
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.product.updateProduct'))
expect(lastProcedureInput(api.fetchMock, 'admin.product.updateProduct')).toMatchObject({
id: 7,
name: 'Chicken',
storeId: 1,
productType: 'item',
skus: [
expect.objectContaining({
id: 71,
price: 250,
marketPrice: 300,
features: [{ featureName: 'quantity', featureValue: '1 kg' }],
}),
],
})
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Product updated successfully!')
)
})
it('refetches the product and list after a successful update', async () => {
const api = setupApiMocks({
procedures: {
'admin.product.getProductById': { product },
'admin.product.updateProduct': updateResponse,
'admin.product.getProducts': listResponse,
'common.getStoresSummary': { stores: [{ id: 1, name: 'Main Store' }] },
},
})
renderWithProviders(<EditProduct />)
await waitFor(() => expect(screen.getByTestId('product-name-input').props.value).toBe('Chicken'))
const productBefore = procCount(api.fetchMock, 'admin.product.getProductById')
const listBefore = procCount(api.fetchMock, 'admin.product.getProducts')
fireEvent.press(screen.getByTestId('create-product-button'))
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.product.updateProduct'))
await waitFor(() =>
expect(procCount(api.fetchMock, 'admin.product.getProductById')).toBeGreaterThan(productBefore)
)
await waitFor(() =>
expect(procCount(api.fetchMock, 'admin.product.getProducts')).toBeGreaterThan(listBefore)
)
})
it('refetches through useManualRefresh', async () => {
const api = setupApiMocks({
procedures: {
'admin.product.getProductById': { product },
'common.getStoresSummary': { stores: [{ id: 1, name: 'Main Store' }] },
},
})
renderWithProviders(<EditProduct />)
await waitFor(() => expect(screen.getByTestId('product-name-input').props.value).toBe('Chicken'))
const before = procCount(api.fetchMock, 'admin.product.getProductById')
expect(refreshHooks.manualRefresh).toBeTruthy()
refreshHooks.manualRefresh?.()
await waitFor(() =>
expect(procCount(api.fetchMock, 'admin.product.getProductById')).toBeGreaterThan(before)
)
})
it('shows the saving label while the update is pending', async () => {
setupApiMocks({
procedures: {
'admin.product.getProductById': { product },
'admin.product.updateProduct': () => new Promise(() => {}),
'common.getStoresSummary': { stores: [{ id: 1, name: 'Main Store' }] },
},
})
renderWithProviders(<EditProduct />)
await waitFor(() => expect(screen.getByTestId('product-name-input').props.value).toBe('Chicken'))
fireEvent.press(screen.getByTestId('create-product-button'))
await waitFor(() => expect(screen.getByText('Saving...')).toBeVisible())
})
})

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