# Pre-Release QA Test Plan — ChhoteKisan Web

**App**: Laravel 11 / PHP 8.2 e-commerce & delivery platform (products, "salad"/Vital Kitchen catalog, subscriptions, coupons, referrals, wallet, Razorpay payments, WhatsApp/SMS/push notifications).
**Surfaces**: Customer mobile API (`routes/api.php`, Sanctum bearer auth, 19 controllers) + Admin backend (`routes/web.php`, session auth, 40+ controllers).
**Purpose**: Manual/QA execution plan for a pre-release sanity pass. There is currently almost no automated test coverage (5 trivial stub tests in `tests/`, no model factories beyond `UserFactory`, and PHPUnit is not configured for an isolated sqlite DB) — treat this document as the primary release gate.

## How to use this document

- Section 1 lists concrete pre-release risks found while mapping the codebase — triage these first.
- Section 2 (P0) has full test cases for every revenue/security-critical flow: steps, API calls, expected responses, DB checks, edge cases.
- Section 3 (P1/P2) covers the remaining ~50 admin/customer modules as compact test-case tables — enough to execute a scripted pass without the full template overhead.
- Section 4 has representative SQL to validate DB integrity after running the functional passes.
- Section 5 is an OWASP-style security checklist tied to what actually exists in this codebase.
- Section 6 is the final go/no-go checklist.

### Environment / test data prerequisites

- `database/seeders/DatabaseSeeder.php` only actively calls `PermissionSeeder → UserSeeder → SubscriptionSeeder → SubscriptionPlanSeeder`. All catalog/CMS/delivery/coupon/VK/salad seeders exist but are **commented out** — run them individually before testing, e.g.:
  `php artisan db:seed --class=CategorySeeder`, `--class=ProductSeeder`, `--class=DeliveryZoneSeeder`, `--class=CouponSeeder`, `--class=SaladManagementSeeder`, etc. (26 seeders total under `database/seeders/`).
- No factories exist beyond `UserFactory` — build test orders/products/coupons/subscriptions via the admin UI or direct seeding, not `Model::factory()`.
- `phpunit.xml` has SQLite in-memory commented out — if you also write automated Feature tests, point them at a disposable DB first; don't run them against a shared dev DB.
- Have at least: 1 superadmin (`id=1`), 1 role-based staff user, 1 direct-permission staff user, 1 staff user with no permissions, 2+ customer accounts, products in multiple pricing/stock states (in stock, low stock, out of stock, pre-order), an active coupon, an active subscription plan, and Razorpay **test-mode** credentials configured in `Settings → Payment`.

---

## 1. Findings / Pre-release Blockers

Severity-tagged risks surfaced while mapping the codebase. Each maps to test cases in Section 2/3 — fix or explicitly accept before release.

| # | Severity | Finding | Location | Recommendation |
|---|----------|---------|----------|-----------------|
| F1 | **High** | No Razorpay webhook or signature-verification endpoint exists anywhere (`routes/api.php` and `routes/web.php` both confirmed clean of `webhook`). Payment reconciliation depends entirely on the mobile client calling `POST /payments/razorpay` after capture. If the app crashes/loses connectivity after Razorpay captures the payment but before this callback fires, the charge succeeds with **no local order/payment record**, and nothing will ever retry it. | `app/Http/Controllers/Api/PaymentController.php` | Add a Razorpay webhook receiver with `X-Razorpay-Signature` HMAC verification as a reconciliation safety net. At minimum, execute TC_PAY_006 (abandonment scenario) and decide if this is acceptable for launch. |
| F2 | **Medium** | For `payment_type != 'order'` (e.g. `subscription`), `PaymentController::payableAmount()` trusts the client-supplied `amount` at order-creation time (only `min:1` validated) — unlike the `order` path, which always recomputes from the server-side cart. It's cross-checked later against the *captured* Razorpay amount and, at subscription-creation time, against `SubscriptionPlan.selling_price` — so a tampered amount should still be rejected downstream, but this needs explicit verification. | `app/Http/Controllers/Api/PaymentController.php:205-241` | Execute TC_PAY_007 (tamper `amount` on a subscription payment intent, confirm rejection). |
| F3 | **Medium** | Sanctum tokens never expire (`config/sanctum.php` → `expiration => null`). A leaked/stolen mobile bearer token stays valid indefinitely until the user explicitly logs out. | `config/sanctum.php`; comment in `app/Http/Middleware/UpdateLastActiveAt.php:12-14` | Confirm this is an accepted risk for the mobile API; verify TC_AUTH_009/010 (logout and logout-all actually revoke tokens). Consider a max token TTL or idle-expiry policy. |
| F4 | **Medium** | `OtpService::otpMatches()` has a hardcoded test-mobile/test-OTP bypass sourced from `SendSmsService::getTestMobile()/getTestOtp()`. | `app/Services/OtpService.php:102-112` | Verify TC_AUTH_011: confirm the bypass values are unset/unreachable in the production `Setting` configuration before release. |
| F5 | **Medium** | Product image uploads validate only `image\|max:2048`, with **no explicit `mimes:` whitelist** — unlike Gallery/Blog controllers, which explicitly exclude SVG. Laravel's default `image` rule permits SVG uploads, a known stored-XSS vector if ever rendered inline/unsanitized. | `app/Http/Controllers/Backend/ProductListController.php` (multiple upload actions), `VkProductController.php` | Execute TC_SEC_003: attempt to upload a crafted SVG as a product image; add `mimes:jpeg,png,jpg,webp,gif,bmp,avif` explicitly if it succeeds. |
| F6 | **Low/Medium** | `App\Http\Middleware\CheckPermission` is defined but registered/used nowhere in the app. Real backend authorization instead relies on inline Policy `can()` checks and ad-hoc dual-path (role-based + direct-permission) checks written per-controller (e.g. `CustomerController::authorizeCustomer()`). `OrderManagementController` shows **no visible per-action permission check** beyond the blanket `admin` session-guard middleware. | `app/Http/Middleware/CheckPermission.php`; `app/Http/Controllers/Backend/OrderManagementController.php` | Execute TC_PERM_004/005: confirm every high-value backend controller (Orders, Coupons, Customers, Settings) enforces an explicit authorization check, not just "is a logged-in admin." |
| F7 | **Low** | No `config/cors.php` exists — Laravel 11 falls back to framework defaults (`allowed_origins: ['*']`) for `api/*` and `sanctum/csrf-cookie`. | (absent file) | Likely acceptable since the customer API uses bearer tokens, not cookie-credentialed requests, but should be an explicit, published config rather than an implicit default. |
| F8 | **Low** | `public/razorpay-test.html` — a manual Razorpay checkout test harness — is deployed inside `public/` and will be publicly reachable in production unless excluded from the release build. | `public/razorpay-test.html` | Remove or restrict access before release. |
| F9 | **Info** | `isSuperAdmin()` is hardcoded to `$this->id === 1`. | `app/Models/User.php` | Verify user ID 1 cannot be deleted/reassigned and is protected in the admin UI. |
| F10 | **Info** | Three different validation-error response shapes coexist across the API: Laravel default (inline `$request->validate()`), FormRequest classes (custom `failedValidation()` → `{status:'error', message, errors}`), and `Validator::make()` + `sendValidationError()` (seen in `PaymentController`). | Various | Execute TC_API_001 (contract check) — confirm mobile clients handle all observed shapes, or standardize before release. |

