# Google Analytics 4 (Google tag + key events)

## What it does

Measures the public site and the ad landing pages in GA4 (property `G-R6MKJ41J1M`), and reports
the five **key events** the business counts: `sign_up`, `generate_lead`, `book_appointment`,
`qualify_lead` and `purchase`. One submission is one key event: a lead form that also creates an
account reports `generate_lead` (with `new_account`), never a `sign_up` beside it. Page views come from the Google tag in the browser. The key events are sent from the
**server**, at the moment the outcome is certain, for the visitor whose `_ga` cookie is on the
request.

## How it works

- **The tag.** `partials/google-tag.blade.php` is printed by `app.blade.php` (every Inertia page),
  `CinematicSiteController::withSeo()` (the frozen cinematic pages) and `errors/minimal.blade.php`.
  It renders only on `services.google_tag.hosts` (propertylabglobal.com, and propertylab.com.my /
  app.propertylab.com.my, where the ad landing pages run) and never on `services.google_tag.skip_paths`
  (`/manage`, and private links whose token or signature is the credential; GA stores every page's
  full URL). Dev workspaces are not in the host list, so they never send anything.
- **In-app navigation.** The stream's enhanced measurement turns every history change into a
  `page_view`, so `app.js` sends none of its own. `resources/js/utils/googleTag.js` turns an Inertia
  visit from a tagged page into `/manage` into a full page load, which arrives without the tag. The
  one visit it cannot see is the sign-in itself (a POST whose redirect Inertia follows in place), so
  `PasswordlessLoginController::completeLogin()` answers an Inertia sign-in that lands on `/manage`
  with `Inertia::location()` — a full load — instead (2026-11-10).
- **Key events.** `App\Services\Marketing\GoogleAnalyticsConversions::report($event, $params)` reads
  the current request: right host, not a skip path, a `_ga` cookie present, and an API secret
  configured. It queues `SendGoogleAnalyticsEventJob` → `Src\Marketing\Services\GoogleAnalyticsMeasurementProtocol`
  (Measurement Protocol). The event carries the GA client id and session id from `_ga` / `_ga_R6MKJ41J1M`,
  so GA credits it to the visit that led to it. Every event gets a `form` parameter: the route name,
  else the path.

  | Event | Fired from | When |
  |---|---|---|
  | `sign_up` | `Auth\RegisterController` (`verify()` and the no-verification path), when the outcome is `'created'` | A new account was opened on /register. `PasswordlessAuth` reports nothing itself |
  | `generate_lead` | `LandingController` (every landing-page registration, `new_account` yes/no), `EnquiryController` (partner form; contact form only for `business` / `investor` enquiries), Property Match (`new_account`) and Rental Estimate `verify()` | Contact details were handed over. Passes the lead, which keeps the GA client id for `qualify_lead` |
  | `book_appointment` | `ConsultationController::store()`, `Calendar\BookingController::store()`, `PropertyMatchController::booked()` (the first slot only) | A consultation request or booking was made |
| `qualify_lead` | `SyncLeadStatusFromEngagements`, via `GoogleAnalyticsConversions::reportQualifiedLead()` | The lead first climbed to Qualified (or straight to Converted), once per lead |
  | `purchase` | `ReportPurchaseToGoogleAction`, called beside the Meta one from `PurchaseFulfiller::fulfill()` | The gateway confirmed the payment |

- **Purchases** are confirmed by a webhook, which has no browser. So `CheckoutOpener::open()` stores
  the buyer's GA ids on the pending row (`purchase_histories.ga_client_id` / `ga_session_id`), and the
  action reports `purchase` once (`ga_reported_at`) with `transaction_id` = the purchase uuid, value
  and currency. Its one item is named by the product TYPE (`class_basename(payable_type)`, e.g.
  `MembershipTier`), never the purchase title: a /pay link's title is typed by staff and can name the
  customer, and GA's terms forbid personal data. A sale with no stored ids (gateway-hosted link, manual record, backfill) or paid more
  than 72 hours ago (the Measurement Protocol limit) is not reported.
