# LIVE_LOCATION_DETECTED.md

_QA investigation — Vendor Live Location & Booking System_
_Source of truth: attached PDF "Operational Flow – Vendor Live Location & Booking System" + actual implementation._
_Date: 2026-08-17_

---

## 1. Detection result

**LIVE LOCATION DETECTED: YES**

The new booking flow is genuinely wired to live vendor location. Vendor eligibility for
both nearby-search and booking is gated on live coordinates + an online toggle +
a 10-minute location-freshness window, exactly as the PDF describes. This is not a
registration-address lookup — it uses the live `latitude`, `longitude`, `is_online`,
and `location_updated_at` columns that were added specifically for this feature.

---

## 2. Exact code locations

### Database
- **Migration** `database/migrations/2026_08_17_113757_add_live_location_fields_to_vendor_businesses_table.php`
  - Adds `is_online` (boolean, default `false`) and `location_updated_at` (nullable timestamp) to `vendor_businesses`.
  - `latitude` `decimal(10,7)`, `longitude` `decimal(10,7)` already existed on `vendor_businesses`.
- **Model** `app/Models/VendorBusiness/VendorBusiness.php`
  - `latitude`, `longitude`, `is_online`, `location_updated_at` are in `$fillable`.
  - NOTE: no `$casts` for `is_online` / `location_updated_at` (see risks).

### Vendor live-location update (write path)
- **Route** `routes/api.php:74` — `POST /api/v1/vendor/business/update-live-location`
  (inside `middleware: jwt.auth`, `prefix: vendor`).
- **Controller/method** `app/Http/Controllers/Api/VendorBusiness/VendorBusinessController.php:54`
  → `updateLiveLocation(Request $request)`.
  - Validates `latitude` (required|numeric), `longitude` (required|numeric), `is_online` (nullable|boolean).
  - Resolves the vendor's business from the **JWT user** (`auth('api')->user()` → `VendorBusiness::where('user_id', $user->id)`), NOT from the request body.
  - Writes `latitude`, `longitude`, `is_online` (defaults to `true` if omitted), `location_updated_at = now()`.

### Customer nearby search (read path)
- **Route** `routes/api.php:135` — `POST /api/v1/customer/nearby/{group?}` (**public — no auth middleware**).
- **Controller/method** `app/Http/Controllers/Api/Customer/CustomerController.php:19` → `nearby()`.
- **Service** `app/Services/Customer/CustomerService.php:31` → `getNearbyVendors(...)`.
  - Filters: `onboarding_step = 6`, `is_online = true`, `location_updated_at >= now()->subMinutes(10)`, related `user.is_active = 1`, `latitude BETWEEN south..north`, `longitude BETWEEN west..east`, plus optional category / subcategory / group filters.
  - Computes Haversine distance (`distanceSql()`, Earth radius `6371` km) as a `distance` alias for sort/display; **does not** apply a radius cutoff (bounding-box only).

### Customer booking (read + write path)
- **Route** `routes/api.php:144` — `POST /api/v1/customer/book` (inside `jwt.auth`, `prefix: customer`).
- **Controller/method** `CustomerController.php:261` → `book()`.
- **Service** `CustomerService.php:642` → `createBooking(...)`.
  - `$radius = 10` (km).
  - **Direct booking** (`vendor_id` present): query for that vendor with `category_id`, `onboarding_step = 6`, `is_online = true`, `location_updated_at >= now()->subMinutes(10)`, active user, then keep only if `distance <= 10`.
  - **Broadcast booking** (no `vendor_id`): same online/fresh/onboarding/active/category filters for all vendors, excludes "busy" vendors (those already `accepted_vendor_id` on active leads), keeps `distance <= 10`, orders by distance.
  - Creates a `Lead`, fans out `LeadVendor` rows, and sends FCM notifications via `FirebaseService`.

### Distance / geospatial calculation
- SQL Haversine in `CustomerService::distanceSql()` (nearby) and inline in `createBooking()` (booking), both using Earth radius `6371` km.
- PHP Haversine in `CustomerService::calculateDistance()` (used only for display in bookings/accepted-vendors lists).
- SQLite test env registers `acos/cos/sin/radians` so the SQL Haversine runs under tests (`tests/Feature/BookingFlowTest.php:240`).

### Frontend / device geolocation
- **Not present in this repository.** This is a Laravel API backend. The PDF's "Vendor Client App" periodic ping loop and the customer app's "Fetch Map Bounds / Location" are external mobile clients that call these APIs. No browser/JS geolocation acquisition code exists here to exercise (see Phase 5 note in the QA report).

---

## 3. Actual discovered flow