---

## 2. P0 Critical-Path Test Cases

### 2.1 Authentication & OTP

```
TEST CASE ID: TC_AUTH_001
Title: Send OTP to a valid 10-digit mobile number
Priority: P0 | Type: API/Functional
Preconditions: None (guest)
Steps:
 1. POST /api/auth/send-otp { "mobile": "9876543210" }
Expected: 200, OTP dispatched via SendSmsService; otp_verifications row created for the mobile with 5-minute expiry, attempts=0.
DB Check: SELECT * FROM otp_verifications WHERE mobile='9876543210' ORDER BY id DESC LIMIT 1; -- expect fresh row, expires_at ~5 min out
Edge Cases: mobile not 10 digits (422), non-numeric mobile (422), 4th send within 10 min for same mobile (blocked by app-level window even if route throttle window has reset), 4th send within 1 min (429 via throttle:3,1).
```

```
TEST CASE ID: TC_AUTH_002
Title: Verify OTP with correct code — new customer auto-created
Priority: P0 | Type: API/Functional/DB
Preconditions: Valid OTP sent (TC_AUTH_001) for a mobile with no existing user row
Steps:
 1. POST /api/auth/verify-otp { "mobile": "9876543210", "otp": "<code>", "device_name": "iphone-15", "platform": "ios" }
Expected: 200, new user created (user_type=customer, is_mobile_verified=1, mobile_verified_at set), Sanctum token returned, referral code auto-generated for this new user, LoginHistory row written, welcome notification fired.
DB Check: SELECT id, user_type, is_mobile_verified, referral_code FROM users WHERE mobile='9876543210';
         SELECT * FROM login_histories WHERE user_id=<id> ORDER BY id DESC LIMIT 1;
Edge Cases: expired OTP (auto-deleted, 422/expired message), wrong OTP (attempts++, on 5th failure record auto-deleted + 429), OTP already consumed (reused after successful verify).
```

```
TEST CASE ID: TC_AUTH_003
Title: Verify OTP with referral_code — referral processed only on first creation
Priority: P0 | Type: Functional/DB
Preconditions: A valid referrer's referral_code exists; new mobile number
Steps:
 1. POST /api/auth/verify-otp { "mobile": "...", "otp": "...", "referral_code": "ABC123" }
Expected: New user created and linked as referee; referral record created (pending until first order per admin flow). Re-verifying the same already-existing user later with a referral_code must NOT create a duplicate/second referral.
DB Check: SELECT * FROM referrals WHERE referee_user_id=<new_user_id>; -- exactly 1 row (unique constraint enforced)
Edge Cases: invalid/nonexistent referral_code (should not block login, ignored or 422 — verify actual behavior), self-referral (own code), malformed code violating regex ^[A-Za-z0-9]{3,20}$.
```

```
TEST CASE ID: TC_AUTH_004
Title: Verify OTP with guest_token — guest cart/wishlist/preferences merge into new user
Priority: P0 | Type: Functional/DB
Preconditions: A guest cart with items exists under guest_token=<uuid> (added via POST /api/cart/add with X-Guest-Token header before login)
Steps:
 1. Add 2 distinct items to guest cart.
 2. POST /api/auth/verify-otp with the same guest_token in the body.
Expected: User's cart now contains the merged items (quantities summed where product_id+product_pricing_id match, new lines otherwise); guest cart row deleted; guest wishlist and selected-pincode preference also merged.
DB Check: SELECT * FROM cart_items WHERE cart_id=(SELECT id FROM carts WHERE user_id=<id>); SELECT * FROM carts WHERE guest_token='<uuid>'; -- expect 0 rows (deleted)
Edge Cases: guest_token omitted entirely (merge must NOT run); guest_token referencing an empty/nonexistent guest cart (no-op, no error); user already has existing cart items that overlap with guest items (quantities summed, not duplicated).
```

```
TEST CASE ID: TC_AUTH_005
Title: Verify OTP — max attempts lockout
Priority: P0 | Type: Security/Functional
Steps:
 1. Send OTP, then submit 5 consecutive wrong OTPs for the same mobile.
Expected: Each failed attempt increments `attempts`; after the 5th failure the OTP record is deleted and a 429/locked response returned. A subsequent send-otp for the same mobile should issue a fresh record (subject to the send-rate window).
DB Check: SELECT attempts FROM otp_verifications WHERE mobile='...'; -- row should be gone after 5th failure
```