- **Qualified leads** are decided in /manage, days later, with no visitor on the request. So the lead
forms pass their lead to `report()`, which keeps the visitor's client id on it (`leads.ga_client_id`),
and `reportQualifiedLead()` sends `qualify_lead` for that id, once (`leads.ga_qualified_reported_at`),
with `stage` = qualified / converted. It carries no session id, so GA credits it to the user's first
source. Leads that never filled in a form on a tagged host are not reported.
- **Cookies.** gtag.js and the Meta Pixel set their cookies in the browser, unencrypted, so
  `EncryptCookies` must not decrypt them: `_ga*` via `isDisabled()`, `_fbp` / `_fbc` in `$except`.
  Before 2026-11-09 the decrypt step blanked them, which is why `lead_funnels.fbp` was always null.
  Unencrypted, a crafted cookie arrives as sent, and `Request::cookie()` throws on an array
  (`_ga[x]=1`), so these cookies are read as strings only — `GoogleAnalyticsConversions::cookie()`
  and `ReportsMetaConversions::metaCookie()` — never through `$request->cookie()`.
- **Setup outside the code.** `GOOGLE_TAG_API_SECRET` in `.env` (GA → Admin → Data streams → the stream
  → Measurement Protocol API secrets); without it the tag still runs but no key event is sent. The
  five names are marked as key events in GA → Admin → Key events. Register `form`, `funnel` and
  `enquiry_type` as event-scoped custom dimensions to see them in reports.

## Reference usage

```php
use App\Services\Marketing\GoogleAnalyticsConversions;

// After the write has succeeded, inside the visitor's own request:
app(GoogleAnalyticsConversions::class)->report('generate_lead', ['funnel' => $funnel?->name]);
```

Real consumer: `App\Http\Controllers\Main\LandingController::reportConversionToGoogle()`. Never call
it from a queued job or a `/manage` action (it reports nothing there, by design), and never pass a
URL, email, phone or name as a parameter: GA forbids personal data.

## Related files

**Backend**
- `app/Services/Marketing/GoogleAnalyticsConversions.php` — `report()`, `visitor()`
- `src/Marketing/Services/GoogleAnalyticsMeasurementProtocol.php` — the HTTP call, `_ga` cookie parsing
- `app/Jobs/Marketing/SendGoogleAnalyticsEventJob.php`
- `app/Actions/Marketing/ReportPurchaseToGoogleAction.php`
- `app/Http/Middleware/EncryptCookies.php`
- `config/services.php` — `google_tag` (id, api_secret, hosts, skip_paths)
- `app/Http/Controllers/Auth/PasswordlessLoginController.php` — sign-in into `/manage` is a full page load
- Call sites: `app/Http/Controllers/Main/LandingController.php`,
  `app/Http/Controllers/EnquiryController.php`, `app/Http/Controllers/Main/PropertyMatch/PropertyMatchController.php`,
  `app/Http/Controllers/Main/RentalEstimate/RentalEstimateController.php`, `app/Http/Controllers/Main/ConsultationController.php`,
  `app/Http/Controllers/Main/Calendar/BookingController.php`, `app/Services/Payment/CheckoutOpener.php`,
  `app/Services/Payment/PurchaseFulfiller.php`, `app/Http/Controllers/Auth/RegisterController.php`, `app/Actions/SyncLeadStatusFromEngagements.php`

**Frontend**
- `resources/views/partials/google-tag.blade.php`
- `resources/js/utils/googleTag.js` (+ `googleTag.test.js`), registered in `resources/js/app.js`

**Migrations**
- `database/migrations/2026_11_09_100001_add_google_analytics_to_purchase_histories.php`
- `database/migrations/2026_11_09_100002_add_google_analytics_to_leads.php`

**Tests**
- `tests/Feature/Marketing/GoogleAnalyticsConversionsTest.php`, `tests/Feature/Main/GoogleTagTest.php`
