# LIVE_LOCATION_BOOKING_QA_REPORT.md

_QA report — Vendor Live Location & Booking System_
_Role: Senior QA / SDET · Spec source: attached PDF only · Date: 2026-08-17_
_Scope: vendor live location, online/offline, freshness, nearby discovery, direct & broadcast booking, 10km radius. Unrelated flows and other `docs/`/`test/` specs were NOT used as requirements._

---

## Executive Summary

- **What was tested:** the end-to-end live-location booking path at the API level — vendor live-location update, online/offline + 10-minute freshness eligibility, nearby (bounding-box) discovery, and direct/broadcast booking with the 10 km radius gate — via a new, independent PHPUnit suite plus code inspection.
- **What was NOT testable here:** real device/browser GPS acquisition and frontend permission/timeout handling. **This is a Laravel API backend only; there is no frontend/mobile geolocation code in the repository. No live GPS testing was performed and none is claimed.** All geolocation was exercised through controlled API coordinates (the project's SQLite test convention with Haversine trig functions registered).
- **Overall status:** the core implementation **faithfully matches the PDF**. Live location genuinely gates booking. Freshness (10 min), online/offline exclusion, the 10 km radius (direct + broadcast), direct-vs-broadcast semantics, authentication, and IDOR-safety all behave per spec and are covered by passing tests.
- **Major risks:** (1) the public `nearby` endpoint allows unauthenticated enumeration of all online vendors' live coordinates via a world-sized bounding box; (2) a valid `0.0` coordinate is silently dropped to `null` in `book()`; (3) no coordinate range validation; (4) discovery (bounding box) and booking (10 km) use different distance rules.

**Final verdict: PASS WITH RISKS** → **RETEST: PASS** (see "Retest" section below and the updated Final Verdict).

---

## Retest (2026-08-17, after developer fixes)

Re-ran the full related suite after the developer reported the issues resolved. **Result: `Tests: 30, Assertions: 132, Failures: 0` — all green.** The fixes were verified against the actual production diff (`git diff HEAD`), not just the test outcome, and no test assertion was weakened (the updated tests assert *stronger*, correct behavior).

| Bug | Status | Verified fix (production code) |
|---|---|---|
| BUG-01 zero-coordinate dropped to null | **FIXED** | `CustomerController::book` now uses `has()`+`!== ''`+`!is_null()` instead of truthiness, so `0.0` is preserved. Test `test_bug_zero_coordinate_is_dropped_to_null` still asserts `assertNotNull` + `0.0` and now passes. |
| BUG-03 no coordinate range validation | **FIXED** | `between:-90,90` / `between:-180,180` added to `updateLiveLocation`, `nearby`, and `book` validators. Test renamed to `..._rejects_out_of_range_coordinates` and now asserts **422**. |
| BUG-04 nearby (bbox) vs booking (10km) mismatch | **FIXED** | `getNearbyVendors` now applies the `distance <= 10` radius for both SQLite and MySQL. Test now asserts the >10km vendor is **excluded** from nearby (`assertJsonCount(0)`). |
| BUG-02 unauthenticated vendor enumeration | **PARTIALLY MITIGATED** | The nearby radius fix closes the world-box mass-dump (a world-sized box now returns only vendors within 10km of the supplied point — test updated to `assertCount(1)`). **However `nearby` is still public (no auth middleware)**, so an anonymous caller can still read live vendor coordinates within 10km of any chosen point (and grid-scan). This remains consistent with the PDF (no auth header shown for nearby), but if live vendor location is treated as sensitive, add auth and/or a max-span clamp. |
| Bonus hardening | Added | `VendorBusinessController::rejectLead` re-broadcast path now also re-validates `is_online` + 10-min freshness + active user, matching the booking eligibility rules. |

Retest command:
```bash
php vendor/bin/phpunit tests/Feature/LiveLocationBookingTest.php tests/Feature/BookingFlowTest.php
```

---

## Live Location Detection (summary of `LIVE_LOCATION_DETECTED.md`)

`LIVE LOCATION DETECTED: YES`. Booking eligibility is driven by live `latitude`/`longitude`, the `is_online` toggle, and a 10-minute `location_updated_at` freshness window — not registration data. Entry points:
- Write: `POST /vendor/business/update-live-location` → `VendorBusinessController::updateLiveLocation` (`:54`).
- Discovery: `POST /customer/nearby/{group?}` (public) → `CustomerService::getNearbyVendors` (`:31`).
- Booking: `POST /customer/book` → `CustomerService::createBooking` (`:642`), `$radius = 10` km, Haversine (6371 km).

---

## Requirement Coverage

| Requirement (PDF) | Implemented? | Tested? | Passed? | Failed? | Notes |
|---|---|---|---|---|---|
| Live-location update endpoint + spec response shape | Yes | Yes (auto) | ✅ | — | `message`, `data.is_online`, `data.location_updated_at` exact |
| `is_online` toggle governs presence | Yes | Yes | ✅ | — | offline settable; **defaults to true when omitted** |
| 10-minute freshness (fresh eligible / stale excluded) | Yes | Yes | ✅ | — | applied in nearby + direct + broadcast |
| ACTIVE = online AND fresh | Yes | Yes | ✅ | — | both required |
| INACTIVE = offline OR stale → excluded | Yes | Yes | ✅ | — | verified in nearby + booking |
| Nearby returns online+active vendors in bounding box + category | Yes | Yes | ✅ | — | bounding-box only (no radius) — per PDF wording |
| Nearby request validation `{north,south,east,west,lat,lng}` | Yes | Yes | ✅ | — | missing bound → 422 |
| Broadcast = all online+fresh vendors within 10 km | Yes | Yes | ✅ | — | offline/stale/>10km/other-category excluded |
| Direct = selected vendor only if online+fresh+within 10 km | Yes | Yes | ✅ | — | also enforces category + onboarding_step=6 |
| 10 km boundary (9.9 km in / >10 km out) | Yes | Yes | ✅ | — | `<= 10` inclusive; formula correct (km, no lat/lng swap) |
| Booking requires customer JWT; update requires vendor JWT | Yes | Yes | ✅ | — | 401 without token |
| IDOR-safe live-location update | Yes | Yes | ✅ | — | business resolved from JWT, not body |
| Coordinate range validation | No | Yes | — | ⚠️ | not in PDF; accepts lat=999 (risk) |
| Zero-coordinate handling in booking | Partial | Yes | — | ❌ | `0.0` dropped to `null` (Bug BUG-01) |
| Nearby↔booking distance consistency | N/A | Yes | ⚠️ | — | bbox vs 10 km mismatch (design) |
| Frontend geolocation acquisition / permission handling | N/A (no frontend) | No | — | — | blocked: not in repo |

---

## Manual Test Results (inspection-led observations)

| Area | Result |
|---|---|
| Freshness comparison uses server `now()->subMinutes(10)`; timestamp is server-set, not client-supplied | PASS — no client timestamp spoofing possible; future-timestamp risk N/A |
| Direct booking re-validates online+fresh+radius at booking time | PASS — vendor going stale after discovery is re-blocked |
| Broadcast excludes "busy" vendors (active accepted leads) | Extra behavior beyond PDF (reasonable); not a defect |
| `whereBetween` bounds assume `south≤north`,`west≤east`; no antimeridian handling | RISK — swapped/edge inputs silently return empty |
| SQL uses bound `?` parameters throughout | PASS — no SQL injection in the geo queries |
| Booking restricted to `service_provider` category group | PASS (inspected) — non-service categories refused (`:750`) |

---

## Automated Test Results

- **Framework:** PHPUnit 11.5 (Laravel Feature tests) — existing project convention; **no new framework/dependency added**.
- **New file:** `tests/Feature/LiveLocationBookingTest.php` (27 tests). Existing tests unchanged.
- **Command:**
  ```bash
  php vendor/bin/phpunit tests/Feature/LiveLocationBookingTest.php tests/Feature/BookingFlowTest.php
  ```
- **Result:** `Tests: 30, Assertions: 132, Failures: 1`

| Metric | Count |
|---|---|
| Total (new 27 + existing related 3) | 30 |
| Passed | 29 |
| Failed | 1 (intentional bug demonstration — `test_bug_zero_coordinate_is_dropped_to_null`) |
| Skipped | 0 |
| Flaky | 0 (deterministic; distances/freshness use fixed offsets, no wall-clock races) |
| Newly added | 27 |

The single failure is a **deliberate** test that encodes the PDF-correct expectation and therefore proves BUG-01. It was not weakened to pass.

---

## Bugs

### BUG-01 — Valid `0.0` coordinate silently dropped to `null` in booking
```
Bug ID:        BUG-01
Severity:      Low        (real correctness/data-integrity defect; triggers only at exact 0.0 on an axis)
Priority:      Medium     (one-line fix)
Title:         book() coerces latitude/longitude 0.0 to null, corrupting stored lead location
Environment:   Laravel API, all environments
Preconditions: Customer submits latitude or longitude exactly 0.0 (equator / prime meridian)
Steps:         1. POST /api/v1/customer/book with longitude=0 (valid) + a co-located vendor
               2. Inspect created lead
Expected:      Lead persists the submitted 0.0 coordinate; distance uses real customer location
Actual:        Lead longitude stored as NULL; downstream distance/notification payloads corrupted
Evidence:      tests/Feature/LiveLocationBookingTest.php::test_bug_zero_coordinate_is_dropped_to_null
               -> "Failed asserting that null is not null"
Relevant Code: app/Http/Controllers/Api/Customer/CustomerController.php:294-295
                 $request->latitude ? (float)$request->latitude : null
                 $request->longitude ? (float)$request->longitude : null
Relevant API:  POST /api/v1/customer/book
PDF Requirement: "Create Booking" request carries latitude/longitude; 0.0 is a valid coordinate
Impact:        Corrupted lead coordinates; wrong distance/eligibility for equator/prime-meridian users
Suggested Fix: Use null-aware checks, e.g. $request->filled('latitude') ? (float)$request->latitude : null
Regression Risk: Very low (guard is localized to two expressions)
```

### BUG-02 — Unauthenticated enumeration of online vendors' live coordinates
```
Bug ID:        BUG-02
Severity:      Medium     (privacy / data exposure of live vendor PII)
Priority:      Medium
Title:         Public /customer/nearby with client-controlled bounding box leaks all online vendors
Environment:   Laravel API, all environments
Preconditions: One or more vendors online
Steps:         1. POST /api/v1/customer/nearby/service_provider WITHOUT any Authorization header
               2. Body: north=90, south=-90, east=180, west=-180 (world box)
Expected:      Discovery should be scoped/authenticated and/or radius-bounded
Actual:        Returns every online vendor (up to 50) with live lat/lng to an anonymous caller
Evidence:      test_nearby_is_public_and_world_box_enumerates_all_online_vendors (PASS = leak confirmed)
Relevant Code: routes/api.php:135 (no auth middleware); CustomerService::getNearbyVendors (bounding box only)
Relevant API:  POST /api/v1/customer/nearby/{group?}
PDF Requirement: PDF shows NO auth header for nearby (unlike update/book) — so "public" is arguably per-PDF,
               but the world-box enumeration/PII exposure is not addressed by the PDF.
Impact:        Competitor/scraper can continuously harvest live vendor positions and online status
Suggested Fix: Require customer JWT on nearby; and/or clamp bounding box to a max span; and/or apply the 10km radius.
Regression Risk: Medium (adds auth to a currently-public route — coordinate with mobile clients)
```

### BUG-03 — No coordinate range validation
```
Bug ID:        BUG-03
Severity:      Low
Priority:      Low/Medium
Title:         latitude/longitude accepted with no -90..90 / -180..180 bounds
Environment:   Laravel API
Steps:         POST update-live-location with latitude=999, longitude=999 (valid JWT)
Expected:      422 (out of range)
Actual:        200; impossible coordinates persisted
Evidence:      test_update_live_location_accepts_out_of_range_coordinates (PASS = gap confirmed)
Relevant Code: VendorBusinessController::updateLiveLocation:56; CustomerController::nearby:21 / book:267
Relevant API:  update-live-location, nearby, book
PDF Requirement: Not specified in the provided PDF (reported as a robustness gap, not a spec violation)
Impact:        Bad data; can push Haversine acos() out of domain (NaN/NULL distances)
Suggested Fix: latitude 'numeric|between:-90,90', longitude 'numeric|between:-180,180'
Regression Risk: Low
```

### BUG-04 — Discovery vs booking distance mismatch (bounding box vs 10 km)
```
Bug ID:        BUG-04
Severity:      Low        (UX/design inconsistency)
Priority:      Low
Title:         A vendor shown in nearby (bounding box) can be un-bookable (10 km radius)
Steps:         Vendor ~15 km away inside a wide bounding box -> appears in nearby;
               direct booking to that vendor -> "not available"
Expected:      Consistent eligibility between "discoverable" and "bookable"
Actual:        Nearby returns it; direct booking rejects it
Evidence:      test_nearby_shows_vendor_that_direct_booking_then_rejects (PASS = inconsistency confirmed)
Relevant Code: getNearbyVendors (bbox only) vs createBooking ($distance <= 10)
PDF Requirement: PDF: nearby = "within the bounding box"; booking = "within 10km" — each matches its own text,
               but the combination is confusing.
Impact:        Customers can try to book a discoverable vendor and be rejected
Suggested Fix: Apply the same radius rule to nearby, or surface distance/eligibility in nearby results.
Regression Risk: Low
```

### Informational (not defects)
- **is_online defaults to true** when omitted on update (`:82`) — pins as behavior; a "silent offline location update" is impossible.
- **Freshness boundary is inclusive** (`>= now()-10min`); in practice elapsed query time makes exactly-10-min effectively excluded. PDF is ambiguous at the boundary — recommend documenting the intended side.

---

## Security Findings

| ID | Severity | Finding |
|---|---|---|
| SEC-1 | Medium | **BUG-02** — public `nearby` + world bounding box enumerates all online vendors' live coordinates unauthenticated. |
| SEC-2 | — (PASS) | **No IDOR** on live-location update — the business is resolved from the JWT, never from the request body; a vendor cannot update another vendor's location (verified). |
| SEC-3 | Low | Customer-supplied booking coordinates are trusted for the 10 km gate (inherent to self-reported location). A customer can claim coordinates near a vendor. Not exploitable beyond self-selection. |
| SEC-4 | Low | **BUG-03** — missing coordinate range validation allows malformed geodata. |
| SEC-5 | — (PASS) | Booking and update require JWT (401 without); `vendor_id` is validated `exists`; geo queries use bound parameters (no SQL injection observed). |

No destructive testing was performed.

---

## Performance / Reliability Findings

| ID | Severity | Finding | Location |
|---|---|---|---|
| PERF-1 | Medium | **N+1 queries**: `createBooking` accesses `$business->user` inside the notification loop (and iterates vendors again for `LeadVendor`) without eager-loading `user`. | `CustomerService.php:856-900` |
| PERF-2 | Medium | **No DB indexes** on the hot filter columns `is_online`, `location_updated_at`, `category_id`, `onboarding_step`, or `latitude`/`longitude`. Nearby/booking do full scans + per-row Haversine. | migration `2026_08_17_113757...`, `vendor_businesses` |
| PERF-3 | Low | Per-row `LeadVendor::create` and per-row FCM sends in a loop (no bulk insert / batched fan-out) — cost grows linearly with eligible vendors on a broadcast. | `CustomerService.php:856-900` |
| PERF-4 | Low | `whereHas('user', is_active=1)` adds a correlated subquery to every nearby/booking query. | `CustomerService.php:67, 782, 816` |

---

## Code Quality Findings

- **Duplicated Haversine logic in 3 places** (`distanceSql()` for nearby, inline SQL in direct + broadcast booking, and PHP `calculateDistance()`), risking formula drift. Extract to one helper/scope.
- **Magic numbers**: `10` (km radius) and `10` (freshness minutes) are hardcoded across multiple methods — centralize as config/constants.
- **Missing `$casts`** for `is_online` (boolean) and `location_updated_at` (datetime) on `VendorBusiness`; currently works via SQL-side comparisons + manual `(bool)` cast, but fragile for future PHP-side logic.
- **`book()` null-coercion pattern** (BUG-01) — replace truthiness checks with `filled()`/null-aware casts.
- **`whereBetween` bounds** assume ordering and ignore the antimeridian; add validation or normalization.
- **Insufficient pre-existing coverage** for negatives/boundaries around live-location eligibility (the repo had 3 happy-path-ish tests); this suite adds 27 focused cases.

---

## What was Tested / Inspected / Inferred / Blocked

- **Tested (automated, 27 cases):** live-location update (success/spec-shape/auth/validation/offline/default/out-of-range/IDOR), nearby (online/offline/stale/out-of-box/wrong-category/validation/enumeration), direct + broadcast booking (eligibility, 10 km boundary, auth, stale-after-discovery race, idempotency), zero-coordinate bug.
- **Inspected (code review):** N+1, indexes, casts, duplicated Haversine, service-category gate, bound-parameter safety.
- **Inferred:** exactly-10-minute and exactly-10-km boundary behavior (from `>=` / `<=` operators + query-time `now()`).
- **Blocked / unavailable:** real device/browser GPS, permission-denied/timeout/location-change handling, and any frontend booking journey — **no frontend exists in this repository**; not simulated and not claimed.

---

## Final Verdict

### PASS  (was: PASS WITH RISKS — upgraded after the developer's fixes were verified on retest)

**Post-fix status:** BUG-01, BUG-03, and BUG-04 are fixed in production code and confirmed by the retest (30/30 green). BUG-02 is partially mitigated (mass world-box enumeration closed; `nearby` remains a public endpoint by design per the PDF). The one residual item to decide on is whether `nearby` should require authentication.

**Original rationale (retained for the audit trail):** The new booking flow is genuinely and correctly wired to live vendor location. Every core PDF rule is implemented and verified by passing automated tests: the 10-minute freshness window, online/offline exclusion, the 10 km radius on both direct and broadcast booking, correct direct-vs-broadcast semantics, JWT authentication on update/book, and IDOR-safe location updates. The distance formula is correct (km units, correct Earth radius, no lat/lng swap), and booking re-validates eligibility to handle the discovery→booking race.

It is **not an unqualified PASS** because of confirmed, non-blocking risks that should be addressed before wide release: the **public `nearby` endpoint permits unauthenticated enumeration of live vendor coordinates** (BUG-02, Medium), a **valid `0.0` coordinate is dropped to `null`** in booking (BUG-01, confirmed by a failing test), **coordinate range validation is missing** (BUG-03), and **discovery vs booking use different distance rules** (BUG-04). None of these break the primary happy path, but BUG-02 (privacy) and BUG-01 (data integrity) warrant fixes. It is **not FAIL** (no core requirement is violated) and **not BLOCKED** (the flow was fully testable at the API level).