```
TEST CASE ID: TC_AUTH_006
Title: Get profile / update profile — uniqueness scoping
Priority: P0 | Type: API/Functional
Preconditions: Authenticated customer
Steps:
 1. GET /api/auth/profile
 2. POST /api/auth/update-profile { "mobile": "<another verified customer's mobile>" }
Expected: (1) 200 with own profile. (2) 422 — mobile must be unique among user_type=customer; a mobile used by a staff/admin account with the same value should NOT block (uniqueness is scoped to customers), and updating with your own current mobile should succeed (no false-positive collision).
```

```
TEST CASE ID: TC_AUTH_007
Title: FCM token registration
Priority: P0 | Type: API/Functional
Steps:
 1. POST /api/auth/fcm-token { "fcm_token": "<token>", "device_name": "pixel-8", "platform": "android" }
Expected: 200, user_fcm_tokens row created/updated for (user_id, device_name).
Edge Cases: same device_name re-registered with a new token (upsert, not duplicate row); fcm_token missing (422).
```

```
TEST CASE ID: TC_AUTH_008
Title: Login history
Priority: P0 | Type: API/Functional
Steps:
 1. Login from 2 different devices.
 2. GET /api/auth/login-history
Expected: 2 open (not-yet-logged-out) entries with correct device_name/IP/user-agent, most recent first.
```

```
TEST CASE ID: TC_AUTH_009
Title: Logout — single device
Priority: P0 | Type: Security/Functional
Preconditions: 2 active tokens/devices for the same user
Steps:
 1. POST /api/auth/logout with device A's token.
 2. Immediately retry any authenticated call (e.g. GET /api/auth/profile) with device A's token.
 3. Retry the same call with device B's token.
Expected: (2) 401 Unauthenticated — token revoked. (3) still 200 — device B unaffected. login_histories row for device A gets a logout timestamp; device B's stays open.
```

```
TEST CASE ID: TC_AUTH_010
Title: Logout-all — revokes every token
Priority: P0 | Type: Security/Functional
Preconditions: 3 active tokens across 3 devices
Steps:
 1. POST /api/auth/logout-all on any one device's token.
 2. Retry authenticated calls from all 3 devices.
Expected: All 3 return 401. All FCM tokens for the user removed. All open login_histories rows closed.
DB Check: SELECT count(*) FROM personal_access_tokens WHERE tokenable_id=<id>; -- 0
```

```
TEST CASE ID: TC_AUTH_011
Title: [F4] Confirm OTP test-bypass is disabled in production config
Priority: P0 | Type: Security
Steps:
 1. Inspect the production Settings table for the SMS test-mobile/test-OTP keys used by SendSmsService::getTestMobile()/getTestOtp().
 2. If populated, attempt verify-otp using the configured bypass pair.
Expected: Either the keys are empty/unset in production, or if intentionally kept for App-Store review purposes, confirm the test mobile number is not a real customer-reachable number and access is otherwise restricted.
```

### 2.2 Addresses (`app/Http/Controllers/Api/AddressController.php`)

```
TEST CASE ID: TC_ADDR_001
Title: Create address — Home/Work single-slot enforcement
Priority: P0 | Type: API/Functional
Preconditions: Authenticated customer with no saved addresses
Steps:
 1. POST /api/addresses { label: "Home", address_line_1: "12 MG Road", city: "Chennai", pincode: "600001", ... }
 2. Repeat with label "Home" again (different address_line_1/pincode).
 3. POST again with label "Work".
 4. POST twice more with label "Office" (custom label).
Expected: (1) 201, is_default auto-set true (first address). (2) 422 "You already have a Home address...". (3) 201 succeeds (Work is independent of Home). (4) both custom-label "Office" addresses succeed — no cap on custom labels.
DB Check: SELECT label, is_default FROM user_addresses WHERE user_id=<id>;
```

```
TEST CASE ID: TC_ADDR_002
Title: Create address — duplicate address_line_1 + pincode rejected
Priority: P0 | Type: API/Functional
Steps:
 1. Create an address with address_line_1="12 MG Road", pincode="600001".
 2. Create another with the same address_line_1 and pincode but a different label/city.
Expected: (2) 422 "This address already exists in your saved addresses." Confirm the check is scoped per-user (a second user can use the identical address_line_1+pincode without conflict).
```

```
TEST CASE ID: TC_ADDR_003
Title: use_my_details toggle — name/mobile sourced from profile
Priority: P0 | Type: API/Functional
Steps:
 1. POST /api/addresses { use_my_details: true, address_line_1: "...", city: "...", pincode: "..." } (name/mobile omitted).
Expected: 201 — name/mobile on the created address equal the user's profile name/mobile, not blank/required-error.
Edge Case: use_my_details:false with name/mobile omitted → 422 (required when not using profile details).
```

```
TEST CASE ID: TC_ADDR_004
Title: Update address — partial update must not silently reset use_my_details
Priority: P0 | Type: Functional (regression — code comment flags this exact risk at AddressController.php:162-167)
Preconditions: Address exists with use_my_details=true
Steps:
 1. PUT /api/addresses/{id} { "city": "Bengaluru" } — omit the use_my_details key entirely.
Expected: 200 — use_my_details remains true on the stored record (must NOT flip to false just because the key was absent from this partial-update request).
DB Check: SELECT use_my_details FROM user_addresses WHERE id=<id>; -- still 1
```

```
TEST CASE ID: TC_ADDR_005
Title: Set default address — swap semantics
Priority: P0 | Type: Functional
Preconditions: 2+ saved addresses, address A is default
Steps:
 1. POST /api/addresses/{B}/set-default
Expected: 200 — B.is_default=1, A.is_default=0 (and every other address for this user is false — only one default at a time).
```

```
TEST CASE ID: TC_ADDR_006
Title: Delete address — blocked when default or subscription-linked
Priority: P0 | Type: Functional
Preconditions: Address A is default; Address B is linked to an active or paused UserSubscription.delivery_address_id; Address C is a plain non-default, unused address
Steps:
 1. DELETE /api/addresses/{A} (default)
 2. DELETE /api/addresses/{B} (subscription-linked)
 3. DELETE /api/addresses/{C}
Expected: (1) 422 "cannot be deleted... set another as default first." (2) 422 "linked to an active subscription." (3) 200, deleted.
```