```text
Vendor Client App (external mobile app; periodic ping loop, e.g. every 3 min)
        |
        v
POST /api/v1/vendor/business/update-live-location   { latitude, longitude, is_online }
   (jwt.auth vendor)  ->  VendorBusinessController::updateLiveLocation()
        |
        v
vendor_businesses row updated:
   latitude, longitude, is_online, location_updated_at = now()   (business resolved from JWT user_id)
        |
        v
Customer App fetches map bounds + own location
        |
        v
POST /api/v1/customer/nearby/{group?}   { north, south, east, west, lat, lng, category_id }   (PUBLIC)
   CustomerController::nearby() -> CustomerService::getNearbyVendors()
   filter: onboarding_step=6 AND is_online=true AND location_updated_at >= now-10min
           AND user.is_active=1 AND lat in [south,north] AND lng in [west,east] AND category
   -> returns vendors (Haversine distance computed for sort/display; NO radius cutoff)
        |
        v
POST /api/v1/customer/book   { category_id, description, latitude, longitude, full_address, vendor_id? }
   (jwt.auth customer)  ->  CustomerController::book() -> CustomerService::createBooking()
        |
        +--> vendor_id present  => DIRECT: that vendor only, must be online + fresh(<=10min) + within 10km + same category
        |                                    else "Selected vendor is not available in this area or category"
        |
        +--> vendor_id absent   => BROADCAST: all online + fresh + within 10km + same category vendors,
                                             excluding busy vendors; ordered by distance
        |
        v
Lead created (status=pending; expires_at = +15min direct / +5min broadcast; is_direct flag)
   -> LeadVendor rows (status=pending) -> FCM notifications to eligible vendors
```

---

## 4. PDF requirement mapping

| PDF requirement | Implemented? | Where | Match? |
|---|---|---|---|
| Vendor live-location update endpoint `POST /vendor/business/update-live-location` | YES | `VendorBusinessController::updateLiveLocation` (`:54`) | Matches |
| Request body `{ latitude, longitude, is_online }` | YES | validator `:56` | Matches (see risk: `is_online` optional, defaults `true`) |
| Response `{ success, message:"Live location updated successfully", data:{ is_online, location_updated_at } }` | YES | `:86` | Matches spec exactly |
| `is_online` toggle governs presence | YES | write `:82`, filters in service | Matches |
| `location_updated_at` recency (10-minute freshness) | YES | `now()->subMinutes(10)` in nearby `:66`, direct `:781`, broadcast `:815` | Matches (boundary inclusive `>=`; see risk) |
| ACTIVE = `is_online=true` AND fresh(<=10min) | YES | combined `where` clauses | Matches |
| INACTIVE = `is_online=false` OR stale(>10min) → excluded | YES | filters exclude both | Matches |
| Nearby search `POST /customer/nearby/{group?}` returns online+active within bounding box | YES | `getNearbyVendors` `:31` | Matches (bounding-box; no radius by design) |
| Nearby request `{ north, south, east, west, lat, lng, category_id }` | YES | validator `CustomerController:21` | Matches |
| Booking `POST /customer/book` `{ category_id, description, latitude, longitude, full_address, vendor_id? }` | YES | `book()` `:261` | Matches |
| Broadcast = alert all active online vendors within 10km | YES | `createBooking` broadcast branch, `distance <= 10` | Matches |
| Direct = alert selected vendor only if online + within 10km | YES | `createBooking` direct branch, online+fresh+`distance<=10` | Matches (also enforces category + onboarding) |
| Vendor JWT auth on live-location; Customer JWT auth on book | YES | route middleware `jwt.auth` | Matches |
| (Nearby) auth header | NOT shown in PDF | route is public | PDF shows no auth header for nearby; implementation is public — consistent w/ PDF but see security risk |

---

## 5. Initial risks (pre-testing observations — not yet fixed)

1. **No coordinate range validation** (`updateLiveLocation`, `nearby`, `book`): `latitude`/`longitude` are only `numeric`. Values like `999` / `-500` are accepted (no `-90..90` / `-180..180` bound). PDF does not specify ranges, but this is a robustness gap that can feed the Haversine `acos()` out-of-domain.
2. **`latitude`/`longitude == 0` silently dropped in `book()`** (`CustomerController.php:294-295`): `$request->latitude ? (float)... : null`. A valid `0.0` coordinate (equator / prime meridian) becomes `null`, breaking distance filtering. Real correctness defect (edge coordinates).
3. **Nearby is bounding-box only, booking is 10km-radius** — a vendor beyond 10 km but inside a wide bounding box appears in nearby yet is rejected by direct booking ("not available"). Discovery/booking inconsistency.
4. **Nearby endpoint is public + client-controlled bounding box** — an anonymous caller can pass a world-sized box (`north=90,south=-90,east=180,west=-180`) and enumerate all online vendors' live coordinates (capped at 50). Live-location/PII exposure + enumeration risk.
5. **Freshness boundary inclusive `>=`** at exactly 10 minutes; PDF wording ("within the last 10 minutes") is ambiguous at the boundary. Needs an explicit decision.
6. **`is_online` defaults to `true`** when omitted on update — a vendor cannot push a location update while remaining offline; any ping forces "online".
7. **No `$casts`** on `is_online` / `location_updated_at` in the model — works today (SQL-side comparisons + manual `(bool)` cast) but fragile for future PHP-side logic.
8. **Client-provided customer coordinates are trusted** for the 10km gate (inherent to design) — a customer can self-report coordinates near a vendor to be matched. Not exploitable beyond self-selection, but worth noting.
9. **Performance:** notification/`LeadVendor` loops in `createBooking` access `$business->user` without eager-loading (N+1); no DB indexes on `is_online`, `location_updated_at`, `category_id`, `onboarding_step`, or the coordinate columns used for filtering.
10. **`whereBetween` assumes `south<=north` / `west<=east`** and does not handle antimeridian; swapped/edge inputs silently return nothing.

_No code has been changed. This document records what was discovered before test execution._