```
TEST CASE ID: TC_ADDR_007
Title: Cross-tenant address access is not leaked
Priority: P0 | Type: Security
Steps:
 1. As user A, note an address id belonging to user B.
 2. GET /api/addresses/{B's id} as user A. Repeat for PUT and DELETE.
Expected: 404 (not 403 — scoped via $user->addresses()->findOrFail(), so the ID space doesn't confirm existence to a non-owner) for all three verbs.
```

```
TEST CASE ID: TC_ADDR_008
Title: Address field validation boundaries
Priority: P1 | Type: API/Functional
Steps: Submit pincode with 5 or 7 digits; mobile with 9 or 11 digits; latitude=91 / longitude=181; delivery_instructions_images with 6 files; a non-image file disguised with an image extension.
Expected: All rejected with 422 and field-specific messages (pincode: digits:6, mobile: digits:10, lat between -90..90, lng between -180..180, images max:5, mimes enforced).
```

### 2.3 Cart

```
TEST CASE ID: TC_CART_001
Title: Guest cart — add/update/remove/clear via X-Guest-Token
Priority: P0 | Type: API/Functional
Preconditions: No auth token; a fresh guest_token (client-generated UUID)
Steps:
 1. POST /api/cart/add with header X-Guest-Token: <uuid>, body { product_id, product_pricing_id, quantity: 2 }
 2. GET /api/cart/ with the same header.
 3. PUT /api/cart/items/{id} { quantity: 5 }
 4. DELETE /api/cart/items/{id}
 5. DELETE /api/cart/clear
Expected: Each step 200 with the guest cart correctly scoped to that guest_token only (a different guest_token/no token sees an empty cart).
```

```
TEST CASE ID: TC_CART_002
Title: Stock and min/max quantity enforcement
Priority: P0 | Type: Functional
Preconditions: A product with stock_qty=3, and (if configured) min/max order qty on ProductPricing
Steps:
 1. Add quantity=3 (should succeed).
 2. Add quantity=4 for the same item (should fail or cap, per business rule).
 3. Add an out-of-stock product.
Expected: Out-of-stock add rejected with a clear message; over-stock add rejected or clamped consistently with checkout-time re-validation (see TC_ORD_003).
```

### 2.4 Coupons

```
TEST CASE ID: TC_COUP_001
Title: Apply/remove coupon; recalculation invalidates an inapplicable coupon
Priority: P0 | Type: Functional
Preconditions: Active coupon with min-cart-value or category restriction; cart currently qualifies
Steps:
 1. POST /api/coupons/apply { code: "SAVE50" } → verify cart totals reflect the discount.
 2. Remove enough items so the cart no longer qualifies, then trigger any endpoint that recalculates totals (e.g. PaymentController::createOrder).
Expected: Coupon is automatically detached (coupon_id cleared) and the create-order call returns 422 "Applied coupon is no longer valid..." rather than silently charging the discounted amount.
DB Check: SELECT coupon_id, coupon_code FROM carts WHERE id=<cart_id>; -- coupon_id null after invalidation
```

```
TEST CASE ID: TC_COUP_002
Title: Coupon usage is one-per-order (unique constraint)
Priority: P0 | Type: DB/Security
Steps:
 1. Successfully place an order using coupon "SAVE50".
 2. Attempt to force a second coupon_usages row for the same order_id (e.g. via a retried/duplicated request).
Expected: Second attempt fails at the DB layer (coupon_usages.order_id is UNIQUE) — no double-discounting of a single order.
```

### 2.5 Checkout / Orders

```
TEST CASE ID: TC_ORD_001
Title: Checkout — server always recomputes cart total (amount tampering blocked)
Priority: P0 | Type: Security/Functional
Steps:
 1. Build a cart totaling ₹500.
 2. Call POST /api/payments/razorpay/create-order with payment_type=order and a client-supplied amount far below the real total (e.g. amount=1). (Note: 'amount' is accepted by the validator but must be IGNORED for payment_type=order.)
Expected: The Razorpay order is created for the server-computed ₹500 (plus tip), not the client-sent value — confirm via the returned RazorpayOrderResource amount and by cross-checking Razorpay's dashboard/test API.
```

```
TEST CASE ID: TC_ORD_002
Title: Checkout blocked without address / unserviceable pincode
Priority: P0 | Type: Functional
Steps:
 1. Attempt checkout with no default address and no address_id supplied.
 2. Attempt checkout with a valid address but a pincode that has no DeliveryZonePincode row.
Expected: (1) 422 "add or select a delivery address." (2) 422 "Delivery is not available for the selected pincode."
```

```
TEST CASE ID: TC_ORD_003
Title: Checkout re-validates stock at payment time (race condition)
Priority: P0 | Type: Functional/Concurrency
Steps:
 1. Add the last unit of a product to Cart A (user 1) and Cart B (user 2).
 2. User 1 completes checkout first (stock now 0).
 3. User 2 attempts checkout.
Expected: User 2 gets 422 "currently out of stock" / "Only 0 unit(s) available" at the create-order/store step, even though the item was addable to cart earlier. Pre-order-flagged products should bypass this stock-out block — verify with a pre-order product at 0 stock (should be allowed through).
```

```
TEST CASE ID: TC_ORD_004
Title: Scheduled delivery slot validation
Priority: P0 | Type: Functional
Steps:
 1. Checkout with delivery_type=scheduled, scheduled_delivery_at inside a configured slot window.
 2. Same but scheduled_delivery_at in the past.
 3. Same but scheduled_slot_key referencing a non-existent slot.
 4. scheduled_delivery_enabled=false in Settings, attempt any scheduled checkout.
Expected: (1) 200. (2) 422 "must be after the current time." (3) 422 "invalid." (4) 422 "not currently available."
```

```
TEST CASE ID: TC_ORD_005
Title: Payment idempotency — payment_reference_no reuse blocked
Priority: P0 | Type: Security/Functional
Steps:
 1. Complete a successful order payment with payment_reference_no=P1.
 2. Replay the identical POST /api/payments/razorpay request with the same P1 (e.g. via a retried mobile network call).
 3. Attempt to use P1 again on a second, different order.
Expected: (2) 409 "This payment has already been processed." (3) 409 conflict — a captured payment can only ever be attached to one order/subscription resource_id.
```

```
TEST CASE ID: TC_ORD_006
Title: Captured amount vs payable amount mismatch rejected
Priority: P0 | Type: Security
Steps: Simulate/force a scenario where the Razorpay-reported captured amount differs from the server-computed payable amount (e.g. cart changed between order-create and capture).
Expected: 422 "Paid amount does not match the payable amount." — order is NOT created; funds are captured on Razorpay's side but must be flagged for manual reconciliation (there is no automated refund-on-mismatch path — confirm this is handled operationally).
```

```
TEST CASE ID: TC_ORD_007
Title: COD/online payment availability toggle edge values
Priority: P1 | Type: Functional
Steps: Set Settings.cod_enabled / razorpay_status to each of: 1, "1", true, "true", "on", "yes", "enabled", 0, "", "false", null. Attempt checkout with each payment method.
Expected: Only the "enabled" truthy variants listed permit that payment method; 0/""/"false"/null correctly disable it. No PHP loose-comparison surprises (e.g. "false" string must NOT evaluate truthy).
```

```
TEST CASE ID: TC_ORD_008
Title: Order list / detail / receipt / reorder
Priority: P0 | Type: API/Functional
Steps:
 1. GET /api/orders/ (list, paginated)
 2. GET /api/orders/{id} (own order) and {other user's order id} (should 404)
 3. GET /api/orders/{id}/receipt (PDF)
 4. POST /api/orders/{id}/reorder
Expected: (2) cross-tenant 404. (3) valid PDF with correct order lines/totals. (4) new cart populated from the original order's line items, respecting current stock/price (not the historical price).
```

### 2.6 Admin Order Management (`OrderManagementController`)

```
TEST CASE ID: TC_ADMORD_001
Title: Illegal status transitions rejected
Priority: P0 | Type: Functional
Steps: From an order in "new" status, attempt to jump directly to "delivered" (skipping confirmed/packed/dispatched).
Expected: 422 — rejected against the hardcoded WORKFLOW_ACTIONS transition map. Only the explicitly allowed next-states succeed.
```

```
TEST CASE ID: TC_ADMORD_002
Title: Cancel — stock restoration + referral reversal is idempotent
Priority: P0 | Type: Functional/DB
Steps:
 1. Cancel a confirmed order that had reduced ProductPricing.stock_qty at checkout and was linked to a first-order referral reward.
 2. Attempt to trigger the cancel action a second time on the same already-cancelled order (e.g. resubmit the request).
Expected: (1) stock_qty restored correctly per line item, InventoryLog entries written, referral reward reversed once (reversed_at stamped). (2) second attempt is a no-op / blocked — stock is NOT restored twice and the referral reward is NOT reversed twice.
DB Check: SELECT stock_qty FROM product_pricing WHERE id=...; SELECT reversed_at FROM referrals WHERE ...;
```

```
TEST CASE ID: TC_ADMORD_003
Title: Delivered — referral reward credited exactly once
Priority: P0 | Type: Functional/DB
Steps: Mark an order "delivered" twice in a row (second call should be blocked by the transition map, but verify at the DB/service level too).
Expected: Referrer + referee wallet credit happens exactly once, not on every delivered-transition attempt.
```

```
TEST CASE ID: TC_ADMORD_004
Title: Notification firing per transition
Priority: P1 | Type: Functional
Steps: Transition an order through confirmed → dispatched (with delivery_person_id assigned) → delivered, and separately cancel a different order.
Expected: Correct push/SMS/email/WhatsApp notifications fire per transition; invoice PDF is attached as the WhatsApp header document specifically on delivery.
```

### 2.7 Admin Auth & Permissions

```
TEST CASE ID: TC_PERM_001
Title: Superadmin (id=1) bypasses all permission checks
Priority: P0 | Type: Security
Steps: As user id=1, access every admin module without any explicit role/permission rows assigned.
Expected: Full access everywhere (isSuperAdmin() bypass). Confirm no other user can ever be assigned id=1 (e.g. after a fresh migrate:fresh + seed, or after deleting/recreating users).
```

```
TEST CASE ID: TC_PERM_002
Title: Role-based permission grants access; absence denies it
Priority: P0 | Type: Security
Steps:
 1. Create a role with only the "customers.read" permission, assign to staff user X.
 2. As X, access Customers (read) — expect success.
 3. As X, attempt to create/update a customer, or access an unrelated module (e.g. Coupons).
Expected: (2) 200. (3) 403 for both the disallowed action on an allowed module and any action on a disallowed module.
```

```
TEST CASE ID: TC_PERM_003
Title: Direct (non-role) permission grants access independent of role
Priority: P0 | Type: Security
Steps: Assign a direct permission to a staff user via /admin/users/{id}/permissions with no role assigned at all.
Expected: Access granted per the direct-permission set, proving the OR-logic (role OR direct OR superadmin) works even with role_id null.
```

```
TEST CASE ID: TC_PERM_004
Title: [F6] Staff user with zero permissions and zero role cannot mutate orders
Priority: P0 | Type: Security
Steps: As a staff user with valid admin-session login but no role and no direct permissions, attempt OrderManagementController::updateStatus.
Expected: Verify whether this is actually blocked. Per code review, OrderManagementController appears to only require the blanket `admin` middleware (any active non-customer logged-in user) with no visible per-action authorization check — if this test succeeds when it shouldn't, it confirms F6 and should be treated as a release blocker for order-tampering by any staff account.
```

```
TEST CASE ID: TC_PERM_005
Title: [F6] Audit remaining backend controllers for missing per-action authorization
Priority: P0 | Type: Security
Steps: Repeat TC_PERM_004's pattern (login as a permission-less staff user, attempt a mutating action) against: CouponController, SettingsController, ManageUsersController (role/permission editor itself), DeliverySetupManageZoneController, SubscriptionController (admin), ReferralController.
Expected: Document which controllers correctly 403 a permission-less staff user and which rely only on the `admin` middleware. Escalate any gaps found before release — a permission-less-but-authenticated staff account should not be able to edit payment/coupon/settings/role data.
```

### 2.8 Payment Security Cross-Checks (tie back to Findings)

```
TEST CASE ID: TC_PAY_006
Title: [F1] Abandoned payment — captured on Razorpay, callback never sent
Priority: P0 | Type: Functional/Reconciliation
Steps:
 1. Create a Razorpay order via /payments/razorpay/create-order.
 2. Complete payment on Razorpay's checkout (test mode) so it is captured.
 3. Do NOT call POST /api/payments/razorpay/store (simulate app crash/kill before callback).
 4. Check payment_gateway_histories and orders tables.
Expected (documenting current behavior, not a pass/fail per se): no local record is created; the captured amount is "orphaned" with no automated retry/reconciliation. Confirm with the team whether this needs a webhook fix (F1) before launch, or a manual ops runbook to reconcile via Razorpay's dashboard.
```

```
TEST CASE ID: TC_PAY_007
Title: [F2] Tamper client-supplied amount for a non-order payment_type
Priority: P0 | Type: Security
Steps:
 1. POST /api/payments/razorpay/create-order { payment_type: "subscription", amount: 1, plan_id: <a plan actually priced at ₹999> }
 2. Complete the ₹1 Razorpay test payment (or attempt to).
 3. POST /api/payments/razorpay (store) with the resulting payment_reference_no, requesting the app create the ₹999 subscription.
Expected: The subscription-creation step must cross-check against SubscriptionPlan.selling_price and reject the mismatch (422) rather than granting a ₹999 subscription for ₹1. If it does NOT reject, this is a critical pricing-bypass bug — escalate immediately.
```

---

## 3. P1/P2 Modules — Compact Test-Case Tables

### 3.1 Subscriptions (`SubscriptionController` — customer API)

| ID | Title | Steps | Expected |
|----|-------|-------|----------|
| TC_SUB_001 | Subscribe to a plan | POST /subscriptions/subscribe with valid plan_id, address_id, payment_method | 201; one active/paused subscription max per subscriber — repeat call while one is already active → 422 |
| TC_SUB_002 | Family-pack subscribe | POST /subscriptions/family-pack/subscribe with 2 family members in one request | 201; same member listed twice across two groups in one request → 422 |
| TC_SUB_003 | Family-pack payment method restriction | Attempt family-pack subscribe with payment_method=online | 422 — endpoint only allows COD per code review; verify actual behavior |
| TC_SUB_004 | Pause | POST /subscriptions/{id}/pause with from=today | 422 — pause `from` must be tomorrow or day-after only |
| TC_SUB_005 | Pause length cap | Pause spanning more days than plan.max_pause_days | 422 |
| TC_SUB_006 | Resume | Resume before pause end | end_date extended to reclaim unused pause days |
| TC_SUB_007 | Change plan — no immediate switch | POST /subscriptions/{id}/change-plan | New plan takes effect the day AFTER current end_date, not immediately; a second change-plan request while one is pending → 422 (no stacking) |
| TC_SUB_008 | Cancel | POST /subscriptions/{id}/cancel | Subscription cancelled; verify no further billing/production entries generated |
| TC_SUB_009 | Today's salad / dashboard | GET /subscriptions/{id}/today, /salads, /dashboard | Correct day's scheduled items reflect plan + pause state |
| TC_SUB_010 (Admin) | Subscriber pause/resume from admin | Admin pauses a subscriber via SubscriberController | Reflected correctly on customer's GET /subscriptions/my |

### 3.2 Family Members

| ID | Title | Steps | Expected |
|----|-------|-------|----------|
| TC_FAM_001 | CRUD | Create/update/delete a family member | Standard CRUD success |
| TC_FAM_002 | Delete blocked while subscribed | Delete a family member with an active/paused subscription | 422 |
| TC_FAM_003 | default_delivery_address_id ownership | Set default_delivery_address_id to another user's address id | 422/404 — Rule::exists scoped to user_id |

### 3.3 Wishlist / Search / Notify-Me

| ID | Title | Steps | Expected |
|----|-------|-------|----------|
| TC_WISH_001 | Guest wishlist requires guest_token | POST /wishlist/toggle as guest with no guest_token | 422 ValidationException |
| TC_WISH_002 | Toggle add/remove | Toggle same product twice | Added then removed |
| TC_SRCH_001 | Fuzzy search | Search a misspelled product name | Reasonable fuzzy/Levenshtein match returned |
| TC_SRCH_002 | Search history scoping | Two different guest_token/device_id values | Histories isolated per identity |
| TC_SRCH_003 | Delete search history | DELETE /search/history/{id} and /search/history (all) | Correct scoped deletion |
| TC_NOTIFY_001 | Back-in-stock subscribe | POST /notify-me for an out-of-stock product | Row created; when restocked, NotifyAdminsNotifyMeJob / customer notification fires |

### 3.4 Referrals & Wallet

| ID | Title | Steps | Expected |
|----|-------|-------|----------|
| TC_REF_001 | One referral per referee | Same user referred twice via two different referral codes | Second attempt blocked (referee_user_id unique) |
| TC_REF_002 | Wallet balance accuracy | Credit via referral reward, debit via wallet-funded order | GET /referrals/wallet balance matches sum of wallet transactions |
| TC_REF_003 | Wallet deduction only on completed payment | Start a wallet-partial-payment checkout, abandon before payment completes | Wallet must NOT be debited for an abandoned/failed order |

### 3.5 Notifications & Preferences

| ID | Title | Steps | Expected |
|----|-------|-------|----------|
| TC_NP_001 | Toggle preferences | PUT /notification-preferences/ disable SMS | Subsequent SMS-triggering events skip this user |
| TC_NP_002 | Mark read / read-all | PATCH /notifications/{id}/read, POST /notifications/read-all | Correct read_at stamping |
| TC_NP_003 (Admin) | Broadcast campaign | Create broadcast targeting an audience segment | audience-count matches actual recipient count; resend doesn't double-send to already-sent users |
| TC_NP_004 (Admin) | Template test-sender | Use test-email/test-sms/test-whatsapp senders in Settings | Delivered to the test target only, not real customers |

### 3.6 Admin CMS Modules

| ID | Module | Steps | Expected |
|----|--------|-------|----------|
| TC_CMS_001 | Blog | Create/update/delete blog, check URL-uniqueness (url-check endpoint) | Duplicate slug rejected |
| TC_CMS_002 | Blog Category | CRUD + url-check | Same as above |
| TC_CMS_003 | Career + Job Applications | Post a career, submit application, change applicant status | Status workflow correct; applicant list filters work |
| TC_CMS_004 | Testimonial | CRUD + status toggle | — |
| TC_CMS_005 | Gallery | Upload image (jpeg/png/webp/gif/bmp/avif) and one disallowed type (e.g. .exe renamed .jpg) | Whitelisted mimes accepted, others rejected |
| TC_CMS_006 | Meta Tags | Per-page meta tag CRUD | Reflected correctly on frontend `<head>` |
| TC_CMS_007 | Legal Policy | CRUD | Publicly reachable via GET /api/legal-policies/{title} |
| TC_CMS_008 | Home Hero Banner | CRUD + reorder + status | Reorder persists; inactive banners excluded from customer API |
| TC_CMS_009 | Manage Content (banners) | CRUD, category linking, deeplink-search, status | Deeplink target resolves correctly on tap (see project's Deeplink Targets contract) |
| TC_CMS_010 | Enquiry inbox | Submit contact-us form, admin changes status | — |

### 3.7 Catalog / Inventory Admin

| ID | Module | Steps | Expected |
|----|--------|-------|----------|
| TC_CAT_001 | Category CRUD + reorder + toggle-status | — | Inactive category hidden from customer catalog endpoints |
| TC_CAT_002 | Section CRUD + multiple reorder endpoints | Reorder sections, assign products/groups/banners | Ordering persists and reflects on GET /home/sections |
| TC_CAT_003 | ProductList — product/group/subgroup CRUD | — | Section pricing overrides base pricing correctly |
| TC_CAT_004 | VkProduct — CRUD + ingredients | — | Ingredient/calorie data reflected in customer product detail |
| TC_CAT_005 | Salad Management — bowls/categories/ingredients/addons/health-benefits | — | — |
| TC_CAT_006 | Salad orders — export/invoice/cancel/status | Cancel a salad order | Consistent with general order-cancel stock/referral rules (TC_ADMORD_002) |
| TC_INV_001 | Manage Inventory — update-stock / add-stock / add-wastage | Add wastage entry | stock_qty decremented; InventoryLog entry written with correct reason |
| TC_CAT_007 | [F5] Product image upload accepts SVG | Upload a `<svg onload=alert(1)>` file as a product image via ProductListController/VkProductController | Currently likely ACCEPTED per code review — confirm and fix per F5 |

### 3.8 Delivery Setup

| ID | Title | Steps | Expected |
|----|-------|-------|----------|
| TC_DEL_001 | Delivery zone/pincode CRUD | Add a pincode to a zone | Pincode becomes serviceable at checkout (TC_ORD_002 dependency) |
| TC_DEL_002 | Fee bands | Configure a fee band, place an order | Confirm actual delivery-fee calculation source — code review found fee logic is pincode/product-group based; DeliveryZoneFeeBand.from_km exists but wasn't observed wired into computation. Verify which one actually applies today. |
| TC_DEL_003 | Delivery team CRUD + status | — | Inactive delivery person not assignable in Order Management dispatch |

### 3.9 Reports & Admin Misc

| ID | Title | Steps | Expected |
|----|-------|-------|----------|
| TC_REP_001 | Sales/Product/Inventory/Customer/Payment reports | Generate each report for a known date range | Figures match direct DB aggregates (see Section 4) |
| TC_SET_001 | Settings groups | Update general/app-web/invoice/SEO/payment/Firebase/reCAPTCHA settings | Persisted and reflected where consumed (e.g. Firebase config flows into the service-worker route at routes/web.php) |
| TC_ACT_001 | Activity Log | Perform a mutating admin action | activity_logs row written with correct module/action/type, sensitive fields (password, mail_password, firebase_private_key, SMS/Razorpay secrets) redacted |
| TC_PGH_001 | Payment Gateway History (read-only) | Cross-check listed transactions against actual Razorpay test-mode transactions | Match |

---

## 4. Database Validation Queries

Run after executing the functional passes above to confirm constraint integrity.

```sql
-- Coupon: one usage row per order (F-tied to TC_COUP_002)
SELECT order_id, COUNT(*) FROM coupon_usages GROUP BY order_id HAVING COUNT(*) > 1;
-- Expect 0 rows

-- Referral: one referral row per referee (TC_REF_001)
SELECT referee_user_id, COUNT(*) FROM referrals GROUP BY referee_user_id HAVING COUNT(*) > 1;
-- Expect 0 rows

-- Wallet: exactly one wallet row per user
SELECT user_id, COUNT(*) FROM user_wallets GROUP BY user_id HAVING COUNT(*) > 1;
-- Expect 0 rows

-- Orders: verify denormalized order_items survive product deletion
-- (product_id/product_pricing_id nullOnDelete, but product_name/price snapshot columns must remain populated)
SELECT id, product_id, product_pricing_id, product_name, price
FROM order_items
WHERE product_id IS NULL AND (product_name IS NULL OR product_name = '');
-- Expect 0 rows — a deleted product must not blank out historical order line data

-- Roles: confirm no orphaned users.role_id after a role delete
SELECT u.id, u.role_id FROM users u
LEFT JOIN roles r ON r.id = u.role_id
WHERE u.role_id IS NOT NULL AND r.id IS NULL;
-- Expect 0 rows; if this ever returns rows, deleting an in-use role leaves dangling FKs (test TC_PERM_002/003 dependency)

-- Payment idempotency: no duplicate payment_reference_no + payment_type
SELECT payment_reference_no, payment_type, COUNT(*) FROM payment_gateway_histories
GROUP BY payment_reference_no, payment_type HAVING COUNT(*) > 1;
-- Expect 0 rows

-- Address: exactly one default address per user
SELECT user_id, COUNT(*) FROM user_addresses WHERE is_default = 1 GROUP BY user_id HAVING COUNT(*) > 1;
-- Expect 0 rows

-- Subscriptions: at most one active/paused subscription per subscriber
SELECT subscriber_id, COUNT(*) FROM user_subscriptions
WHERE status IN ('active','paused') GROUP BY subscriber_id HAVING COUNT(*) > 1;
-- Expect 0 rows

-- Stock sanity: no negative stock after cancel/restore cycles (TC_ADMORD_002)
SELECT id, stock_qty FROM product_pricing WHERE stock_qty < 0;
-- Expect 0 rows

-- OTP: no stale unexpired-looking rows past their expiry still present (cleanup job sanity)
SELECT COUNT(*) FROM otp_verifications WHERE expires_at < NOW();
-- Investigate if non-trivial — expired rows should be pruned on next verify/send for that mobile, not accumulate indefinitely
```

---

## 5. Security Checklist

- [ ] **TLS/HTTPS** enforced in production (`SESSION_SECURE_COOKIE`, `APP_URL` scheme) — `config/session.php` does not force `secure` true by default; confirm prod `.env`.
- [ ] **Razorpay reconciliation** — F1: webhook/signature verification gap accepted or fixed (TC_PAY_006).
- [ ] **Amount tampering** — F2 verified closed (TC_PAY_007); TC_ORD_001/TC_ORD_006 pass.
- [ ] **Token lifecycle** — F3: Sanctum non-expiry accepted; TC_AUTH_009/010 (logout/logout-all revoke tokens) pass.
- [ ] **OTP bypass** — F4 confirmed disabled/restricted in production (TC_AUTH_011).
- [ ] **File upload validation** — F5: SVG-via-product-image gap fixed or accepted (TC_CAT_007); all other upload paths (Gallery, Blog, Address delivery-instructions images) re-verified against their explicit mime whitelists.
- [ ] **Authorization coverage** — F6: every mutating backend controller has an explicit permission/policy check, not just the blanket `admin` session gate (TC_PERM_004/005).
- [ ] **CORS** — F7: `allowed_origins: ['*']` default reviewed and explicitly accepted or tightened.
- [ ] **Test harness exposure** — F8: `public/razorpay-test.html` removed/restricted from the release build.
- [ ] **Superadmin protection** — F9: user id=1 cannot be deleted or have its role stripped in a way that locks out all admin access.
- [ ] **API contract consistency** — F10: validation-error envelope differences across FormRequest / inline `validate()` / `Validator::make()` documented for mobile client handling (TC_API_001).
- [ ] **Input validation / injection** — spot-check search (`SearchController`), DataTable filters (CustomerController, VkProductController), and report date-range filters for parameterized-query usage (Eloquent/query builder default; flag any raw `DB::raw`/string-concatenated SQL found).
- [ ] **Rate limiting** — confirmed only on OTP routes (`throttle:3,1`, `throttle:10,1`) plus the app-level OTP window; all other customer API endpoints (search, cart, coupon-apply) are otherwise unthrottled at the route level — assess abuse risk for cart/coupon endpoints specifically (coupon brute-forcing codes, cart-spam).
- [ ] **Sensitive-data logging** — `LogUserActivity` redaction list (password, mail_password, firebase_private_key, SMS/Razorpay secrets) re-verified still covers every current secret field after any settings-schema changes since this audit.
- [ ] **Cross-tenant data isolation** — spot-checked for Addresses (TC_ADDR_007), Orders (TC_ORD_008), Family Members (TC_FAM_003) — extend the same 404-not-403 pattern check to Subscriptions and Wishlist.
- [ ] **Path traversal** — the `/media/{path}` and `/storage/{path}` file-proxy routes in `routes/web.php` guard against `..` in the path; re-verify with URL-encoded traversal payloads (`%2e%2e%2f`) and absolute paths.

---

## 6. Pre-Deployment Checklist

- [ ] All P0 test cases (Sections 2.1–2.8) executed and passing, or exceptions explicitly signed off.
- [ ] Findings F1–F10 each have a documented decision: **fixed**, **accepted risk**, or **deferred with a tracked ticket**.
- [ ] Security Checklist (Section 5) fully checked off.
- [ ] Representative P1/P2 modules (Section 3) smoke-tested — at minimum one full CRUD cycle per module.
- [ ] Database Validation Queries (Section 4) run against the pre-release/staging dataset with zero unexpected rows.
- [ ] Razorpay is confirmed in **live** mode with live credentials in `Settings → Payment` before go-live (and test-mode artifacts like `razorpay-test.html` removed per F8).
- [ ] Seeders/test data used for QA are NOT present in the production database (no test users, test coupons, or test Razorpay transactions leaking into prod).
- [ ] Error messages reviewed for user-friendliness (no raw stack traces/exception messages leaking to the mobile client — confirm `APP_DEBUG=false` in production).
- [ ] Mobile app smoke-tested end-to-end against the release API build: OTP login → browse → cart → address → checkout → payment → order tracking → notification received.
- [ ] Admin panel smoke-tested end-to-end: login → new order appears → confirm → pack → dispatch → deliver → referral/wallet credited → invoice PDF correct.
