# Ads, Funnel Sessions & Slot Landing — backend logic map

> **Scope.** This map covers six screens for funnel 4 and session 31:
> - **Funnel 4**: id 4, uuid `07ef866f-3b68-4c26-8e77-abd69c707df5`, slug `investment-masterclass`, "1. Trust Nurturing - Property Investment".
> - **Session 31**: id 31, uuid `a988838d-b187-4099-845d-3638c6101db7`, "AI买房训练营 - 14 Oct 2026", slot 5 `ai-masterclass`.
>
> **Sources.** It was compiled on 2026-10-11 from verified read-only slice maps, verifier corrections and gap answers. Where a correction or gap answer contradicted a reader report, the correction or gap answer is used.
>
> **Line numbers** are for the working tree at `/home/zs/peta` unless marked **prod**, meaning `origin/master` as deployed.
>
> **Production figures** are live reads, and each carries its timestamp. They keep changing.

---

## 2026-10-11 changes — read this before §1–§11

Apart from the `meta_leads` notes already edited into §1.1–§1.2, everything below this section was compiled **before** the changes listed here. The changes are in the `dev-shawn` working tree (uncommitted, **not deployed**); production still behaves as mapped until a deploy. Where a row below names a section, that part of the map is **superseded**.

**The owner's decision: ONE CPL rule on every page — CPL = ad spend ÷ landing sign-ups.** It answers open question 6 ("Canonical CPL"): the report CPL's arithmetic won, and the allocated figure became a breakdown detail.

**Production check (2026-09-12 → 10-11):** spend RM 22,975.74 ÷ 343 advertised sign-ups = **RM 66.98**; Ads Manager: RM 64.72 (÷ 355 Results). Under the old Traffics rule (÷ first-touch new leads) the same page read ≈ RM 82.

| Area | Before (as mapped below) | Now | Supersedes |
|---|---|---|---|
| **Shared denominator** (new) | — | `app/Services/Marketing/LandingSignups.php`. A sign-up = a session `event_registrations` row with source LANDING, dated by `created_at`, or a VSL `slot_registrations` row with `marketing_source` FUNNEL, dated by `registered_at`; soft-deleted sessions / slots out. `advertisedTotal(?since, ?until, ?funnelIds, ?slotId)` = every sign-up on a destination where ≥ 1 sign-up (any date) carries a `campaign_id` — the divisor of every TOTAL CPL. `countBy($idCol, ?since, ?until)` = sign-ups carrying each campaign / adset / ad id — the divisor of a ROW CPL. Rows therefore never add up to the total (the gap is untagged sign-ups on advertised pages). | §8.1 #2, #3, #6 as CPL divisors |
| **`meta_leads`** | Σ of lead-action aliases → exactly ×2 | Ads Manager's **Results** (complete registrations + Instant Form leads), each alias family counted once (`FacebookAdsService::resultCount()`); Graph fetched in 7-day slices so `--days=180` works. Every label reads **"Meta results"** / **"Results in Ads Manager"**; the column / prop key stays `meta_leads`. Old rows stay doubled until `php artisan meta:sync-ad-insights --days=180` runs after deploy. | §1.2 (heading already updated), every "Meta leads" / "Leads in Ads Manager" label in §2–§5, §10.1 `:147`, open question 3 |
| **Traffics** | CPL = spend ÷ first-touch `leads` (rows and tile); tile "Leads ours / Meta"; Return view had a CPL column | Row: `signups` = `countBy`, **`cpl` = spend ÷ signups**, `cost_per_new_lead` = spend ÷ leads; rows with sign-ups (or new leads) but no stored spend are appended. Totals: `signups` = `advertisedTotal(since, until)`, `cpl` = spend ÷ signups, `cost_per_new_lead`. Tiles: **Sign-ups** "/ N Meta results", **CPL** with "Cost per new lead" under it. Delivery: … CPC, Meta results, Sign-ups, CPL. Return: Spend, Meta results, **New leads**, Buyers, Conv., Revenue, ROAS, Profit (**no CPL**). `leads` is renamed "New leads" in the UI and still drives Buyers / Conv. / Revenue / ROAS. `MetricInfoButton`: CPL rewritten; new `signups` / `new_leads` entries; CTR / CPC now say they use Meta's Link clicks = Ads Manager's *CTR (link click-through rate)* / *CPC (cost per link click)*. `RoasInfoButton` example: "45 new leads → cost per new lead RM 66.67". | §2.3 steps 7, 8, 11, 14 (columns, tiles); §2.4 Leads-tile, CPL-tile, Row Our leads, Row CPL rows; §2.6 "Appended no-spend rows"; §8.1 #3 CPL; §10.3 `MetricInfoButton` bullet |
| **Operations** (`/manage/operations`, not mapped below) | Cost per lead = Σ spend ÷ Σ row leads | `kpis.cpl` = spend ÷ `advertisedTotal` for each period (current and comparison); new `kpis.signups`, `kpis.cost_per_new_lead`; `kpis.leads` kept for "N from ads" and "Ad lead → registered". 11 ad cards (Meta results / Sign-ups / Cost per lead / New leads …); campaign table gains Sign-ups + New leads; scoreboard sub-line "… spend ÷ N landing sign-ups". | — |
| **Sessions tab** | "report CPL", printed "÷ N landing"; "—" tooltips blamed the sync | Same number (`reportCplForEvents`), now **the** session CPL. Printed "÷ N in window". Ad spend / CPL / ROAS "—" tooltips name the real cause (no window · no tagged landing sign-up · no stored spend · no sign-up in the window · non-MYR sales). Search placeholder "Search session or status…". | §3.4 CPL row label; §3.6 bullets 1–4 and "Search"; §10.2 `SessionsTab.vue` rows |
| **Summary tab** | Report CPL + an "Allocated Session CPL" footnote; date editor pinned the window on a budget-only edit | One CPL; the allocated footnote is gone (`SessionSummaryService` still computes `allocated_cpl`, unread). The editor sends dates only when one changed or the window was already manual. "Results in Ads Manager". | §4.5 "Allocated Session CPL" row and "Leads in Ads Manager" row; §4.7 bullet 1 (Summary half) |
| **Ads tab** | Tiles = allocated `cplForEvents` headline, missing when the grain had no tagged rows; separate "Spent promoting" card | `headline` (built by `headlineForEvent()` → `reportCplForEvents()`) is on **every** response: three tiles **Ad spend** (promotion window, campaigns, *Manually set*, *Change dates*) · **Landing sign-ups** in the window · **Session CPL**, each "—" explained. Below: **"Allocated breakdown by {grain}"** (not the session's CPL) with the grain switch; columns Sign-ups / Allocated / Per sign-up and "This {grain}, every session — {first → last sign-up day}" (Spend / Impr. / CTR / Meta results); `total` gains `since` / `until`; footnotes rewritten (why Allocated < Spend). *Change dates* no longer sends `promo_budget`. | §5.3 steps 4b, 4j, 9; §5.4 "Spent promoting" and the three Tile rows; §5.5; §5.6 bullets "Two CPLs under one name", "Footnotes", "Switching to the Ad set or Ad grain"; §10.3 `AdsTab.vue` bullets |
| **Funnel Dashboard** | KPI CPL = spend ÷ distinct `lead_funnels` people (organic included); session column = allocated `ad_cpl`, whose `CplInfoButton` was never imported (no "?" rendered) | KPI CPL = scope spend ÷ `advertisedTotal(since, until, funnel, slot)` (`kpis.signups`); session column = `report_cpl` / `report_leads` (`ad_leads` / `ad_spend` / `ad_cpl` removed from its rows); the column's "?" renders; "Results in Ads Manager". Spend scope unchanged. | §8.1 #6 (CPL), #8; §8.2 group C; §10.3 Dashboard rows |
| **VSL Summary / Ads tabs** | CPL = spend ÷ ALL landing leads; row CPL = the object's whole spend ÷ the leads it brought THIS funnel | KPI and tiles = spend ÷ `advertisedTotal(null, null, funnel, slot)`; row CPL = whole synced spend ÷ `countBy($idCol, null, null)` (sign-ups carrying the id on ANY page); new Sign-ups column; bands "This page" / "This {grain} — all synced days, every page"; "Meta results". | §10.3 `VslAdsTab` / `VslSummaryTab` "not checked" |
| **`CplInfoButton`** | Explained only the allocation | Rewritten to the one rule (one session, a total, a VSL row, why it differs from Ads Manager, when "—", allocated ≠ CPL); right for every mount point | §3.6 bullet 1; §10.3 first block |
| **Promotion-window writes** | Until stored 00:00 → resolved a day early on every save; `after:`; Ads tab wiped `promo_budget`; flash read the request | `EventRepository::update()` → `promoBoundary()`: a date-only From = 00:00:00, Until = 23:59:59; `after_or_equal` (From = Until is one day); `promo_budget` written only when the key is sent; the flash names what changed on the row. | §1.5 "Until set through a date editor" row; §4.6; §4.7 bullet 1; §5.5; open question 8 (first two parts) |
| **`SessionAdInsightsService`** | `cplForEvents()` = "the number three screens must agree on" | `reportCplForEvents($ids, ?$promotion)` is THE session CPL; `cplForEvents()` is allocated detail only; docblocks rewritten (promotion spend IS the CPL numerator, never the allocation's; session revenue ≠ cohort ROAS). | §8.2 groups B–C; §10.2 rows for `SessionAdInsightsService.php` |

**Figures that now always agree** (replaces §8.2 B and C):
- **Session CPL:** Sessions tab = Summary CPL card = Ads tab headline = Funnel Dashboard session column — all `reportCplForEvents()`.
- **Overall CPL for the same dates:** Traffics headline (campaign grain) = Operations Cost per lead — both Σ `rollup('campaign')` spend ÷ `advertisedTotal()`. The Funnel Dashboard's all-funnels KPI uses the same divisor but its own spend scope (campaigns seen on in-range `lead_funnels` rows + tied ones), so it can read differently.

**Tests touched:** new `tests/Feature/Marketing/LandingSignupsTest.php`; `AdPerformanceTest::test_cpl_divides_spend_by_landing_signups_not_new_leads`; `TrafficsPageTest::test_the_headline_cpl_divides_spend_by_every_advertised_signup`; `OperationsDashboardTest::test_cost_per_lead_divides_ad_spend_by_landing_signups`; `FunnelDashboardTest::test_the_kpi_cpl_divides_spend_by_advertised_sign_ups`; `SessionAdInsightsTest::test_the_ads_tab_headline_is_the_session_cpl_and_survives_an_empty_grain` (replaces `test_the_headline_tiles_never_move_when_the_grain_does`); `SessionPromotionWindowTest::test_typed_dates_save_as_whole_days_and_resolve_to_themselves` + `test_a_dates_only_save_keeps_the_push_budget`. Separately, `MetaPixelCapiTest` and `ConsultationCapiTest` were re-fixtured onto slots after the slot refactor (1b58c06a6) made them 404.

**Still open after these changes:**
- **Ads tab *Change dates* still pins an automatic window**: it pre-fills `headline.since` / `until` and always posts them (`AdsTab.vue` `openWindowEditor` / `saveWindow`). The Summary editor's changed-or-already-manual check was not ported.
- **Operations *Set targets* hint** (`TargetsModal.vue`) still reads "ad spend ÷ leads from ads", and any CPL target saved before today was set against the old, higher figure.
- **Dead allocated work:** `FunnelsController@show` still builds `ad_leads` / `ad_spend` / `ad_cpl` (nothing reads them; its comment says the Dashboard does) and runs `promotionSpendForEvents()` twice; `SessionSummaryService` still computes `allocated_cpl`; `EventsController@adInsights` still returns `promotion`, which the Ads tab no longer reads.
- **Dashboard spend scope** is unchanged: a campaign that brought no `lead_funnels` row in range is invisible there, unlike Traffics' store-wide spend.
- **Operations "Ad lead → registered"** still divides by new leads — a separate decision.
- **Tests left red by the slot refactor (not today's CPL change):** `ThankYouPageTest` (3), `VslCallerRotationTest` (10), `VslFunnelManageTest` (34 before today; its CPL assertions now need `slot_registrations` fixtures), `MarketingRoleTest` (2, `vslCallers` / `vslLeads` props).
- **Production:** deploy, then run `php artisan meta:sync-ad-insights --days=180` once.

---

## 0. Read this first: two stacks behind one set of URLs

### 0.1 Which code and which data you are looking at

| | **Production** | **zs.propertylab.com.my (Shawn)** |
|---|---|---|
| Code | `origin/master` @ 189442cb9 (2026-10-10). Local `origin/master` was fetched 2026-10-11 04:40 UTC, so a newer deploy cannot be ruled out. | Uncommitted working tree on `dev-shawn` (536 changed paths). `peta-zs-app.service` runs with `WorkingDirectory=/home/zs/peta`. |
| Database | `petav3` | `peta_zs_dev` on host 34.87.149.195 (no cached config, so `.env` is read on every request) |
| Data freshness | Live; Meta sync runs hourly | **Frozen.** Latest `meta_ad_insights.date` is 2026-10-08 and the last write was 2026-10-08 01:01. Event 31 has 84 registrations, the latest at 2026-10-07 01:08:53. The zs scheduler runs only a heartbeat, and the zs queue workers have no network access (PrivateNetwork). |
| Migrations `2026_10_04_100006` (reminders_muted_at), `2026_10_07_190000` (slot_registrations, slot_landing_aliases, `context_event_id`), `2026_10_08_160000` (event_registration_removals) | **None applied.** None of these tables or columns exist. | **All applied** (batches 125, 127, 130). |
| `funnels:upgrade-slots --apply` | Never run; the command does not exist in prod code | Done: `slot_operation_upgrades` = `slot-operations-v1`, 2026-10-08 08:13:14 |

The committed `dev-shawn` HEAD (5310dc4f6) is deployed **nowhere**. It is 6 commits behind and 3 ahead of `origin/master`.

### 0.2 Files behind these pages

| File | Lines (prod / master / HEAD / WT) | Prod = working tree? |
|---|---|---|
| `app/Http/Controllers/Manage/Marketing/CampaignsController.php` | 553 / 553 / 553 / 553 | **Yes** (identical git hash) |
| `app/Services/Marketing/AdPerformanceService.php` | 280 ×4 | **Yes** |
| `app/Services/Marketing/SessionAdInsightsService.php` | 961 ×4 | **Yes** |
| `app/Services/Marketing/SessionSummaryService.php` | 612 ×4 | **Yes** |
| `src/Event/Support/SessionPromotionWindow.php` | 185 ×4 | **Yes** |
| `app/Http/Controllers/Manage/Events/FunnelsController.php` | 3329 / 3329 / 3526 / 3572 | No |
| `app/Http/Controllers/Manage/Events/EventsController.php` | 1380 / 1380 / 1393 / 1396 | No |
| `app/Http/Controllers/Main/LandingController.php` | 1004 / 1004 / 1007 / 1097 | No |
| `app/Actions/RegisterLeadAction.php` | 477 / 477 / 491 / 502 | No |
| `app/Actions/DispatchFunnelWelcomeAction.php` | 192 / 192 / 207 / 225 | No |
| `src/Event/Repositories/EventRegistrationRepository.php` | 294 / 294 / 337 / 438 | No |

**What this means:**
- The **same code in both places**: Traffics, the Ads tab, the Summary tab, the promotion window, and the Sessions-tab spend/CPL formulas. In FunnelsController the Sessions-tab spend block, the landing count and `transformSession` are logically identical. Their line numbers are WT 313-327 / 331-341 / 3444 versus **prod** 276-290 / 294-304 / 3211.
- **Version-specific**: registration writes, landing routing, welcome scope, the Messages band, removals and muted reminders.

### 0.3 What behaves differently

| Behaviour | Production (`origin/master`) | Working tree |
|---|---|---|
| Funnel-wide auto-enrol | **Live.** `RegisterLeadAction.php:250-251` (prod) calls `enrollSessions->execute`. That gives a `SOURCE_LANDING` row with the same ad snapshot in every upcoming public session of the funnel (`EnrollLeadInFunnelSessionsAction.php:58-59,70`). | **Removed.** `RegisterLeadAction.php:234-261` has no `else` branch. The action is still injected at :57 but never called. The comments at :231 and :257-259 are now stale. |
| `/{slug}` | Renders the funnel design via `renderLanding` (**prod** `LandingController.php:50-59`) | 302 to a slot via `PublicSlotResolver` (`LandingController.php:53-57`). `renderLanding` (:528) has no caller. |
| `slot_registrations` | Not referenced | Written at `RegisterLeadAction.php:168-174` |
| Welcome scope (`chooseScope`) | Slot rules, otherwise funnel-wide rules (**prod** `DispatchFunnelWelcomeAction.php:186-191`) | **Slot rules only** (`:221-224`). With no slot, nothing is sent. `:155` also skips the AI call when the registration did not come from a landing. |
| Messages band ledger filter | `event_id = X OR event_id IS NULL` (**prod** `EventsController.php:331`) | `event_id = X OR context_event_id = X OR (both NULL)` (`:332`) |
| Session page props | — | Adds `has_zoom_webinar` (887), `slot_uuid`, `landing_url` (900-901), `funnel.has_candidate_source`, `reminders_muted_at` (1026) |
| Remove registration | Plain delete (**prod** `EventRegistrationRepository.php:288-293`) | Tombstone in `event_registration_removals`, plus an optional Zoom delete (`:393-437`) |
| Funnel `landing_url` prop | `'/' . slug` (**prod** FunnelsController 3185) | `null` (WT 3418) |
| Merged-funnel redirect on the funnel hub | — | `FunnelsController.php:268-273` |
| Prod-only code | `LandingController` has `nextRegisterableSession` (**prod** :355, :532; commit 543e5bf97). Its logic was **not traced** in this map. | — |

### 0.4 `?suite=other`

It never changes a number. `PreservesSuite::currentSuite` is the only reader (`app/Http/Controllers/Concerns/PreservesSuite.php:50-61`). It takes the request's `?suite=`, otherwise the Referer's, and only if the value is one of `project / focus / other / appointment / ceo`. It is used in four places:

1. **Traffics**, only on the redirect that fires when no active Facebook integration exists (`CampaignsController.php:72-74`; `PreservesSuite.php:93-96`).
2. **Funnel hub**, only on the merged-funnel redirect, and only in the working tree (`FunnelsController.php:268-273`).
3. **Session Show**: `backUrl` via `ResolvesBackUrl.php:55-61`. When a suite is appended, the fallback no longer equals the bare index path, so `?tab=sessions` is **not** appended (`EventsController.php:105-108`). The back link then opens the funnel without the Sessions tab.
4. Nothing on the landing or registration side reads it: there is no `suite` in LandingController, PublicSlotResolver, SlotLanding.vue, RegisterLeadAction, ThankYouController, RegisterRequest or ConsultationController (grep). `/summary` and `/ad-insights` do not read it either (`EventsController.php:488-558`).

### 0.5 True on every page

- **No staff, test or merged-lead exclusion anywhere.**
  - Traffics never joins `leads` (`AdPerformanceService.php:203-236`).
  - The session queries filter only on `event_id` and `source` (`SessionAdInsightsService.php:105-107, :233-235, :350-354, :573-575, :878-889`).
  - The Summary `$regs` has no `is_staff` filter (`SessionSummaryService.php:70-75`).
  - `Lead` and `User` register no global scope (`src/Lead/Lead.php:192`, `src/People/User.php:114`).
- **No group/team scoping.**
  - Traffics: everyone with `view-marketing` sees every ad account and every attributed payment. `facebook_integrations.group_id` is unused there.
  - Session pages: any admin with `view-events` or `view-events-reports` can open any session by uuid.
  - Roster: anyone with **any** `view-leads-*` level sees **every** registrant (`EventsController.php:149, :229`).
- **No `Cache::` / `remember(`** in AdPerformanceService, SessionAdInsightsService, FunnelDashboardService, SessionSummaryService, SessionPromotionWindow, MetaAdLabelResolver or DashboardController (grep). The exceptions are:
  - Traffics' Sync-now flag (`CampaignsController.php:154, :169`).
  - `FunnelsController.php:1115` (`resolveGroupJid`, which serves a different route).
  - Zoom live participants, cached for 15 s.
  - Settings are read straight from the database on every call (`Setting.php:134-139`).
- **No live Meta Graph call on any request path of these pages.**
  - Graph is called only by the scheduled syncs, by Sync now, and by `ResolveMetaAdRefsJob`, which is queued at registration.
  - Session pages read stored spend only. The comments say so: `FunnelsController.php:310-311` ("LOCAL spend store only — zero Graph calls") and `routes/web.php:1056-1057`.

---

## 1. Shared building blocks

### 1.1 The Meta ad store

**Tables**

- **`meta_ad_insights`** (`src/Marketing/MetaAdInsight.php:29`) holds one row per ad per day.
  - Upsert key: `(date, ad_id)` (`SyncMetaAdInsights.php:160-166`). The update list at :164-165 leaves `created_at` alone, so `created_at` records the first insert.
  - `reach` is stored but never summed or shown (`MetaAdInsight.php:60-71, :78-83`).
  - The `*_name` columns are read **only** by Traffics.

**Writer: `meta:sync-ad-insights`** (`app/Console/Commands/Marketing/SyncMetaAdInsights.php`)

- **Accounts.** It takes the `facebook_ad_accounts` of ACTIVE integrations and applies `->unique('account_id')` with **no ordering** (:55-68). There is no `account_status` filter.
  - The comment at :53-54 says System User tokens are tried first. That is false: the first row in default order wins, which today is integration 8.
  - If the chosen row's token is dead, that account fails even when another integration could read it.
- **Graph request.** `GET act_X/insights` with `level=ad`, `time_increment=1`, `time_range {since, until}` and **no timezone parameter** (`src/Marketing/Services/FacebookAdsService.php:473-536`, :488-499).
  - Fields: campaign_id, adset_id, ad_id, spend, impressions, clicks, inline_link_clicks, reach, account_currency, actions.
  - `limit=500`, with a 200-page paging guard (:503-526).
- **Row mapping.**
  - Rows without `ad_id` or `date_start` are skipped (:129-133).
  - `date = date_start` (:134), which is the **ad account's day** (migration `2026_07_29_210001:39`).
  - `campaign_id` and `adset_id` are `(string)($row[...] ?? '')` (:136-137), so a missing id is stored as `''`.
  - `link_clicks = inline_link_clicks` (:145).
  - `currency = account_currency ?? 'MYR'` (:148). The column default is MYR (migration :58).
  - `meta_leads` = `FacebookAdsService::resultCount()`: per family in `RESULT_ACTION_FAMILIES` (website complete registration; Instant Form lead) the first alias present, never summed. **Fixed 2026-10-11** — before that it summed `LEAD_ACTION_TYPES` (`lead` + `offsite_conversion.fb_pixel_lead` + …) and stored exactly 2× (see §1.2). The raw `actions` array is discarded.
- **Window.** Default `--days=7` (:35): `since = now()->subDays(6)`, `until = now()`, in app time (:50-51).
- **Failures.** A failing account is skipped softly, and the pages already fetched are still written. Rows are never deleted, so an ad-day row that Meta later drops stays stale.

**Schedule** (`app/Console/Kernel.php`)

- Insights: hourly, `->timezone('Asia/Kuala_Lumpur')`, `withoutOverlapping`, `->when(active integration exists)` (:541-545).
- Settings: `meta:sync-ad-settings` every 4 hours, gated the same way (:554-557).
- If the token expires, spend silently stops updating. No session page shows that anything is wrong.

**`meta:sync-ad-settings`** (`SyncMetaAdSettings.php:48-128`)

- Reads the campaigns, adsets, ads, customaudiences and adimages edges, and upserts:
  - `meta_ad_settings`, unique on (level, meta_id) (migration `2026_08_03_000001:74`);
  - `meta_custom_audiences` on (account_id, meta_id);
  - `meta_ad_images` on (account_id, image_hash).
- Never deletes, so archived or deleted objects keep their last-synced status.
- Uses the same unordered account pick (:50-63).

**Sync now**

- `SyncMetaAdDataJob` (`app/Jobs/Marketing/SyncMetaAdDataJob.php:37-45`):
  - runs `Artisan::call('meta:sync-ad-insights', --days=3)` (:40), then `meta:sync-ad-settings` (:41);
  - `Cache::forget(flag)` in `finally`;
  - `tries=1`, `timeout=1800`, no queue set, so it runs on the default queue.

**Display names**

- **Session pages** use `MetaAdLabelResolver` (`app/Services/Marketing/MetaAdLabelResolver.php`):
  - `meta_ad_refs` where name is not null, keyed by `level:meta_id`, with no staleness check (:54-58);
  - then `meta_ad_settings` at the same level (:63-79);
  - then `meta_campaigns`, for campaigns only (:84-95).
- `meta_ad_refs` is filled by the queued `ResolveMetaAdRefsJob` (§7.7).
- **Traffics** instead reads `MAX(campaign_name | adset_name | ad_name)` straight from `meta_ad_insights` (`AdPerformanceService.php:45-49, :137`).

### 1.2 Ad-account timezone, currency, and the doubled `meta_leads`

**Timezone and currency are not stored.**
- `facebook_ad_accounts` holds only `integration_id, account_id, account_name, account_status, blame, timestamps` (migration `2026_06_10_100003…:11-24`; `src/Facebook/FacebookAdAccount.php:19-26`).
- `facebook_integrations` has no such columns, and `metadata` holds only `connected_at`.
- The connect flow asks Graph for `id,name,account_status` only (`app/Helpers/FacebookClient.php:278-282`; `FacebookAdAccountRepository.php:22-40`).
- The only currency column on the Meta side is `meta_ad_insights.currency`, and no reader groups by it.

**Production data (2026-10-11)**

| Account | Currency | Days | Spend | `meta_leads` |
|---|---|---|---|---|
| `act_385479768703987` (FMX) | MYR | 2026-03-03 → 10-11 | 154,749.60 | 2,816 |
| `act_264115421784900` (MKT) | MYR | 2026-04-01 → 07-20 | 55,828.03 | 0 |

- `SELECT DISTINCT currency` returns only `MYR` (3,922 rows).
- A stored `MYR` cannot be told apart from the fallback.
- There are 23 `facebook_ad_accounts` rows (20 unique ids) across integrations 8 and 9. Any of them that starts spending, in any currency, will land in the same sums.

**Timezone (inferred, not stored).** For FMX, every same-day first insert happened 60–121 minutes after midnight MYT. That fits UTC+8; ±1 hour cannot be excluded. Confirming it needs one Graph read of `timezone_name`.

**`meta_leads` was ×2 — CONFIRMED against live Graph 2026-10-11 and FIXED the same day** (now counts complete registrations once; old rows need `meta:sync-ad-insights --days=180`).
- All 322 production rows with `meta_leads > 0` are even numbers, with a minimum of 2.
- All of them come from ad sets optimised for the pixel `COMPLETE_REGISTRATION`.
- The thank-you page fires the pixel `Lead` event (`ThankYou.vue:194`). Meta likely reports that as both `lead` and `offsite_conversion.fb_pixel_lead`, and both are summed.
- A test pins `lead=3` + `onsite_conversion.lead_grouped=2` → 5 (`tests/Feature/Marketing/SyncMetaAdInsightsTest.php:183-192`).
- Cross-check: Sep 688 (half = 344) against 307 landing registrations; Oct 282 (half = 141) against 136.
- This affects every "Meta leads" / "Leads in Ads Manager" figure: `MetaAdInsight.php:82`, `SessionAdInsightsService.php:946`, `SessionSummaryService.php:101-105`, `FunnelDashboardService.php:295, :414`.

### 1.3 Dates and timezones

- `app.timezone` = `APP_TIMEZONE`, default and set to `Asia/Kuala_Lumpur` (`config/app.php:78`; `.env:16`). Session start and end times use `app.user_timezone` (`config/app.php:80`; `Event::startsAt` at `Event.php:178-185`).

| Field | Time basis |
|---|---|
| `meta_ad_insights.date` | Ad account's day |
| `lead_funnels.registered_at` | MYT; **nullable** (migration `2026_06_18_000002:21`) |
| `event_registrations.created_at` | MYT; this is the column **all session CPL maths** use |
| `event_registrations.registered_at` | Shown on the roster; MYT wall clock in a TIMESTAMP column (DB session tz is UTC), emitted as ISO with +08:00 |
| `purchase_histories.purchased_at` | MYT wall-clock `datetime` (§1.6) |

- Day keys are compared **as strings**. They line up only if the ad account is on UTC+8.

### 1.4 Session status: `Event::live_status` and the Zoom webinar state machine

**`live_status`** (`src/Event/Event.php:211-246`), checked in this order:
1. `status = 3` → `cancelled` (:215).
2. `status = 2` → `past` (:219).
3. Zoom mode with a webinar (`hasOne(ZoomWebinar)->latestOfMany()`, :156-159): ENDED → `past` (:224), LIVE → `live` (:227).
4. Otherwise the clock decides, with times parsed in `user_timezone` (:176-196): `now ≥ end` → `past` (:238), `now ≥ start` → `live` (:241), otherwise `upcoming`.

**Zoom statuses** (`src/Zoom/ZoomWebinar.php:48-55`): UPCOMING 1, LIVE 2, ENDED 3, CANCELLED 4, CREATING 5, FAILED 6.

| Transition | Writer | Trigger |
|---|---|---|
| → LIVE | `ZoomWebinarRepository.php:609` (`markLive`) | **Only** the `webinar.started` webhook (`ZoomWebhookController.php:405`), guarded by `status !== UPCOMING → return` (:401) |
| → ENDED | `:641` (`markEnded`; `ended_at` keeps the first value, :645) | **Only** the `webinar.ended` webhook (`ZoomWebhookController.php:428-429`) and the manual `php artisan zoom:recover-webinar <id>` (`RecoverZoomWebinar.php:162-165`) |
| → CANCELLED | `:547` (`cancel()`) | **Dead code**: no caller |

- **No scheduled fallback exists.** `webinar.ended` also completes a SCHEDULED event (`EventRepository::complete`, `:437-440`), snapshots the offers (:446-448) and queues `ReconcileWebinarAttendance` with a 5-minute delay (:467).
- `webinar.deleted` is ignored (:161-162). Zoom-side CANCELLED is never written, so `live_status` treats any status-4 row like UPCOMING.

**If `started` arrived but `ended` was lost**, the session reads `'live'` **forever**. The knock-on effects:
- The landing skips it (only `LIVE_UPCOMING` is accepted).
- On the Registrations tab, `isFinalized` stays false and the Unknown-people card never shows (`RegistrationsTab.vue:59-61`).
- Every Session Show page load by a full-view user makes a live Zoom call (`EventsController.php:765-767, :1218`).
- `zoom:sync-live-qa` polls every minute with no time limit (`ZoomSyncLiveQa.php:50`).
- After-ended funnel rules never send (`SessionDueWindow.php:133-135`).

**Ways out:**
- `zoom:recover-webinar` backdates `ended_at`. If it is run more than about 60 minutes late, after-ended messages never fire (`SessionDueWindow.php:189-193`).
- Setting the event to Completed by hand only fixes `live_status`.

### 1.5 The promotion window (`src/Event/Support/SessionPromotionWindow.php`)

**Siblings** (`forEvents`, :99-120): `Event::whereIn('event_series_id')`, with soft-deleted rows excluded and **no status filter**. A cancelled sibling therefore still counts.

**End** (:63): `promo_ends_at ?: startsAt()`. If that resolves to null, the window is all-null with `is_resolvable=false` (:68-74).

**Start** (:64): `promo_starts_at ?: previousStart()`.
- `previousStart` (:131-149) is the latest sibling `startsAt` **strictly** before this one (`lt`, :146), excluding self.
- It is null with no start time or no `event_series_id` (:135-137).

**Start fallback** (:79): `$endsAt->copy()->startOfDay()`. That is the day of the **resolved end**, which is the session's own day unless `promo_ends_at` is set.

**Day ownership** (:163-184):
- `hoursOwned = isEnd ? at->hour : 24 − at->hour` (:173). Minutes are ignored, so 11:59 counts as 11.
- `≥ 12` keeps the day (:175-177). Otherwise the end moves back a day (`subDay`) and the start moves forward a day (`addDay`) (:181-183).

**`is_manual`** = `promo_starts_at !== null || promo_ends_at !== null` (:61). The `promo_*` columns are cast `datetime` (`Event.php:102-103`).

**Consequences**

| Situation | Result |
|---|---|
| Handover at 12:00–12:59 | **Both** windows keep the changeover day, so its spend is counted twice. The docblock at :33-35 and :155 says "never counts one day twice", which is drift. |
| Morning session (start < 12:00) that is first in its slot, or whose predecessor started the evening before | `since` = its own day, `until` = the previous day. The window is inverted but `is_resolvable=true`, so spend = 0.00 and CPL = '—'. |
| "Until" set through a `<input type=date>` editor | Saved as 00:00 (no mutator). `hour = 0 < 12`, so `until` = typed date − 1. Re-saving unchanged moves it back again. |
| Cancelled sibling | Acts as a boundary. Spend during its stretch goes to the cancelled row. |

**Session 31 (prod, 2026-10-11 17:29 MYT)**
- The previous sibling is **session 23** (2026-09-30 20:00, status 2, not deleted).
- Event 24 (also 2026-10-14 20:00) was soft-deleted on 2026-09-17, so it is excluded. No cancelled sibling sits in between.
- Start-day test: 24 − 20 = 4 hours < 12, so **since = 2026-10-01**. End-day test: 20 hours, so **until = 2026-10-14**.
- No `promo_*` overrides are set.

### 1.6 Money: what a `purchase_histories` row means, and how a sale is credited to a session

**Row semantics**
- `total_amount` is **gross**: no discount, SST or gateway-fee columns or code.
- Every writer sets `quantity=1` and `price=total_amount`.
- Payable types are **Membership, Project (a project fee that opens an engagement), and Course** only. Touch 'n Go rows can have a null payable and a null `lead_id` (`TngLedger.php:77-83`). Property-booking money is **not** in this table.
- There is no concept of instalments or deposits, but several ACTIVE rows for the same lead and payable are all summed.
- `purchased_at` is MYT wall clock. For Stripe it is the checkout session's `created` time, not the settlement time.

**Refunds**
- A refund is a status flip to INACTIVE (`PurchaseHistoryRepository.php:376-384`) at the full amount, and the row keeps its original `purchased_at`. A refund this month therefore removes revenue from the window the sale was booked in.
- **Partial refunds**:
  - The live webhook keeps the row ACTIVE at the full amount (`WebhookProcessor.php:446-456`).
  - A hosted-link import or re-import marks the **whole** row INACTIVE (`:357-366, :399-402`).
- Disputes, PayEx refunds and TnG outflows are not handled.
- There is no refund route. Manual and TnG rows can only be soft-deleted, or have their amount overwritten (TnG is locked).

**Readers on these pages** all filter `status = ACTIVE` only:
- `AdPerformanceService.php:213-220` (raw SQL with `deleted_at IS NULL`);
- `CampaignsController.php:285-288`;
- `SessionAdInsightsService.php:473-475`;
- `FunnelDashboardService.php:123-126`.

The currency accessor `currency_code` falls back to MYR (`PurchaseHistory.php:407-410`).

**Crediting a sale to a session** (`app/Services/Marketing/PurchaseSessionAttributor.php:62-98`)
- **When it runs.** On the first `PurchaseFulfiller::fulfill()` (`PurchaseFulfiller.php:88`) that finds the row ACTIVE, with no `event_attributed_at`, a non-zero `lead_id` and a non-null `purchased_at`. If any of these is missing, a later fulfill retries.
- **Rules, in order:**
  1. **CTA tap**: the latest `whatsapp_cta_touches` row for this lead with a non-null `event_id` and `touched_at ≤ purchased_at`. It does **not** check whether that event is soft-deleted (:111-122).
  2. **Last attended**: `event_registrations.status = ATTENDED`, `COALESCE(attended_at, events.scheduled_date) ≤ purchased_at`, `events.deleted_at IS NULL`, latest first (:141-156).
  3. **None**: `event_id = null` is stamped with `event_attributed_at = now()` (:96).
- **Write**: `PurchaseHistoryRepository.php:177-188` (forceFill).
- **Re-deciding.** The unscheduled `purchases:backfill-sessions` command stamps old rows, and `--force` clears and re-decides them (`BackfillPurchaseSessions.php:43-99`).
- `EVENT_ATTRIBUTION_MANUAL` (3, "Set by admin") is declared (`PurchaseHistory.php:192, 202`) but nothing writes it.

### 1.7 Attribution rows and their first-touch grain

**`lead_funnels`** (funnel grain)
- `firstOrCreate(lead_id, event_funnel_id)` with no update afterwards (`src/Lead/Repositories/LeadFunnelRepository.php:61-65`). The docblock at :20-21 says it "refreshes registered_at"; it does not.
- Unique on (lead_id, event_funnel_id) (migration `2026_06_18_000002:45`). `event_funnel_id` is nullable (:20), so a lead can hold several NULL-funnel rows.
- **It is not immutable:**
  - **Lead merge** (`LeadRepository::mergeLeadFunnels`, :2439-2475):
    - NULL-funnel loser rows are re-pointed with no collision check (:2444-2447).
    - On a collision, the 17-column attribution group (marketing_source, utm_*, fbclid, fbp, fbc, ad_id, adset_id, campaign_id, placement, referrer_url, landing_url, ip_address, user_agent) is copied **whole**, and only if **every** column is blank on the kept row (`blankFills` :1779-1796).
    - `registered_at` becomes the earlier of the two (`pickStamp` :2244-2251, :2470).
    - The loser row is deleted (:2472-2473), so a kept row with any organic landing_url, IP or UA loses the loser's ad ids.
  - **Import backdate** rewrites every `registered_at` of the lead (`LeadRepository.php:424`).
  - **Funnel merge** moves rows between funnels (`FunnelMergeRepository.php:145`).

**`slot_registrations`** (slot grain, **working tree only**)
- `firstOrCreate(lead_id, event_series_id)`. It is seeded from the `lead_funnels` row's fillable attributes, then **overridden by this visit's tracking, nulls included**, because `data_only` keeps null keys (`SlotRegistrationRepository.php:16-32`; `diver/Helpers/Data.php:12-31`).
- Lead merge does not re-point it (IdentityChildMap has no `slot_*` entries). `mergeLeadFunnels` can delete the `lead_funnels` row that its `lead_funnel_id` points at.

**`event_registrations`** (session grain)
- Unique on **(event_id, lead_id)**, which is per lead, not per human (migration `2026_06_29_000003:215`). No soft deletes (`EventRegistration.php:22`).
- Sources: LANDING 1, ADMIN 2, WALK_IN 3, ZOOM 4, IMPORT 5, FROM_PREVIEW 6. Statuses: REGISTERED 1, ATTENDED 2, NO_SHOW 3 (`EventRegistration.php:27-62`).
- `join()` (`EventRegistrationRepository.php:35-87`) returns an existing row unchanged (:61-65). Ad columns are written only on create (:72-83). So the ad snapshot is first-touch per session.
- **Other writers of the ad columns:**
  - Merge `foldRegistration` (`LeadRepository.php:2395-2424`) blank-fills `campaign_id, adset_id, ad_id, placement` as **one group**, only when all four are blank on the winner.
  - Data-fix migration `2026_08_03_100001` retro-NULLed `{{macro}}` values.
- **Merge dedupe** (`LeadRepository.php:1935-1952`):
  - The loser's row is **hard-deleted** after its responses, attendances, chats and activity subjects are re-pointed.
  - The kept row gets:
    - `registered_at`, `attended_at` and `join_clicked_at` set to the earliest non-null value;
    - `status` = the higher rank (registered < no_show < attended);
    - `attended_minutes` = the max;
    - `join_click_count` = the sum.
  - If the winner had no row for that event, the loser's row is simply re-pointed.

---

## 2. Page 1 — Traffics: `/manage/marketing/campaigns`

### 2.1 Purpose

The marketer's one-page answer to "which Meta ads are spending and what did they bring back".
- It merges the old Campaign Performance and Ad Return pages. `/manage/marketing/roas` redirects here with `?view=return`.
- There is one row per campaign, ad set or ad (`grain`).
- The Delivery | Return toggle only hides columns in the browser. Grain and date window reload data from the server.

**Code is identical in prod and the working tree.** On dev the data is frozen, and dev has 2 active integrations, so it does not redirect.

### 2.2 Files

| Layer | File |
|---|---|
| Route | `routes/web.php:1059` (GET), `:1062` (POST sync) |
| Controller | `app/Http/Controllers/Manage/Marketing/CampaignsController.php` |
| Service | `app/Services/Marketing/AdPerformanceService.php` |
| Models | `src/Marketing/MetaAdInsight.php`, `MetaAdSetting.php`, `MetaCustomAudience.php`; `src/Facebook/FacebookIntegration.php`, `FacebookAdAccount.php` |
| Job / commands | `app/Jobs/Marketing/SyncMetaAdDataJob.php`, `SyncMetaAdInsights.php`, `SyncMetaAdSettings.php` |
| Vue | `resources/js/Pages/Manage/Marketing/Campaigns.vue`; `MetricInfoButton.vue`, `RoasInfoButton.vue` |

### 2.3 Data flow

1. **Gate.**
   - The `manage` group applies `auth` + `admin` (web.php:13), and the marketing group adds `permission:view-marketing` (web.php:1054).
   - route:list: web → Authenticate → EnsureUserIsAdmin → PermissionMiddleware:view-marketing.
   - **No** `viewMetaAny` is required, unlike `/ads` and `/campaign-mapping` (web.php:1055, :1069). So the reports-only `marketing` role (`view-events-reports` + `view-marketing`, `RolesSeeder.php:82-85`) can open it.
2. **No integration → redirect.** `if (! FacebookIntegration::where('status', STATUS_ACTIVE)->exists()) return $this->redirectWithSuite('manage.facebook.index')` (:72-74).
   - The integration must be non-deleted (`FacebookIntegration extends SoftDeleteModel`, `FacebookIntegration.php:19, :36`).
   - This is the controller's only use of `?suite=`.
3. **Parameters.**
   - `range` ∈ {last_7d: 7, last_30d: 30, last_90d: 90, last_180d: 180}, default last_30d (:45-50, :76-78).
   - `grain` ∈ {campaign, adset, ad}, default campaign (:80-82).
   - `view` ∈ {delivery, return}, default delivery (:53, :84-86). It is only echoed back.
4. **Window** (`window()`, :219-239; `parseDate` :247-258).
   - If **both** `from` and `to` parse as Y-m-d they win. A backwards pair is swapped; `since = from 00:00`, `until = to 23:59:59`, `custom = {from, to}`.
   - Otherwise `until = Carbon::today()` (MYT) and `since = today − (N−1)`. "Last 30 days" is therefore 29 past days plus today.
5. **Spend rows** (`spendRows`, `AdPerformanceService.php:134-164`). Raw `DB::table('meta_ad_insights')`:
   - SELECT `grain_id, MAX(name), MAX(currency), MAX(account_id), MAX(CASE WHEN spend > 0 THEN date END) AS last_spend_date, SUM(spend), SUM(impressions), SUM(clicks), SUM(link_clicks), SUM(meta_leads)`;
   - WHERE `date BETWEEN since AND until` AND `<grain col> != ''`, GROUP BY grain col (:136-148; sumSelect `MetaAdInsight.php:78-83`).
   - There is **no account, integration-status or currency filter**, so a since-disconnected account's history still appears.
6. **Our leads and revenue** (`leadAndRevenueRows`, :178-243), over `lead_funnels lf`:
   - **First touch** (:187-196): `lf.id = (SELECT lfx.id FROM lead_funnels lfx WHERE lfx.lead_id = lf.lead_id AND (fbclid OR fbc OR campaign_id OR ad_id IS NOT NULL) ORDER BY registered_at ASC, id ASC LIMIT 1)`.
     - It is **global**: no funnel filter, and null-funnel rows count.
     - It is the same rule as `ReportPurchaseToMetaAction::firstAdTouch` (`ReportPurchaseToMetaAction.php:140-153`).
   - **Outer filter** (:231-235): first-touch row only, `lf.<grainId> IS NOT NULL AND != ''`, `lf.registered_at BETWEEN 'since 00:00:00' AND 'until 23:59:59'`, GROUP BY grain id.
   - `leads = COUNT(DISTINCT lf.lead_id)` (:205).
   - `revenue = COALESCE(SUM(ph.total_amount), 0)` over `purchase_histories ph WHERE ph.lead_id IN (cohort with the same grain id, in range, first touch) AND ph.status = 1 AND ph.deleted_at IS NULL` (:213-221). There is **no date, currency or product filter** on the payment.
   - `buyers = COUNT(DISTINCT ph.lead_id)` under the same conditions (:222-230).
   - Rows from funnel landings, Meta Lead Gen (`SyncFlgLeadToCrmAction.php:102-106`) and Messenger referrals (`ProcessInboundMessengerWebhook.php:225-230`) all count when their first-touch row carries the grain id.
7. **Merge** (:71-109).
   - Spend rows are the spine.
   - "Our leads but no stored spend" rows are appended with spend 0, name null, account_id `''` and currency null.
   - Ids are compared as strings (:93-97).
8. **Decorate** (:253-279).
   - `MetaAdInsight::rates`: `ctr`, `cpm`, `cpc` (`MetaAdInsight.php:92-106`).
   - `is_delivering = last_spend_date ≥ now()->subDay()->toDateString()` (MYT) (:265-266). `last_spend_date` is the newest spend > 0 day **inside the selected window only**.
   - Also `cpl`, `cpa`, `roas`, `conversion_rate`, and `profit = revenue − spend`.
9. **Sort** (:116-120): `is_delivering DESC`, then `last_spend_date DESC` (null last), then `spend DESC`. The sort is stable (PHP 8 `asort`/`arsort`).
10. **Controller decoration.**
    - `FacebookAdAccount::pluck('account_name', 'account_id')`; appended rows show '—' (:95, :130).
    - `MetaAdSetting WHERE level = levelForGrain(grain) AND meta_id IN ids` (:102-105).
    - Adset grain only: `MetaCustomAudience` (:111-116). Ad grain only: `MetaAdImage` (:118-123).
    - Per row: `account_name`, `effective_status`, `status_label` / `status_color` via `MetaAdSetting::badge` (`MetaAdSetting.php:150-158`), and `settings = presentSettings()` (:125-136, :325-552).
11. **`totals()`** (:269-311): see the metrics table.
12. **Other props** (:151-154, :192-201):
    - `hasSpendData` = any `meta_ad_insights` row exists;
    - `lastSyncedAt` = `syncedAgo(MAX(meta_ad_insights.updated_at))`;
    - `settingsSyncedAt` = `syncedAgo(MAX(meta_ad_settings.last_synced_at))`, with future stamps shown as "just now";
    - `syncRunning` = `Cache::has('traffics-manual-sync-running')`.
13. **Render** `Inertia::render('Manage/Marketing/Campaigns')` with: view, grain, grains, range, ranges, rows, since, until, custom, totals, hasSpendData, lastSyncedAt, settingsSyncedAt, syncRunning (:138-155).
14. **Front end** (`Campaigns.vue`):
    - Grain and range changes are `router.get` and keep `from`/`to` (:58-67); `useRange` drops `from`/`to` (:101-108).
    - This month / Last month use the **browser clock** (:86-97).
    - The view toggle is `history.replaceState` (:122-127).
    - Search is client-side over name, id and account_name (:131-138).
    - `DataTable` is unpaginated and not sortable, so the server order is final (:434). The expand panel renders `row.settings` (:526-676).
    - Columns (:144-179):
      - Delivery: Name, Status, Account, Spend, Impr., Clicks, CTR, CPC, Meta leads, Our leads, CPL.
      - Return: Name, Status, Spend, Meta leads, Our leads, CPL, Buyers, Conv., Revenue, ROAS, Profit.
    - 7 KPI tiles (:354-413).

### 2.4 Metrics

| On screen | Formula | Source | Code |
|---|---|---|---|
| Spend tile (RM) | round(Σ row.spend, 2), all rows | `meta_ad_insights.spend`, date in window, grain id ≠ '' | `CampaignsController.php:271` |
| Spend subtitle `since → until` | `window()` | query params; `Carbon::today()` MYT | `:219` |
| Leads tile (ours) | Σ row.leads | first-touch `lead_funnels` cohort | `AdPerformanceService.php:205` |
| Leads tile "/ N Meta" | Σ row.meta_leads | `meta_ad_insights.meta_leads` (likely ×2, §1.2) | `CampaignsController.php:302` |
| "X of Y delivering" | count(is_delivering) / count(rows) | `last_spend_date` inside the window | `:308` |
| CPL tile | leads > 0 && spend > 0 ? round(Σspend / Σleads, 2) : '—' | totals, including appended no-spend rows | `:304` |
| Attributed revenue tile | round(Σ row.revenue, 2) | lifetime ACTIVE payments of the cohorts, any currency | `AdPerformanceService.php:213` |
| Total revenue tile | SUM(total_amount) | `PurchaseHistory` (soft deletes excluded), status = 1, `purchased_at` in window; **no lead, ad, payable or currency filter**, so unassigned TnG rows are included | `CampaignsController.php:285-288` |
| ROAS tile | spend > 0 ? round(Σrevenue(attributed) / Σspend, 2) : null; green when ≥ 1 (null compares as 0) | totals | `:306` |
| Profit tile | round(total_revenue − Σspend, 2), labelled "all sales − spend" | totals | `:297` |
| Profit tile "attributed only" | round(Σrevenue − Σspend, 2) | totals | `:298` |
| Row Spend | (float) SUM(spend) | `meta_ad_insights` | `AdPerformanceService.php:156` |
| Row Impr. | SUM(impressions) | same | `:157` |
| Row Clicks | SUM(link_clicks) = Graph `inline_link_clicks` | same | `SyncMetaAdInsights.php:145` |
| Row CTR % | impr > 0 ? round(link_clicks / impr × 100, 2) : null | summed counts | `MetaAdInsight.php:100` |
| Row CPC | link_clicks > 0 ? round(spend / link_clicks, 2) : null | summed counts | `MetaAdInsight.php:104` |
| Row Meta leads | SUM(meta_leads) | same | `AdPerformanceService.php:162` |
| Row Our leads | COUNT(DISTINCT lead_id), first touch, in window | `lead_funnels` | `:238` |
| Row CPL | leads > 0 && spend > 0 ? round(spend / leads, 2) : null | row | `:268` |
| Row Buyers | COUNT(DISTINCT ph.lead_id), lifetime, ACTIVE, not deleted | `purchase_histories` | `:222` |
| Row Conv. | leads > 0 ? round(buyers / leads × 100, 2) : null | row | `:276` |
| Row Revenue | COALESCE(SUM(total_amount), 0), lifetime | `purchase_histories` | `:213` |
| Row ROAS | spend > 0 ? round(revenue / spend, 2) : null; ≥ 2 green, ≥ 1 amber, < 1 rose | row | `:274` |
| Row Profit | round(revenue − spend, 2), **attributed** basis | row | `:277` |
| Status badge / "last active" | `effective_status` → `MetaAdSetting::STATUSES` (unknown → raw value on slate). No settings row → "Delivering" if delivering, else '—'. "last active" = last_spend_date | `meta_ad_settings` at the grain level | `Campaigns.vue:205` |
| "Ad data / settings synced … ago" | diffForHumans(MAX(updated_at) / MAX(last_synced_at)) | two stores | `CampaignsController.php:152` |
| Expand: Budget / left / cap / bid cap | minor units ÷ 100, round 2 (daily else lifetime; budget_remaining; spend_cap; bid_amount) | `meta_ad_settings` | `:327` |
| Expand: audience size "~42k" | approx_count_lower: ≥ 1e6 → ~x.xM, ≥ 1000 → ~xk, else ~n; null or negative → none | `meta_custom_audiences` | `MetaCustomAudience.php:53` |
| Expand: interests / audiences / places chips | counts over the stored targeting JSON (first 5 places, first 3 interests or audiences named) | `meta_ad_settings.targeting` | `CampaignsController.php:492` |
| Expand: "Carousel · N cards" / "Dynamic · testing a × b" | count(creative.carousel) (≤ 10) / variants counts | `meta_ad_settings.creative` | `:386` |

The money labels are hard-coded "RM" (`Campaigns.vue:357, 372, 377, 386, 401, 411, 479, 491, 502, 512, 521`), and so is the bid cap (:565). Only the budget line prints the currency code: `row.settings.currency || 'RM'` (:550-551).

Computed but **not displayed**: totals `cpa`, `buyers`, `conversion_rate`; row `cpm`, `clicks`, `cpa`, `account_id`.

### 2.5 Actions and write paths

**Sync now**: `POST /manage/marketing/campaigns/sync`, requires view-marketing + manage-marketing (web.php:1062).
- `Cache::add(SYNC_FLAG, now, 1800)` is atomic. If the flag already exists: an info flash, then `back()`.
- Otherwise it dispatches `SyncMetaAdDataJob`, flashes success and returns `back()` (:167-180). See §1.1 for what the job does.

### 2.6 Gotchas

- **Two "Profit"s.** The tile is all sales minus spend. The row is attributed revenue minus spend. Rows add up to the tile's sub-line, not its headline.
- **Attributed revenue keeps growing** for a past window, because the payment has no date bound. It also includes payments made *before* the ad registration, and every payable type (membership, course, project fee).
- **First touch is global.** A lead counts only if their earliest Meta-signal row (across all funnels) falls in the window. A returning person who comes back through a new ad counts for neither ad in that window.
- **Lost leads.**
  - A first-touch row with only fbclid/fbc, or with its ids nulled by `sanitizeAdTracking` (`RegisterLeadAction.php:349-360`), is counted on **no** row at any grain, even if a later row has ids.
  - Ids are nulled independently, so a first-touch row can have `campaign_id` but no `adset_id`. Headline Leads, CPL, ROAS and Buyers can therefore **change with the grain**.
- **NULL `registered_at`** sorts first in MySQL ASC. Such a row becomes the first touch, never matches the window, and the lead vanishes. Live registrations always stamp `now()`, so this mainly hits imports and backfills.
- **Staff and test registrations count.** RegisterLeadAction records staff "like anyone else" (:132-136).
- **Appended no-spend rows** (an account with no token, or unsynced Lead Gen / Messenger ids) push leads and revenue into the headline CPL and ROAS with zero spend. They show as "(unnamed)" with Account '—'.
- **Currency.** Spend is summed across accounts, and both revenues across currencies, under an "RM" label. Budget ÷ 100 assumes a 2-decimal currency. Production today is all MYR (§1.2).
- **`meta_leads` is likely ×2** (§1.2).
- **Clicks.** "Clicks", CTR and CPC use `inline_link_clicks`, not outbound clicks (§10, UI drift).
- **Day boundaries.** Spend days are account-timezone days, while lead and payment windows are MYT. `is_delivering` compares account-tz dates with MYT "yesterday". A custom window ending before yesterday shows nothing as delivering.
- **Sync now on production.**
  - The job timeout (1800 s) exceeds the redis `retry_after` (190 s, `config/queue.php:84`) and the Horizon supervisor-1 timeout (180 s, `config/horizon.php:219`), with 10 default workers (`horizon.php:354`). A sweep longer than 190 s can be re-delivered and then marked failed (tries = 1).
  - With `QUEUE_DRIVER=sync` (the config default, `queue.php:16`), the sweep runs inside the HTTP request.
  - With a file cache, the flag is per server.
  - If the process is killed, `finally` never runs, and the button reads "Syncing…" until the 1800 s TTL expires.
- **Dev box.** The zs scheduler runs only a heartbeat, and the workers are network-isolated. Sync now fails softly and writes nothing.

---

## 3. Page 2 — Funnel Sessions tab: `/manage/events/funnels/{id}?tab=sessions`

### 3.1 Purpose

The funnel hub's list of sessions (event rows), with Ad spend, Registered, CPL, CTA, Sold and ROAS columns.
- `?tab=sessions` is read only by the browser.
- Spend comes from the local `meta_ad_insights` table only.

### 3.2 Files

| Layer | File |
|---|---|
| Route | `routes/web.php:316` (`GET manage/events/funnels/{id}`) |
| Controller | `app/Http/Controllers/Manage/Events/FunnelsController.php` (`show`, `transformSession` :3444-3530) |
| Services | `app/Services/Marketing/SessionAdInsightsService.php`; `src/Event/Support/SessionPromotionWindow.php` |
| Vue | `resources/js/Pages/Manage/Events/Funnels/Show.vue`; `Partials/Tabs/SessionsTab.vue`; `Components/ShowTabs.vue`; `Components/CplInfoButton.vue` |

### 3.3 Data flow

1. **Gate.**
   - `manage` auth + admin (web.php:13); events group `permission:view-events|view-events-reports` (web.php:265-266; `Permission.php:514-517`).
   - Inside `show()`: `$fullView = can(view-events)` (:373), `$seesPeople = canAny(lead levels)` (:376), `$canManage = can(manage-events)` (:377).
   - The `sessions` prop is **not gated**: reports-only viewers get the same rows (:513).
2. **Load the funnel.** `EventFunnel` by uuid with `withCount` of slots, sessions, upcoming sessions and leads (:257-266).
   - If it was merged, it redirects to the target and keeps `?suite` (:268-273, working tree).
   - `$this->managedSlot` is null on this route, so no slot filter applies. Only `/manage/events/slots/{id}` sets it (:231-235).
3. **Chips.** `sessionLiveCounts($funnel->events()->with('webinar')->get(...))` (:290-294; :787-796).
   - It covers **all** non-deleted sessions with **no date window**, bucketed by `live_status`. Cancelled sessions are skipped.
   - Sent as `funnel.session_counts` (:3427).
4. **Row query** (:300-310). `$funnel->events()` (`event_funnel_id = 4`, `deleted_at IS NULL`), with `series` (loaded but never used) and `webinar`.
   - Subquery counts:
     - `registrations_count` = all registrations;
     - `attended_count` = `status = 2`;
     - `cta_count` = `whatsapp_cta_captures` with `event_id = session`.
   - Filter: `DATE(scheduled_date) ≥ today − 90 days` (MYT). There is no status filter, so cancelled sessions are included.
   - Order: `scheduled_date`, `start_time` ascending.
5. **`cplForEvents($ids)`** (:316). Allocated CPL (§5). Sent as `ad_*` but **not rendered** on this tab.
6. **`promotionSpendForEvents($ids)`** (:320; service :326-409) feeds the **Ad spend** column.
   - Reloads the events (:346) and computes windows (:347; §1.5).
   - **Campaigns** = DISTINCT non-null, non-empty `campaign_id` on this session's `source = 1` rows, from **any date** (:350-356).
   - One `daySpend('campaign_id', …)` call covers the union of all windows (:374; `daySpend` :904-924 = `SELECT campaign_id, date, SUM(spend) FROM meta_ad_insights WHERE campaign_id IN (…) AND date BETWEEN … GROUP BY campaign_id, date`, with no currency filter).
   - Per session: Σ of each campaign's full daily spend for days in [since, until] (:391-403).
   - `spend` is null when there are no campaigns or no window (:387). If no session in the list has campaigns, it is null for every row (:364-371).
7. **`revenueForEvents($ids)`** (:323; :445-522) feeds the **Sold** column.
   - Frozen offers come from `EventOffer` (:458).
   - `PurchaseHistory WHERE event_id IN ids AND status = 1`, with soft deletes excluded (:473-475).
   - Grouped by `currency_code`; buyers = distinct `(int) lead_id` (:509, :513).
8. **`reportCplForEvents($ids)`** (:327; :552-602) feeds the **CPL** column.
   - Calls `promotionSpendForEvents` **again** (:554), so the same queries run twice.
   - `EventRegistration::whereIn('event_id', ids)->where('source', 1)` (:573-575), with no campaign, status or lead filter.
   - A row counts when `created_at->toDateString()` is in [since, min(until, `Carbon::today()`)] (:577-593).
   - `cpl = round(spend / leads, 2)` only when both are > 0 (:595-599).
9. **Source split** (:332-342). `SELECT event_id, source, COUNT(*) … GROUP BY event_id, source`. `landing` = the `source = 1` count; `other` = the sum of all other sources.
10. **`transformSession()`** (:3444-3530). Identity, edit fields, `live_status`.
    - Counts (:3477-3479); `ad_*` (:3483-3485); `promo_*` (:3489-3492); `sold_*` (:3496-3501); `registered_landing` / `registered_other` (:3504-3505); `report_cpl` / `report_leads` (:3511-3512).
    - `sold_roas` = round(**MYR** revenue / promo spend, 2) when spend > 0 and MYR revenue > 0, else null (:3518-3523).
11. **Other props.**
    - `funnel`: `leads_count` = `lead_funnels` rows (the header "N acquired leads", :264); `registrants_count` = distinct people on non-deleted sessions (:361, :828-845).
    - `slots`: VSL slots filtered out, for AddSlotSessionModal. Also `moveTargets`, `modes`, `eventStatuses` (:513-525).
    - Every prop is computed on every load whatever the tab. Only `journeyBoard` is `Inertia::optional` (:479). No cache.
12. **Client.**
    - `Show.vue` mounts `SessionsTab` for `#tab-sessions` (:176). The tab badge is `sessions.length` (:126).
    - `ShowTabs` mounts only the active tab and writes `?tab=` with `history.replaceState` (`ShowTabs.vue:141-149, :267`).
    - `SessionsTab` orders, filters and renders the table (:80-136, :189-353):
      - Order: upcoming and live first, soonest at the top; then past and cancelled, most recent first.
      - Filtering: search plus the Past / Live / Upcoming chips, client-side.
      - No totals row, no column sorting.
    - Columns: Session (date and time under the title), Status, Ad spend, Registered, CPL, CTA, Sold, ROAS (:121-136).
    - Working-tree tab strip: Sessions / Slots / Journey (`Show.vue:124-129`). Prod and HEAD: Sessions / Journey / Slots / Automation / Group / Landing, gated by view-events.

### 3.4 Metrics

| On screen | Formula | Source | Code |
|---|---|---|---|
| Past / Live / Upcoming chips | count by `live_status`, cancelled skipped, **all time** | `events` (funnel, not deleted) + latest `zoom_webinars` | `FunnelsController.php:290` |
| Sessions tab badge | `sessions.length` (90-day window onward, cancelled included) | sessions prop | `Show.vue:126` |
| Status badge | `live_status` (§1.4) | events + zoom_webinars | `Event.php:211` |
| **Ad spend** (RM, with since / until and "set by hand") | Σ over the session's campaigns C, over days since ≤ d ≤ until, of SUM(spend WHERE campaign_id = C AND date = d), round 2. '—' when there is no campaign or window; **0.00** when campaigns exist but no spend is stored | `event_registrations` (source = 1) → campaigns; `meta_ad_insights` | `SessionAdInsightsService.php:326` |
| Registered (big number) | COUNT(*) of `event_registrations` for the session (any source or status) | event_registrations | `FunnelsController.php:303` |
| "N landing" | COUNT where source = 1, **all time** | same | `:332` |
| "N other" (if > 0) | Σ source ≠ 1 (admin 2, walk-in 3, Zoom 4, import 5, from-preview 6) | same | `:339` |
| "N attended" (if > 0) | COUNT where status = 2 | same | `:304` |
| **CPL** (RM X, "÷ N landing") | round(promo spend / report_leads, 2) when both > 0, else '—'. report_leads = **this session's** source = 1 rows with DATE(created_at) in [since, min(until, today)] | promotionSpendForEvents + event_registrations | `SessionAdInsightsService.php:552` |
| CTA | COUNT(*) `whatsapp_cta_captures` with `event_id = session` (first touch per link and contact, **not** taps) | whatsapp_cta_captures | `FunnelsController.php:305` |
| Sold (per currency, highest first; buyers) | per currency SUM(total_amount); buyers = COUNT DISTINCT (int) lead_id; '—' when 0 buyers | `purchase_histories` event_id = session, status = 1, not deleted | `SessionAdInsightsService.php:473` |
| ROAS (green if ≥ 1, else amber) | round(MYR revenue / promo spend, 2); null if spend is null or 0, or MYR revenue is 0 | revenueForEvents + promotionSpendForEvents | `FunnelsController.php:3518` |
| Header "N acquired leads" | COUNT `lead_funnels` rows for the funnel | `EventFunnel::leads()` | `:264` |
| `ad_leads` / `ad_spend` / `ad_cpl` (payload only) | allocated (§5) | cplForEvents | `SessionAdInsightsService.php:273` |

### 3.5 Actions

Add session, Link Zoom webinar, Edit and Delete appear only for `can('manage-events')` (`SessionsTab.vue:170, :317`). The routes check the same permission again (web.php:369, 374, 537, 539). Their write internals are not mapped here.

### 3.6 Gotchas

- **The CPL "?" pop-up explains a different number.** `CplInfoButton` (mounted at `SessionsTab.vue:208-210`) describes the *allocated* method. The column is the *report* CPL. Details in §10.
- **"÷ N landing" ≠ "N landing"** whenever landing rows exist before the window. So `SessionsTab.vue:128-129` ("check the division on screen") does not always hold.
- **The "—" CPL tooltip** says "No ad spend synced for this window yet" (:273). The real cause may be that no registration carried a `campaign_id`, or that the window cannot be resolved.
- **The ROAS tooltip** says "No ad spend synced" when buyers > 0. ROAS is also '—' when all sales are non-MYR.
- **Ad spend is campaign-level full spend.**
  - It includes ad sets that point elsewhere.
  - One stray old click pulls a whole campaign into the session.
  - Two sessions with overlapping windows in different slots or funnels that name the same campaign both count it **in full**.
  - Campaigns that spent but produced no landing registration for any session are never counted anywhere.
- **Promotion-window edge cases** from §1.5 apply: cancelled sibling boundaries, the 12:xx double day, and inverted morning windows.
- **Upcoming sessions** (session 31) have partial spend up to the last synced day, and a lead count capped at today.
- **Time zone and currency.** Spend days are account-timezone days, and the currency is ignored (labelled RM).
- **Meta restates about 72 hours.** Today's spend is partial.
- **Sync stops silently** when the token expires (§1.1).
- **Chips and badge cover different sets.** Chips are all-time; the table is the 90-day window. The badge includes cancelled sessions; the chips do not.
- **Search** (placeholder "Search session, slot or status…") matches only the title and `live_status_label` (:106-109, :165).
- **Sold** uses `purchase_histories.event_id`, decided once (§1.6). An attendance import that arrives later does not move older sales.
- **Null `lead_id`** purchases collapse into one "buyer 0".
- **Staff and test registrations** count in every number.
- **Production fan-out (`origin/master`).** A funnel-root landing registration writes `SOURCE_LANDING` rows with the same ad ids into every upcoming public session. This inflates "landing" and can deflate the report CPL for older sessions. For session 31 there are **0 fan-out rows** (§9).
- **Wasted work.** `promotionSpendForEvents` runs twice per load, `series` is eager-loaded for nothing, and the `ad_*` payload is dead weight.

---

## 4. Page 3 — Session Show: `/manage/events/{id}` (default tab = Summary)

### 4.1 Purpose

One session's page.
- The default tab is **Summary**: it is the first tab, and ShowTabs opens the first visible tab when `?tab=` is missing or unknown (`Show.vue:96`; `ShowTabs.vue:70-76`).
- Summary is **not** built from page props. On mount it fetches `GET /manage/events/{uuid}/summary`, which rebuilds the marketer's Telegram report from the database (no Meta, no Zoom, no cache, no jobs).

### 4.2 Files

| Layer | File |
|---|---|
| Routes | `routes/web.php:528` (show), `:532` (summary), `:535-536` (promotion-window, `permission:manage-events`) |
| Controller | `app/Http/Controllers/Manage/Events/EventsController.php` (`show` :88-196, `summary` :488-511, `promotionWindow` :572-587) |
| Services | `SessionSummaryService.php` (`forEvent` :59-167), `SessionAdInsightsService.php`, `FunnelDashboardService.php` (`globalMonthSpend` :194-215), `SessionPromotionWindow.php` |
| Vue | `Pages/Manage/Events/Show.vue`, `Partials/Tabs/SummaryTab.vue`, `KpiCards.vue`, `LeadsSpendTrend.vue`, `Components/FunnelMetrics/ConversionWaterfall.vue` |

### 4.3 Data flow: the page shell (`show`)

1. **Gate.** `manage` auth + admin (web.php:13), and the events group (`view-events|view-events-reports`).
   - `admin` = `EnsureUserIsAdmin`, which redirects non-manage users to `main.dashboard` (`EnsureUserIsAdmin.php:36-40`).
   - Super-admins pass every check through `Gate::before` (`AuthServiceProvider.php:49-51`).
2. **Load.** `Event::with(['series', 'funnel', 'webinar.actions', 'webinar.liveQuestions', 'memberships'])->where('uuid', $id)->firstOrFail()` (:97). A soft-deleted session returns 404. There is no group scope.
3. **Back URL** (:102-108).
   - `indexPath` = the funnel hub, or the funnels index when there is no funnel.
   - `resolveBackUrl` returns the Referer with its query when the Referer path equals `indexPath`. Otherwise it returns `indexPath`, plus `?suite=X` if a suite is known (`ResolvesBackUrl.php:34-61`).
   - `?tab=sessions` is appended **only** when the result is exactly the bare `indexPath`.
   - Client: `withSuite()` (`Show.vue:160`; `useSuite.js:254-259`).
4. **Gates.** `$fullView = can('view-events')` (:118); `$seesPeople = canAny(view-leads-all | group | team | own)` (:128; `Permission.php:494-497`).
5. **Props** (:130-195):

   | Prop | Kind | Notes |
   |---|---|---|
   | `event = transform($event, true)` | eager value | Runs on every request, partial reloads included. Contains `registrations_count = $event->registrations->count()` (:909), which **lazy-loads every registration row**, despite the comment at :90-96. Also `live_status`, `slot_uuid`, `landing_url = /sessions/{uuid}/register` unless members-only, `funnel {uuid, name, has_candidate_source}`, description, zoom_link, location, email_tickets, membership_uuids (:877-924). |
   | `modes`, `statuses`, `visibilities` | constants | |
   | `memberships = []`, `allowVisibility = false` | hard-coded | (:132-138) |
   | `registrations` | closure | Gated on **`$seesPeople`**, not `$fullView` (:149-151). |
   | `registrationStatuses`, `zoomStates` | constants | |
   | `webinar`, `webinar_actions`, `live_questions`, `attendance`, `engagement`, `ctaCaptures`, `messages` | closures | Built only when `$fullView`, else null or [] (:164-194). |
   | `zoomConfigured` | eager | Credentials check only (`ZoomServerService.php:69-84`) |
   | `backUrl` | eager | |

6. **Inertia v2.0.24 behaviour.** On a **full** (non-partial) visit every closure is resolved (`vendor/inertiajs/inertia-laravel/src/Response.php:273-277, :347-348`). Only partial reloads (`X-Inertia-Partial-Component`, :762-764) skip props.
   - So opening the Summary tab still builds the roster (for lead-level users), plus attendance, engagement, CTA and messages (for full-view users).
   - Switching tabs never refetches the shell (`replaceState`).
7. **Side effects of a full visit by a `view-events` user.**
   - **Live webinar.** `getWebinarLiveParticipants` is called from both the webinar and attendance closures (:765-767, :1217-1221) as `GET /metrics/webinars/{id}?type=live`.
     - Only a successful non-null count is cached (15 s). Failures are not cached, so every load calls Zoom again (`ZoomServerService.php:1051-1078`).
   - **Ended webinar** with no `recording_url`, `recording_status ≠ NONE`, Zoom configured, and `recording_synced_at` null or older than 10 minutes. This **queues** `SyncWebinarRecording` + `SyncWebinarRecordingToMeeting` (:769-781, :864-868).
     - The throttle is weak: `recording_synced_at` is stamped only when the job **runs** (`ZoomWebinarRepository.php:818`). Every view before a worker picks the job up dispatches again.
     - Early-return job paths never stamp it (`SyncWebinarRecording.php:60-79`).
8. **Tabs** (`Show.vue:91-151`):
   - Summary and Ads are shown to every viewer (:96-97).
   - Registrations requires a lead level (:62, :102-103).
   - The list is truncated after Ads for users without `view-events` (:113).
   - Badges: Registrations = `registrations.length` (:103); Attendance = `no_show_count` when > 0 (:125); CTA = `ctaCaptures.length` (:144).

### 4.4 Data flow: Summary

1. `SummaryTab` mounts and calls `fetch('/manage/events/{uuid}/summary')` with `Accept: application/json` (`SummaryTab.vue:50-67`).
   - It re-fetches on a successful save (:104), on Retry (:185), and **on every remount** (`ShowTabs` unmounts inactive tabs, :267).
   - There is no polling. `router.post` preserves state, so a save does not double-fetch.
2. **`EventsController@summary`** (:488-511): `Event::with(['funnel', 'series'])` by uuid, then `SessionSummaryService::forEvent()`. Without a lead level, each `sold_items[*].buyer_rows` is unset (:499-508). The route (:532) adds no middleware beyond the group, so reports-only users can read it.
3. **`forEvent`** (`SessionSummaryService.php:59-167`):
   - a. `promo = promotionSpendForEvents([id])`, `revenue = revenueForEvents([id])`, `headline = cplForEvents([id])` (:61-63).
   - b. `until = min(promo.until, today MYT)` (:68-69).
   - c. `$regs` = `event_registrations WHERE event_id AND source = 1 AND created_at BETWEEN 'since 00:00:00' AND 'until 23:59:59'`, eager-loading `lead.user.profile` and `lead.enrichment` (:70-76). This is the same set as the report-CPL leads (:83-85).
   - d. `report = reportCplForEvents([id])` (:86-89).
   - e. `registered_total` = all rows; `attended` = `status = 2`; `isPast = live_status === 'past'` (:93-97).
   - f. `metaLeads` = SUM(`meta_leads`) over the promo campaigns, `date BETWEEN since AND clamped until` (:101-105).
   - g. `countrySplit`, `dailySeries`, `quality`, `budgets` (:107-113), then the payload and `telegram_text` (:115-166).
4. **Budgets** (:458-500).
   - `monthly` = `Setting::get(MARKETING_MONTHLY_ADS_BUDGET)`, global, not per funnel (`FunnelDashboardService.php:202-204`).
   - `weekly = round(monthly / 4, 2)` (:465).
   - `windowDays = diffInDays(since, until) + 1` over the **unclamped** window (:113 passes `promo['until']`; :470-472).
   - Session budget = `events.promo_budget` if not null (`is_derived = false`, :474), else `round(weekly × windowDays / 7, 2)` (:477-479). Null when there is no monthly budget or no valid window.
   - Month spend = SUM(`meta_ad_insights.spend`) from the 1st of the month to today over **all rows** (`FunnelDashboardService.php:194-215`).

### 4.5 Metrics (Summary)

| On screen | Formula | Source | Code |
|---|---|---|---|
| Header status pill | `live_status` | §1.4 | `Event.php:211` |
| Campaign summary period | `since → until` from SessionPromotionWindow | events / siblings / overrides | `SessionPromotionWindow.php:59` |
| **Ad spend** | promotion spend (§3.3 step 6) | meta_ad_insights + landing campaigns | `SessionAdInsightsService.php:391` |
| Ad spend hint "N campaign(s)" | count distinct `campaign_id` on landing rows | event_registrations | `:383` |
| **CPL** (report CPL) | round(spend / leads, 2) when both > 0; leads = landing rows in [since, min(until, today)] | as above | `:596` |
| CPL colour | red if > target_cpl, green if ≤, dark if no target, grey if null | setting `marketing.target_cpl` | `SummaryTab.vue:148` |
| CPL per-country hint | round(bucketSpend / bucketLeads, 2). Leads bucketed by phone prefix (longest wins). Spend bucketed by adset targeting country (one country = that bucket, several = Mixed, no settings row = Unknown); Mixed and Unknown get no CPL | user_profiles.phone, `config marketing.phone_countries`, meta_ad_settings (adset).targeting, meta_ad_insights by adset_id | `SessionSummaryService.php:178` |
| Cost / attendee | round(spend / attended, 2) only if past and both > 0 | report spend; status = 2 (all sources) | `:147` |
| Show-up rate | round(attended / registered_total × 100) only if past and total > 0 | event_registrations | `:146` |
| Revenue (RM) | SUM(total_amount) of **MYR** purchases | purchase_histories event_id, status = 1, not deleted | `:151` |
| Revenue hint "N buyer(s)" | distinct lead_id, **all currencies** | same | `SessionAdInsightsService.php:513` |
| Return × | round(MYR revenue / spend, 2) when both > 0 | — | `SessionSummaryService.php:152` |
| Allocated Session CPL (footnote, plain text) | cplForEvents (§5) | — | `SessionAdInsightsService.php:225` |
| "This push" budget bar | budget (§4.4 step 4); `used_pct = round(spend / budget × 100, 1)` | events.promo_budget, setting | `SessionSummaryService.php:470` |
| "Funnel month" bar | month spend over **all accounts and campaigns**; used % and pace % = round(day / daysInMonth × 100, 1) | meta_ad_insights, setting | `FunnelDashboardService.php:194` |
| Daily leads vs spend | one row per day from since to min(until, today); leads by DATE(created_at); spend = Σ window campaigns that day | event_registrations + promo daily | `SessionSummaryService.php:275` |
| Chart totals, avg CPL, day CPL | client sums; avg = totalSpend / totalLeads | summary.daily | `LeadsSpendTrend.vue:28` |
| Waterfall: Leads in Ads Manager | metaLeads (likely ×2, §1.2) | meta_ad_insights | `SessionSummaryService.php:101` |
| Waterfall: Landing page leads | report leads | event_registrations | `SessionAdInsightsService.php:573` |
| Waterfall: On the roster (+N other) | COUNT all rows; note = total − leads when positive (this mixes non-landing rows with landing rows created before the window) | event_registrations | `SessionSummaryService.php:93` |
| Waterfall: Attended | COUNT status = 2 when past, else "session not run yet" | — | `:94` |
| Waterfall: Bought | revenue.buyers | purchase_histories | `:148` |
| Waterfall stage % | round(stage / previous non-null stage × 100) | client | `ConversionWaterfall.vue:25` |
| What sold | group by `payable_type \| payable_id` (else "unclassified"); per-currency sums; buyers distinct; "pitched" if payment_link_id or payable matches `event_offers` | purchase_histories, event_offers, leads / users / profiles | `SessionAdInsightsService.php:623` |
| Lead quality chips | over window regs, **overlapping** (not a partition): fake = fake_score ≥ 60; wrong number = phone_is_valid = false OR wa_exists = false; agent = is_property_professional ∈ {1, 2}; not enriched = no lead_enrichments row; duplicates = COUNT `verified_identity_pairs` PENDING with email_user_id or phone_user_id in the regs' users | lead_enrichments, verified_identity_pairs | `SessionSummaryService.php:312` (:326-340, :347) |
| Where the leads are | phone prefix decides the country. For MY: area = enrichment geo_region, "Abroad · X" when the IP country ≠ MY, else "Area unknown". % = count / total × 100 (1 dp). Partitions `$regs` | user_profiles.phone, lead_enrichments | `:379` |
| Telegram text | string assembly. The "ROAS:" line lists **revenue per currency**, not a ratio. Month line 🔴 = **under** pace | payload | `:511`, `:526`, `:550-555` |

### 4.6 Write path (Summary editor)

`POST /manage/events/{uuid}/promotion-window` (web.php:535-536, `permission:manage-events`).
- `PromotionWindowRequest`: dates are `'date'`, with `promo_ends_at` `after:promo_starts_at` (:21-31, :26).
- `EventsController@promotionWindow` maps `promo_starts_at`, `promo_ends_at`, and `promo_budget = input ?: null` (:576-578).
- `EventRepository::update` writes inside `DB::transaction` (:121-153, :142-151). Then a flash, `back()`, and the tab re-fetches.

### 4.7 Gotchas

- **The date editor shortens "until" by a day on every save** (§1.5). `openEditor` pre-fills the derived dates, so changing **only the budget** also pins the dates and triggers the off-by-one (`SummaryTab.vue:87-94`).
- **A budget of 0 is stored as null** (auto).
- **"Ad spend" is not allocated** (full campaign spend). The CPL "?" on the Summary CPL card describes the allocated method, although the footnote under it is correct (§10).
- **"Landing page leads" uses `created_at`**, not `registered_at`. Landing rows created before the window are left out, but the waterfall labels the gap "+N from other sources".
- **Revenue cards are MYR-only.** Other currencies appear only in "What sold" and the Telegram text. The "N buyer(s)" hint counts all currencies.
- **Phone-country bucketing** strips **all** leading zeros (:251). A local `012…` number becomes `12…` and lands in the US (`1`) bucket.
- **"Funnel month" is company-wide.**
- **For session 31** (upcoming), show-up and cost per attendee read '—', and leads and the chart stop at today. The budget uses the full 14-day window.
- **Buyer names** are blank when a profile exists with an empty `full_name` (`SessionAdInsightsService.php:700-702`).
- **Live Zoom calls and recording-sync dispatches** on page load, full-view users only (§4.3 step 7).
- **Reports-only users** get Summary and Ads with revenue and buyer *counts*, but no names.

---

## 5. Page 4 — Session Ads tab: `/manage/events/{id}?tab=ads`

### 5.1 Purpose

"What did this session's ad leads cost, and what did promoting it cost?" Loaded only when opened. It reads from the database only: no Graph, no cache, no job, no write.

### 5.2 Files

| Layer | File |
|---|---|
| Route | `routes/web.php:530` (`GET manage/events/{id}/ad-insights`) |
| Request | `app/Http/Requests/Manage/Events/AdInsightsRequest.php` |
| Controller | `EventsController@adInsights` (:528-556) |
| Services | `SessionAdInsightsService::forEvent` (:98-214), `cplForEvents` (:225-292), `promotionSpendForEvents`, `revenueForEvents`; `MetaAdLabelResolver`; `src/Event/Repositories/EventOfferRepository.php` |
| Vue | `Partials/Tabs/AdsTab.vue` |

### 5.3 Data flow

1. **Client.**
   - `grain` comes from `?grain=`, default `campaign` (`AdsTab.vue:29-31`).
   - It calls `fetch('/manage/events/{uuid}/ad-insights?grain=…')` (:41-44). Any non-2xx shows the red "Couldn't load ad performance. Retry" box (:45-48, :171-174).
   - A grain switch rewrites the URL with `replaceState` and re-fetches (:58-63).
2. **Gate.** Auth + admin + `view-events|view-events-reports` (web.php:266). `AdInsightsRequest`: grain nullable, in {campaign, adset, ad}, otherwise 422; empty falls back to campaign (:24-26, :34-38); `authorize()` = true.
3. **Event.** `Event::where('uuid')->firstOrFail()`; soft-deleted → 404. Then `forEvent($event, grain)` (:536).
4. **`forEvent`:**
   - a. `regs` = `event_registrations WHERE event_id AND source = 1`, columns grain ids + `created_at` (:105-107). No lead, staff or quality filter.
   - b. `attributed` = regs whose grain column (as a string) ≠ '' (:114). If there are none, it returns `total = {registrations, attributed: 0, spend: 0, cpl: null}`, `rows = []`, `errors = []`, **with no `headline` key** (:116-125).
   - c. `mine[id] = {count, days[Y-m-d]}` from `created_at->toDateString()` (MYT) (:128-134). `since` / `until` = the min / max day of this session's attributed registrations at this grain (:137-138).
   - d. `globalDayCounts` (:878-888): `event_registrations WHERE <idCol> IN ids AND source = 1 AND created_at BETWEEN … GROUP BY idCol, DATE(created_at)`. This covers **all sessions in all funnels, including soft-deleted sessions** (no join to `events`).
   - e. `daySpend` (:904-924) at the grain column. At campaign and adset grain it sums every ad underneath; no account or currency filter.
   - f. `windowTotals` (:938-958): SUM of impressions, clicks, link_clicks and meta_leads per object over since..until.
   - g. Labels: `MetaAdLabelResolver::namesForLevel` (§1.1); `settings()` gives the badge and creative (:154-167); `previewLinks` at ad grain only (:139-143).
   - h. **Per object** (:153-189):
     - No stored spend row in the window → an `errors[]` entry ("No stored ad spend … run meta:sync-ad-insights") and a row with `spend` and `window_spend` = null (:157-166). A stored row with spend 0 is **not** treated as missing.
     - Otherwise `allocated = Σ over this session's reg days of daily[day] × sessionRegs / dayTotal`, with `daily` defaulting to 0 and `dayTotal = global[id|day] ?? sessionRegs` (:169-174).
     - `window_spend` = Σ stored spend over since..until (:186).
   - i. `row()` (:815-861): `registrations`; `spend` = allocated (round 2); `cpl` = spend / leads when spend > 0; `is_small_sample = leads < 5` (:840, const :76); `window_ctr` (:849); `window_meta_leads`; status badge (:850-854); `preview_link`; creative (ad grain); `days`.
   - j. Sort by spend desc, null last (:192). `total = {registrations, attributed, spend = Σ allocated, cpl = spend / attributed when spend > 0}` (:205-210). `headline = cplForEvents([id])[id]` (:203).
5. **`cplForEvents`** (:225-292). The same algorithm, fixed at **campaign** grain:
   - It loads landing registrations (:233-235) and skips rows with no campaign (:252-255).
   - `spend` is seeded at 0.0 for every id (:239).
   - It uses `daySpend[$id][$day] ?? 0.0` (:279), so a campaign with no stored rows silently contributes 0.
   - `cpl = allocated / attributed` when both > 0 (:286-288).
   - Its window is the union of all requested sessions' attributed days, so batch size does not change any one session's result (:269-271).
6. **`revenueForEvents([id])`**: §3.3 step 7. `offer_revenue` = purchases whose `payment_link_id` matches a **frozen** `event_offers.payment_link_id`, otherwise whose `payable_type | payable_id` matches the frozen offerable (:497).
7. **`promotionSpendForEvents([id])`**: §3.3 step 6.
8. **`EventOfferRepository::resolveFor`** (:32-65): the frozen `event_offers` if any exist, otherwise the live active `event_series_offers` (`offers_frozen = false`). Read-only.
9. **Response JSON**: `{grain, headline, total, rows, errors, revenue, promotion, offers, offers_frozen}` (:556).

### 5.4 Metrics

| On screen | Formula | Source | Code |
|---|---|---|---|
| "Spent promoting this session" | promotion spend: named campaigns' **full** spend over the promotion window; not allocated | event_registrations + meta_ad_insights | `SessionAdInsightsService.php:350` |
| Promotion window since → until | §1.5 | events | `SessionPromotionWindow.php:61` |
| "N campaigns" | distinct non-empty campaign_id on landing rows, all-time | event_registrations | `:383` |
| "Manually set" badge | `promo_starts_at` or `promo_ends_at` not null | events | `SessionPromotionWindow.php:61` |
| Revenue per currency, "N payments" | Σ total_amount and COUNT grouped by UPPER(currency or default) | purchase_histories event_id, ACTIVE | `:473` |
| "… bought the pitch" | offer_revenue | event_offers + purchase_histories | `:497` |
| Buyers | count distinct (int) lead_id | purchase_histories | `:509` |
| "pitched: …" titles | frozen event_offers titles, else live event_series_offers | — | `EventOfferRepository.php:34` |
| Empty state "N landing registration(s) so far" | total.registrations | landing rows | `:118` |
| Tile: Leads from ads (attributed / registrations) | campaign-grain attributed / all landing rows; **does not move with the grain switch** | event_registrations | `:250` |
| Tile: Allocated spend | Σ over campaign c and day d where this session has n_s > 0: spend(c,d) × n_s / N(c,d); N = landing rows with c that day across **all** sessions; round 2 | event_registrations + meta_ad_insights | `:273` |
| Tile: Session CPL | allocated / attributed when both > 0, else '—' | — | `:286` |
| Amber banner "No stored spend yet for N object(s)" | objects at this grain with **zero** stored rows in [first, last] reg day | meta_ad_insights | `:161` |
| Row Leads | this session's landing rows carrying the object id | event_registrations | `:132` |
| Row Spend (allocated) | as the tile, at the grain; null when no stored row | — | `:169` |
| Row CPL (+ "small") | spend / leads when spend > 0; small when leads < 5 | — | `:837` |
| Row Spend (whole window) | Σ stored spend over [first, last] attributed reg day of this session at this grain | meta_ad_insights | `:186` |
| Row Impr. / CTR / Meta leads | SUM(impressions); round(link_clicks / impressions × 100, 2); SUM(meta_leads) (likely ×2) | meta_ad_insights | `:945`, `:849`; `SyncMetaAdInsights.php:182` |
| Row status badge | `MetaAdSetting::STATUSES[effective_status]`, else the raw value on slate | meta_ad_settings | `MetaAdSetting.php:150` |
| Expand: by-day / "Allocated … of … spent in the window" | row.days; spend versus window_spend | — | `AdsTab.vue:389` |
| Footnote "rows total RM X" (adset and ad grain) | client Σ row.spend (null = 0) | rows | `AdsTab.vue:133` |

### 5.5 Write path

"Change dates" is shown only with `can('manage-events')` (`AdsTab.vue:190`). It POSTs `/promotion-window` (:92-99) with **no `promo_budget`**. The controller writes `promo_budget = null` (`EventsController.php:578`), which **wipes a budget set on Summary**. The same "until − 1" off-by-one applies.

### 5.6 Gotchas

- **Three spend figures that never reconcile:**
  - allocated (tiles and rows);
  - whole-window (rows; spans this session's first to last registration day);
  - promotion (top card; the slot-schedule window).
- **Two CPLs under one name.** The Ads "Session CPL" is allocated. The Sessions and Summary "CPL" is the report CPL, which never appears on this tab.
- **Footnotes:**
  - "the same figures the funnel's Sessions tab … show" (:313-315, :428-429) is **stale**.
  - "the gap between the two Spend figures is days with no registration anywhere" (:419-422) is **incomplete**: the gap also holds other sessions' shares on shared days, and days that fed only other sessions.
- **Spend that no session gets:** spend on days with no landing registration from that object is never allocated to anyone. Registrations on **soft-deleted** sessions take a share that no visible session shows.
- **Non-landing ads inflate CPL.** If a campaign also runs Instant Form or other-destination ad sets, all its daily spend is still split across landing registrations.
- **Unsynced campaigns understate the headline CPL**: their leads stay in `attributed` while their spend counts as 0. The banner relates to the selected grain; the headline is always campaign grain.
- **Switching to the Ad set or Ad grain** when no row carries that id hides the headline tiles too: there is no `headline` key, and the Vue `v-if` uses `total.attributed` (:280).
- **Finer grains do not sum to the campaign view.** This is by design.
- **First touch per (event, lead).** A re-registration through a new ad keeps the old ids and the old `created_at` day.
- **Merge** hard-deletes the duplicate row. If the kept row was non-landing, the person drops out of the CPL even though the ad ids get blank-filled onto it.
- **`remove()`** hard-deletes the row and drops it from every numerator and denominator, retroactively.
- **Labels.** An object with spend but no `meta_ad_refs` or `meta_ad_settings` row shows "Ad {id}" or "Campaign {id}".
- **Badge colours.** `badgeClass` maps only emerald, amber and rose; sky and slate statuses fall back to slate.
- **Null `lead_id`** buyers collapse into one.
- **Production fan-out** (§3.6) would split a day N ways. Session 31 has none.

---

## 6. Page 5 — Session Registrations tab: `/manage/events/{id}?tab=registrations`

### 6.1 Purpose

The session roster: one row per `event_registrations` row of the event.
- There is no separate endpoint. The whole roster ships as the unpaginated `registrations` prop of `show()`.
- Filters, search, cards and campaign buttons all run client-side.
- The export re-applies the filters in PHP.

### 6.2 Files

| Layer | File |
|---|---|
| Read | `EventsController@show` (`registrations` closure :149-151, `transformRegistrations` :935-959, `transformRegistration` :993-1107, `buildMessagesProp` :287-409, `buildAttendanceProp` :1173-1250, `aiCallsForLeads` :1118-1148) |
| Concerns | `app/Http/Controllers/Concerns/BuildsLeadEngagementStats.php`, `BuildsLeadInsight.php` |
| Writes | `RegistrationsController`, `RegistrationsImportController`, `PreviewCandidatesController`, `CheckInController`; `EventRegistrationRepository`; `app/Actions/RemoveSessionRegistrationAction.php` |
| Export | `EventsController@exportRegistrations`; `src/Event/Support/RegistrationRosterFilter.php`; `app/Exports/EventRegistrationsExport.php` |
| Vue | `Partials/Tabs/RegistrationsTab.vue`, `AddRegistrationModal.vue`, `RemoveRegistrationModal.vue`, `ExportMenu.vue` |

### 6.3 Read path

1. **Gate.** Route group as in §4. The tab is mounted only when `seesPeople` (`Show.vue:62, :102-103`).
2. **`registrations` closure** (:149-151). If `$seesPeople`:
   - `$event->load(['registrations.lead.user.profile', 'registrations.lead.enrichment', 'registrations.lead.assignedAdmin.profile'])`, then `transformRegistrations()`;
   - otherwise `[]`.
   - **No LeadVisibility, group or staff filter**: every row `WHERE event_id = id` (`Event::registrations`, `Event.php:117-120`).
3. **Batch lookups** (`transformRegistrations`):
   - a. **Ad names** via `MetaAdLabelResolver::forRegistrations` (`MetaAdLabelResolver.php:176-186`). Previews come from `meta_ad_settings` level AD (:128-142). All stored data.
   - b. **`leadEngagementStats`** (`BuildsLeadEngagementStats.php:61-168`). These are **lifetime** numbers, not about this session:
     - `call_recordings` count, SUM(duration_seconds) and MAX(called_at), with NotIgnoredScope (:71-76);
     - happened `zoom_meetings` (`applyHappened`, `ZoomMeeting.php:859-876`): count and round(Σ coalesce(actual_seconds, duration × 60) / 60) (:82-88);
     - `zoom_webinar_attendances`: distinct webinars, Σ per-webinar round(Σ duration_seconds / 60) (:93-104);
     - 1:1 non-sandbox `whatsapp_messages` by direction, joined through conversation, contact (`contacts.user_id`) and channel (:110-125);
     - `activity_logs` count and MAX(occurred_at) (:130-135);
     - `engagements` with status BOOKED, COMPLETED, LOST or SWING (:139-144).
   - c. **`activeMembershipsForLeads`**: `member_subscriptions` ACTIVE → membership names (:441-460).
   - d. **`pipelinesForLeads`**: every non-deleted engagement, newest `updated_at` first → project name and status (:400-431).
   - e. **`aiCallsForLeads`** (`EventsController.php:1118-1148`): the **latest** `ai_voice_calls` with `source = LEAD` per lead, from any funnel, plus the follow-up delivery (`AiCallPresenter.php:41-66, :138-159`).
   - f. `setRelation('event')` on every row (:954).
4. **Per row** (`transformRegistration`, :993-1107):
   - status and label; `is_attended`, `is_no_show`; source and label (`EventRegistration::SOURCES`); `ticket_url` (physical only, signed `main.ticket.show`, `EventRegistration.php:394-405`);
   - `account_manager` = `leads.assigned_admin_id` → profile name, else email;
   - ISO `registered_at`, `reminders_muted_at` (WT), `attended_at`, `attended_minutes`;
   - `is_registrant = zoom_registrant_id !== null` (:1030); `zoom_sync_error` and label; `zoom_sync_exhausted = attempts ≥ 5`; `zoom_sync_held`; `zoom_state` with precedence on > failed > held > syncing (`EventRegistration.php:321-332, :348-364`);
   - `join_clicks`, `join_clicked_at`; memberships, pipelines, ai_call;
   - **`ad = {...}` only when `campaign_id` OR `ad_id` is set** (:1068-1080);
   - `insight` (`BuildsLeadInsight.php:34-96`: enrichment geo, device, occupation and income, plus agent and fake states with admin verdicts outranking AI);
   - `lead = {uuid, name = profile.full_name ?: email, email, phone = user_profiles.phone, email_verified, phone_verified}`;
   - merged with the engagement stats, or `EMPTY_LEAD_STATS` (`BuildsLeadEngagementStats.php:36-49`).
5. **Messages band** (`buildMessagesProp`, `$fullView` only; null when there is no funnel):
   - **Rules** (:296-319): `funnel_whatsapp_messages` (soft-deleted excluded) WHERE `event_funnel_id = funnel AND audience = LEAD AND [(ON_REGISTER AND (series NULL OR = this slot)) OR (BEFORE_EVENT | AFTER_EVENT AND series = this slot)]`.
     - AFTER_ENDED (4) and AFTER_REGISTER (5) are never shown. `is_active` is **not** filtered.
     - Sorted by `[trigger, −offset]`.
   - **Sends** (:329-336): `funnel_whatsapp_sends` with message status, for those rule ids × roster leads AND the ledger filter in §0.3. The latest row per (rule, lead) wins.
   - **Cell outcome** (:342-377): no send → null (pending). Otherwise `FunnelWhatsappSend::outcomeFor` (`FunnelWhatsappSend.php:193-214`): SKIPPED → skipped; FAILED → failed; QUEUED → queued; else by message status read, delivered, failed or sent.
   - **Summary** (:397-406): reached = delivered + read; problems = failed + skipped. These are **cell** counts, not people.
   - **Labels**:
     - The header is `short_label` (`OffsetLabel::short`: "1d" / "2h" / "30m", or "—"; `OffsetLabel.php:52-67`), with no direction.
     - The hover and the export header use `label` = "Welcome", or `OffsetLabel::amount + ' before'` (:381-383, :417-427), even for AFTER_EVENT rules. Offset ≤ 0 gives "Reminder".
   - The AI-call rule never appears here: EventsController does not reference `FunnelAutomation*`.
6. **Attendance** (`buildAttendanceProp`): null without a webinar. Once ended, `unmatched` = `zoom_webinar_attendances` with `lead_id` null, grouped by email (fallback `participant_uuid`) (:1241-1246). These are the "Unknown people".
7. **Client** (`RegistrationsTab.vue`):
   - `isFinalized` (:59-66);
   - cards (:162-195);
   - filters (status / quality / source / manager / campaign / zoom / date), search and the problems toggle in `visibleRegistrations` (:483-499), sorted by `registered_at` desc;
   - conditional columns (:512-586);
   - `DataTable :paginated="false"` (:928).

### 6.4 Metrics

| On screen | Formula | Source | Code |
|---|---|---|---|
| Tab badge | `registrations.length` (unfiltered) | event_registrations | `Show.vue:103` |
| Card Registered | `registrations.length` | same | `RegistrationsTab.vue:170` |
| Card Attended | count status === 2 | status | `:166` |
| Card No-show | count status === 3 | status | `:167` |
| Card Awaiting (physical) | total − attended − no_show | status | `:174` |
| Card Unknown people (Zoom, ended) | `attendance.unmatched.length` | zoom_webinar_attendances, lead_id NULL | `EventsController.php:1241` |
| Cards visibility | (isFinalized OR physical) AND (rows OR unknown). Zoom isFinalized = webinar ended; physical = past and every row is attended or no-show | — | `RegistrationsTab.vue:59` |
| Campaign quick-filter count | rows with `ad.campaign_id = X` (**any source**); label = resolved name or "Campaign {id}" | event_registrations + names | `:257` |
| Drawer Source / Manager / Quality counts | tallies (agent = agent \| agent_linked; fake = fake_state 'fake'; clean = neither) | — | `:226` |
| MESSAGES "N reached" / "N read" / "N problems" | cell counts (§6.3 step 5) | funnel_whatsapp_sends + whatsapp_messages.status | `EventsController.php:402, :404`; `RegistrationsTab.vue:826` |
| Message cell icon | latest send per (rule, lead) → outcomeFor; no send = '—' | — | `FunnelWhatsappSend.php:193` |
| Attended minutes | `attended_minutes` (reconcile: round(seconds / 60)); shown only when attended | — | `ZoomWebinarAttendanceRepository.php:459` |
| Zoom "Clicked link" | join_click_count > 0 | — | `EventsController.php:1055` |
| Registered stamp | `registered_at` ISO +08:00, formatted in the **browser** timezone | — | `RegistrationsTab.vue:937` |
| Message in / out | lifetime 1:1 messages by direction | whatsapp_* | `BuildsLeadEngagementStats.php:110` |
| Zoom Meeting / Webinar minutes | §6.3 step 3b | — | `:82`, `:93` |
| Phone Call / Portal / Property | §6.3 step 3b | — | `:71`, `:130`, `:139` |
| Member chip (+N) | ACTIVE subscription names | — | `:441` |
| AI Call chip | latest call duration (any funnel) | ai_voice_calls | `EventsController.php:1124` |

### 6.5 Write paths

**A. Add lead.** `POST /manage/events/registrations` (web.php:377, `manage-events`). The modal posts `{event, lead_uuid}` (`AddRegistrationModal.vue:60`). A physical session with "walk-in" ticked posts to `/check-in/walk-in` instead (:56-58).
- **Validation.** `RegistrationStoreRequest` (:42-45) only checks that the `event` and `lead_uuid` uuids exist. There is **no LeadVisibility or is_staff check** on the plain path. The workflow variant adds MANAGE_EVENTS in `authorize`, plus LeadVisibility, `is_staff = false` and `WorkflowSessions::eligibleSessions` (:47-79). The picker `/manage/leads/search` is visibility-scoped (`LeadsController.php:264`).
- **Controller** (`RegistrationsController.php:48-99`): `source = SOURCE_ADMIN`, `join(restoreRemoved: ! has('workflow_funnel_uuid'))` (:55-57).
- **`join()`** (`EventRegistrationRepository.php:35-87`):
  1. `data_only` whitelist, then `DB::transaction`;
  2. lock the event `FOR UPDATE`;
  3. delete tombstones when restoring;
  4. return the existing row if there is one;
  5. throw `RemovedRegistrationException` if a tombstone still blocks;
  6. otherwise `firstOrCreate` with status REGISTERED, the source, `registered_at = now()` and the ad snapshot.
- **New rows only:**
  - the ticket. This is a **synchronous** `Mail::send` (`EventTicketMail` is not queued) and goes only to a physical session with `email_tickets` on, a lead email and a ticket URL (`SendEventTicketAction.php:30-46`);
  - an ActivityLog `TYPE_SESSION_REGISTERED` line (:60-87).
- **Always**: `SyncSessionWebinarRegistrantsAction::forEvent` → `SyncWebinarRegistrants` for a webinar that is UPCOMING or LIVE (:91; `SyncSessionWebinarRegistrantsAction.php:34-38`).
  - The job is unique for 600 s, batches 150, paces 0.2 s, pushes rows without `zoom_registrant_id`, and saves the registrant id and join URL (`SyncWebinarRegistrants.php:140-198, :266`).
- **No welcome or AI call at add time.** But timed reminders still reach admin-added rows, because `RunFunnelReminders.php:257-275` has no source filter.

**B. Status select.** `POST /registrations/{uuid}/status` (manage-events). `status ∈ {1, 2, 3}`.
- `markStatus` sets the status, and `attended_at` = now when Attended, else null. It **never** sets `attended_minutes` (:274-290).
- Then `FunnelJourneyHooks::registrationMarked`, fail-soft (`FunnelJourneyHooks.php:530-539`).
- The UI shows the select only when the user has manage-events AND (the session is physical OR past) (`RegistrationsTab.vue:628`). The **backend does not check this**, and Zoom `finalizeAttendance` later overwrites the value.

**C. Reminders off** (working tree). `POST /registrations/{uuid}/reminders` `{muted: bool}` → `setRemindersMuted` writes `reminders_muted_at` / `_by` in a transaction (:374-383). No Zoom call is made.
- Muted rows are skipped by:
  - both scanners, for before **and** after rules (`RunFunnelReminders.php:257-275`; `RunFunnelAutomationReminders.php:136-150`);
  - `EnsureFunnelHumanContact` (:51-52);
  - `FunnelJourneyHandoff::forRegistration` (:294-297).
- It is also set by a call outcome "join next time" (`HandoffOutcome.php:268-270`) and on CSV or legacy imports (`ZoomWebinarRepository.php:117-118`).
- **The column does not exist on production.**

**D. Remove.** `DELETE /registrations/{uuid}` with `{delete_from_zoom}` (`RemoveRegistrationModal.vue:29-30`; `RegistrationDestroyRequest` authorize = manage-events).
- **Working tree** (`RemoveSessionRegistrationAction.php:33-64`):
  1. When asked, it makes **live** Zoom calls inside the request: `getWebinar` (:86-120), registrant lookup by id or by exact email (≤ 20 pages × 300) (:132-163), then `deleteWebinarRegistrant`.
  2. Then `remove()` (:393-437): lock, write a tombstone (lead_id, registrant id, normalised email, plus aliases), null `event_registration_id` on attendances, responses and chats, then **hard delete**.
  3. A late Zoom id dispatches `RemoveLateWebinarRegistrant`. A `ZoomApiException` keeps the row.
- **Production**: plain delete.

**E. Copy join link.** `GET /registrations/{uuid}/join-link` (manage-events, web.php:385).
- Returns 422 when the row is not a Zoom registrant.
- Otherwise `ensureJoinToken` mints the token with a race-safe conditional UPDATE (`EventRegistrationRepository.php:224-246`), and the response is the URL for `/zoom/{token}` (`routes/main.php:406-408`; `RegistrationsController.php:186-199`).
- This is a **GET that writes**. The button sits only in the Zoom column, on `is_registrant` rows, with **no permission check** in the Vue (`RegistrationsTab.vue:1116-1131`), so viewer-only admins get a 403.

**F. Import CSV.** Preview and import (manage-events + manage-leads).
- `BulkMemberImportAction` creates or matches people.
- `join(SOURCE_IMPORT, restoreRemoved: false)` (`RegistrationsImportController.php:94-124`); ticket and ActivityLog on new rows; Zoom sync. No welcome.
- **No try/catch.** A tombstoned person aborts the request at that row: earlier rows stay committed and the Zoom sync is skipped.
- Flash: registered / already / skipped (`:159`).

**G. From Preview** (working tree; only when `funnel.candidate_source_funnel_id` is set).
- `PreviewCandidates::candidates` (:151-219): non-staff registrants of the source funnel's non-cancelled sessions between `since` and this session's start, minus people already on this session.
- The store re-intersects the ticks and refuses a started or cancelled session (`PreviewCandidatesController.php:88, :95-96`).
- Then `join(SOURCE_FROM_PREVIEW)`, ticket, ActivityLog, the journey hook, `DispatchFunnelWelcomeAction(fromLanding: false)` and Zoom sync (:101-139). No try/catch.

**H. Physical door** (not session 31).
- Walk-in: `EventRegistrationRepository::walkIn` (:303-335).
- Close attendance: bulk REGISTERED → NO_SHOW, then the journey hook (:347-361; `CheckInController.php:138-153`).

**Export.** `GET /manage/events/{uuid}/registrations/export` (web.php:427, group gate only).
- `abort_unless(lead level)` (:229). Same load and transform (:231-234). Messages only for view-events (:239).
- `RegistrationRosterFilter` over `$request->all()` (:246), which ignores the forwarded `suite` and `tab`.
- File name `registrations-{slug}[-filtered]-Ymd-His.xlsx|csv` (:254-255).
- `EventRegistrationsExport` is FromCollection (:119-215).

### 6.6 Session 31 on this tab

These are production snapshots at different times, and they keep changing.

- **Earlier slice snapshot:** 123 rows, all Landing / Registered; Zoom 114 On Zoom and 9 Paused (no_phone, 0 attempts; these re-open automatically when a phone is added); 122 with an ad object.
- **17:29 MYT:** 124 rows (§9).
- The webinar is Upcoming (webinar 178, status 1), so the tab shows no cards, no Status column, no Account-manager column and no door buttons.
- MESSAGES columns: rule 5 Welcome (scope "AI买房训练营"), rule 6 "1d", rule 7 "30m".

### 6.7 Gotchas

- **Production ≠ working tree.** Mute, tombstones, Zoom delete, From Preview and `context_event_id` are **dev-only**. Deploying the working-tree `buildMessagesProp` before its migration would make the Messages query fatal.
- **Visibility.** A `view-leads-own` agent sees, and can export, every registrant's phone and email.
- **Staff and test leads** are not excluded. Only From Preview excludes `is_staff` (`PreviewCandidates.php:182`).
- **One prop, every load.** The whole roster ships on every full load, even when Summary is the tab showing. `transform()` lazy-loads all registrations on every request.
- **Status edits** are blocked only in the UI. `markStatus` leaves the minutes null.
- **MESSAGES band:**
  - inactive rules still get a column, all "pending";
  - deleted rules vanish together with their sends;
  - AFTER rules are mislabelled "before";
  - AFTER_ENDED rules are never shown;
  - "problems" counts cells;
  - a legacy welcome with both event ids NULL can colour this session's Welcome cell.
- **Lifetime context.** AI Call, Engagements, Member and Pipelines describe the lead's whole history, not this session.
- **`ad` object edge cases.** It is null when only `adset_id` is set. With `ad_id` set but `campaign_id` null, the cell reads "Campaign null".
- **Removed people** (working tree):
  - The landing swallows the exception (§7). Its logs are silent because `RemovedRegistrationException` extends `ValidationException`, which is in Laravel's `internalDontReport`.
  - CSV import and From Preview abort mid-loop.
- **Timezone.** The date filter compares the MYT day (first 10 characters), but the display uses the browser timezone.
- **Search** is a raw substring match: `012…` will not match `+6012…`.
- **From Preview window.** The GET window starts at the previous session's exact start. The POST re-parses `since` as `startOfDay`, which is slightly wider.

---

## 7. Page 6 — Slot landing and registration capture

### 7.1 Purpose

The public page that Meta ads point at: `/{funnel-slug}/{slot-slug}`, e.g. `/investment-masterclass/ai-masterclass`.
- The server picks **one** session. The visitor never chooses a date.
- One Vue design is rendered, carrying a `tracking` bundle.
- Every design that captures a registrant opens `LeadCaptureModal`, which POSTs `/register`.
- The GET itself writes nothing: no visit table, no cache, no job, no Graph call.

### 7.2 Files

| Layer | File |
|---|---|
| Routes | `routes/main.php`: catch-alls at the end, :1145-1203; `POST register` :79-81 (`throttle:10,1`); `thank-you` :139; `thank-you/phone` :150-152 |
| Controllers | `app/Http/Controllers/Main/LandingController.php` (`index` :53-57, `sessionLanding` :333-339, `slot` :341-482, `register` :678-888, `aiCallWelcomeRule` :950-971, `mergedLandingRedirect` :981-994); `ThankYouController.php`; `ConsultationController.php`; `VideoProgressController.php` |
| Support | `src/Event/Support/PublicSlotResolver.php` (WT, untracked); `EventSeries.php` (`landingPath` :117-120, `finalPoster` :179-186); `app/Support/StructuredData.php` |
| Request | `app/Http/Requests/Main/RegisterRequest.php` |
| Actions | `app/Actions/RegisterLeadAction.php`; `DispatchFunnelWelcomeAction.php`; `EnrollLeadInFunnelSessionsAction.php` (prod only) |
| Repos | `LeadFunnelRepository`, `SlotRegistrationRepository` (WT), `EventRegistrationRepository` |
| Vue | `Pages/SlotLanding.vue`; `Pages/Landings/**`; `Components/LeadCaptureModal.vue`, `LeadCaptureForm.vue`, `PhoneInput.vue`; `Pages/ThankYou.vue` |

### 7.3 Routing (working tree)

- Route files load in this order: company-entry, APIs, `web.php`, then `main.php`, all under the `web` group (`RouteServiceProvider.php:33-38, :62-70`). The first match wins.
- `web` middleware: EncryptCookies, StartSession, SetLocaleTimezone, CSRF, LogRequest, HandleInertiaRequests (`Kernel.php:23-35`). Global middleware: TrimStrings and ConvertEmptyStringsToNull (`Kernel.php:17-18`).
- **Catch-alls in `main.php`, declared last:**
  - `GET {slug}` → `index` (:1145-1147);
  - `{slug}/video` (:1153-1155);
  - `{slug}/supply`, `{slug}/demo` (:1162-1174);
  - `POST {slug}/video/progress`, `{slug}/consultation` (:1179-1190);
  - `GET sessions/{id}/register` → `sessionLanding` (:1195; no regex, no throttle);
  - `{slug}/{slot}/video` (:1196);
  - `GET {funnel}/{slot}` → `slot` (:1200-1203).
- **Shadowed slugs.** Earlier routes take precedence: the cinematic routes (:26-46), `/{country}` with 2 letters (:231), and two-segment literals such as `book/{slug}`, `offer/{slug}`, `pay/{id}`, `membership/plans`, `zoom/{token}`.

### 7.4 GET `/{funnel}/{slot}`: step by step (working tree)

1. **Merged funnel.** `mergedLandingRedirect` (:343-345, :981-994): if the funnel was merged, redirect to the active origin slot with the same slug in the destination funnel, keeping the query. Otherwise 404 (:986-989). Slot aliases are ignored here.
2. **Empty slugs** → log and 404 (:346-356).
3. **`PublicSlotResolver::resolve(funnel, slot)`** (:14-28). Direct match: slot `is_active` + slot PUBLIC + funnel active + `merged_into_funnel_id` NULL + both slugs equal. Otherwise the alias `funnel/slot` from `slot_landing_aliases` (written by slug renames, `EventSeriesRepository.php:126-128`) with the same filters. Otherwise 404.
4. **Alias hit** → redirect to the canonical `landingPath` with the query (:360-362).
5. **Members-only slot** → 404 (:368). Effectively unreachable, because the resolver requires PUBLIC.
6. **Session auto-pick** (:373-379): `Event::where(event_series_id = slot)->with('webinar')->whereDate(scheduled_date >= now()->toDateString())->orderBy(scheduled_date)->orderBy(start_time)->get()`, then the **first** row with `live_status === 'upcoming'`.
   - `now()` is MYT. Soft-deleted rows are excluded.
   - **No filter** on `events.visibility`, no capacity concept (no capacity column, `Event.php:83-92`), and `promo_*` is not used.
   - A session drops off the page at `start_time`, or earlier if Zoom goes LIVE.
7. **`/sessions/{uuid}/register`** (`sessionLanding`, :333-339):
   - Needs the event (not deleted) with a series and `visibility = PUBLIC` (:336). A null `series->funnel` would be fatal (:338).
   - It then calls `slot()`, where the resolver also applies.
   - The forced session is `$slotModel->events()->findOrFail(id)` (:381-383), used **even if past, live or cancelled**.
8. **Preview** (:387): `preview = (session && live_status !== upcoming) || $request->boolean('preview') || (slot.origin_funnel_id && session === null)`.
   - `boolean()` accepts `1`, `true`, `on`, `yes`. A bare `?preview` is false.
   - There is **no admin check**.
   - 404 only when there is no session AND no preview AND the slot is not VSL (:388).
9. **SEO.**
   - Canonical: `/sessions/{uuid}/register` on the session route, else `landingPath` (:390).
   - `og:image`: the final SlotPoster media, else `og_media_id`, else the site default (:393-398).
   - JSON-LD: `StructuredData::event` in user_timezone (`StructuredData.php:58-98`; :399-409).
   - No `noindex`, even in preview.
10. **Render `SlotLanding`** (:411-481) with these props:
    - `slot` {uuid, type, landing_design, video_url, design_funnel_slug = originFunnel.slug, slug, title, description, start / end HH:MM, mode, mode_label};
    - `poster`, `poster_width`, `poster_height`;
    - `session` {uuid, scheduled_date, start / end HH:MM, mode, mode_label} or null;
    - `preview`;
    - `aiCallOffered = aiCallWelcomeRule(funnel, slot) !== null` (:450; :950-971: an active `FunnelAutomationMessage` with medium 4 and trigger 1, slot-scoped before funnel-wide, slot-only for merged slots, with `aiCallProfile.isCallable()` = ACTIVE and synced to Retell, `AiCallProfile.php:725-728`);
    - `funnel` {name = **slot title**, type, landing_url, slug, uuid, whatsapp_group_link = the slot's};
    - **`tracking`** {utm_source / medium / campaign / content / term, fbclid, campaign_id, adset_id, ad_id, placement, read **raw** from the query; `landing_url = fullUrl()`; funnel uuid; `event` = session uuid or null; `slot` uuid} (:459-477);
    - `community = config('whatsapp.community_link')`.
11. **Design pick** (client, at build time; `SlotLanding.vue:28-35`).
    - Eager glob of `./Landings/**/*.vue`. `path = slot.landing_design || (design_funnel_slug || funnel.slug) + '/' + slot.slug`. Render `./Landings/{path}/Index.vue`, else `DefaultSlot.vue`. The server never checks that the file exists.
    - `landing_design` is written only by the upgrade (`SlotOperationsRepository.php:55-67, :76`); SeriesController never maps it.
    - New slots get a starter file only when `app()->isLocal()` (`SeriesController.php:109-115`). This server is APP_ENV=production.
    - **Prod** key: `./Landings/${funnel.slug}/${slot.slug}/Index.vue`.
12. **`/{slug}`** (WT `index`, :53-57): the resolver looks up the alias `path = slug` (`PublicSlotResolver.php:27-28`) and 302s to `landingPath` with the query. With no alias row → 404.
    - Root aliases are written only by the one-time upgrade, pointing at the funnel's first slot by `sort_order` (`SlotOperationsRepository.php:92-94`).
    - **Prod** renders `Landing.vue` → `Landings/{slug}/Index.vue`, else `Default.vue` (**prod** :50-59).

### 7.5 Browser tracking

- The Pixel base code renders only when `META_PIXEL_ID` is set and the path is not `/manage`. It fires PageView on a full load (`meta-pixel.blade.php:14-31`). `app.js` fires PageView on Inertia navigations, with URL de-duplication that decodes `{{macro}}` URLs (`app.js:23-55, :74-77`).
- Opening the modal fires `ViewContent {content_name: funnel.name (= slot title), content_category: 'funnel_registration'}`, with no event id (`LeadCaptureModal.vue:82-93`).
- Submit mints `event_id = crypto.randomUUID()` (`metaPixel.js:52-61`) and fires a browser-only `SubmitApplication` with no eventID (`LeadCaptureForm.vue:136-152`).
- The modal theme comes from `Landings/{funnel.slug}/theme.js` (`LeadCaptureModal.vue:58`).

### 7.6 Capture: `POST /register`

1. **Form state** (`LeadCaptureForm.vue:64-93`): name, phone, email; every `tracking.*` field; funnel, slot and event uuids; `wa_opt_in: true` (always); `ai_call_opt_in: true`, which `form.transform` drops when `aiCallOffered` is false (:156-164); `event_id`.
   - **Client gate**: name not blank, email regex, phone valid for its country (:110-116; `phoneCountries.js:150-188`). PhoneInput emits the dial code + national digits with leading zeros stripped (`PhoneInput.vue:42, :66`).
   - Errors are rendered only for name, phone and email (:119-123).
   - `form.post('/register')` (:169) is the **only** `/register` poster in the codebase.
2. **Route.** `throttle:10,1` (the 11th submit in a minute gets 429); CSRF required.
3. **`RegisterRequest`.**
   - `prepareForValidation`: `phone = PhoneNumber::digits` (strip non-digits); email lower-cased and trimmed (:39-45).
   - Rules (:50-90):
     - name required, ≤ 255;
     - phone required, string, ≤ 30 (**no libphonenumber validity check**);
     - email required, email format;
     - `funnel` required_without event, exists;
     - `slot` nullable uuid, exists (:65, WT);
     - `event` required_without funnel, exists (ignores `deleted_at`);
     - attribution ≤ 255; `landing_url` ≤ 2048; `event_id` ≤ 100; opt-ins boolean.
   - On failure: the flash "Please check your details…" (`diver FormRequest.php:36-43`).
4. **Controller pre-checks** (`register`, :680-726), with no writes before them:
   - Load the funnel and the event by uuid. A soft-deleted event uuid becomes null, so the next upcoming session is auto-picked **silently**.
   - A merged funnel resolves to the origin slot's next upcoming session, else 422 (:692-700).
   - `slot = event.series`; a posted slot must match, else 422 (:702-707). With no event, the funnel-only post falls back to the resolver (:708-710).
   - 404 unless the slot and funnel are active (:711) and the slot is PUBLIC (:712). 422 if the funnel does not match (:713).
   - **Auto-pick only when no event was posted** and the slot is not VSL (:715-718).
   - 422 "No upcoming session is available for this slot." unless the slot is VSL or the event is `LIVE_UPCOMING` (:719). This fires for a posted session that has **just started**, even when a later session exists.
   - 422 if a VSL slot received an event (:720). 404 for a members-only event (:726).
   - Tracking passed to the action:
     - `fbp = cookie('_fbp')`;
     - `fbc = metaClickId()` = `cookie('_fbc') ?: 'fb.1.<now ms>.<fbclid>'`;
     - referrer, IP and UA (:728-763; `ReportsMetaConversions.php:93-99`).
5. **`RegisterLeadAction::execute`** (:74-328). There is **no outer transaction**; each repository commits on its own, so afterCommit jobs fire immediately.
   - a. Snapshot the prior account (by email, else the email-less owner of the canonical phone) and `accountHadEmail` (:76-90).
   - b. **`resolveAccount`** (:431-500):
     - **(1)** `User::where('email')` (no status or role filter, so a staff email matches). Then `adoptPortalPhone` (`LeadRepository.php:2869-2895`): a no-op if it is the same number; refused if the stored phone is verified or the typed number belongs to another profile; otherwise overwrite. Then `backfillContact` fills blanks only (:870-892). This branch **never** files a merge request.
     - **(2)** Otherwise, an email-less, non-staff phone owner → `adoptEmail` + backfill (:2805-2851).
     - **(3)** Otherwise a new user (ACTIVE, `Str::random(40)` password) + profile (`phone = canonicalDigits`, or NULL when it is taken) + NON_MEMBER role (`UserRepository.php:32-82`). If the phone is taken, a pending `verified_identity_pairs` row is created (:486-497; `LeadRepository.php:1036-1052`).
     - `canonicalDigits` is null only when libphonenumber finds no valid **and** no possible reading (`PhoneNumber.php:260-265`).
   - c. `deliverTo` = stored profile phone ?: typed canonical. `allowAutoLogin` = `!accountHadEmail` && deliverTo matches the stored phone (:103-130).
   - d. Lead `firstOrCreate` by user_id (`LeadRepository.php:144-147`). The `Lead::created` hook creates AI credits and, for non-staff unassigned leads while rotation runs, queues `AssignRoundRobinManagerJob` (60 s delay) (`Lead.php:194-208`).
   - e. **`sanitizeAdTracking`** nulls `campaign_id`, `adset_id`, `ad_id`, `placement` and `utm_campaign` when they contain `{{` or `}}` (:349-360). Everything else (other UTMs, fbclid, landing_url) is stored raw.
   - f. **`lead_funnels`** `firstOrCreate(lead, funnel)` with `registered_at = now()`, `marketing_source = 9`, `ai_call_opt_in` (**true when the key is absent**), UTMs, fbclid, fbp, fbc, ad ids, placement, referrer, landing_url, IP, UA (:147-166).
   - g. **`slot_registrations`** (WT) `firstOrCreate(lead, slot)` (§1.7) (:168-174). There is no try/catch, so on a database without the table it would throw after (f) was committed.
   - h. ActivityLog `TYPE_FUNNEL_REGISTERED`, only when the `lead_funnels` row is new (:190-201).
   - i. **`ResolveMetaAdRefsJob`** whenever the sanitised `ad_id` is non-empty, on **every** submit, afterCommit, default queue (:205-211).
     - It skips ads with a fresh ref (≤ 30 days).
     - It loops `tokenCandidates()`: ACTIVE integration tokens (system-user first, then newest), then the env tokens. That is one `GET /{ad_id}` per token until one succeeds (`FacebookAdsService.php:69-86, :375-397, :957-986`).
     - After `fail_count ≥ 3` the ad is given up permanently (`ResolveMetaAdRefsJob.php:49-79`; `MetaAdRefRepository.php:71-107`).
   - j. **`event_registrations`** when `event_id` is set: `join(SOURCE_LANDING, ad snapshot)` (:216-241), an ActivityLog when new, and `webinarSync->forEvent` (:246-260).
     - All of this sits inside `try/catch(\Throwable) → report()` (:233-264).
     - A removal block yields **no session row** and logs nothing (ValidationException is not reported).
     - A failure *after* `join()` leaves the row in place.
   - k. `FunnelJourneyHooks::landingRegistered` (:271-277). Only when `funnel_journey.enabled` and `event_funnels.journey_kind` is set (no such column on prod). It opens the journey (not for staff), assigns the round-robin manager, and schedules `EnsureFunnelHumanContact`.
   - l. **WhatsApp consent** when `wa_opt_in` and a phone are present: find or create the contact by the E.164 of the **typed** digits, then set MARKETING to OPTED_IN, **overwriting a previous STOP**, with proof (:393-417).
   - m. **`DispatchFunnelWelcomeAction`** (lead, funnel, `seriesId = slot.id`, deliverTo, allowAutoLogin, aiCallOptIn, eventId) (:290-306).
     - WT `chooseScope` = slot rules only (:221-224).
     - WhatsApp → a `funnel_whatsapp_sends` row (QUEUED, `event_id` NULL, `context_event_id` = session) → `SendFunnelWhatsAppMessage`.
     - Automations → `funnel_automation_sends` → the SMS, voice, email or `SendFunnelAiCall` job (the last delayed by `welcomeDelaySeconds`).
     - AI call unticked → SKIPPED (opted_out) + `SendAiCallFollowUp` after 2 minutes. Conditions not met → SKIPPED (condition) (:109-205).
     - **No dedupe**: every submit re-sends.
   - n. `EnrichLeadJob` (unique) (:310-314).
   - o. Returns `lead`, `new_registration` = `(slotRegistration ?? leadFunnel)->wasRecentlyCreated`, `slot_registration`, `slot`, `new_account`, `account_had_email` and the masked email (:316-327).
6. **Controller after-effects** (:769-887):
   - Two `SendMetaCapiEventJob` jobs (afterCommit, tries = 1) (:996-1018, :1086-1096):
     - `Lead` with `event_id`;
     - `CompleteRegistration` with `mb_substr(id, 0, 96) . '-cr'` and status new or returning.
     - `content_name` = `EventFunnel.name`. `event_source_url` = the posted landing_url ?: Referer.
     - The job hashes the user data, and `event_time = time()` **when the job runs** (`MetaConversionsApi.php:51-112`).
   - VSL slot only: `Notifier 'events.vsl_registration'` (:1040-1067) and nurture rotation on a new slot registration (:205-234).
   - `funnel_visitor` cookie (user uuid, 30 days, Lax), member and non-member users only (:791; `ResolvesFunnelVisitor.php:135-156`).
   - `session()->put('thank_you', {...})` (:793-869): slot_uuid, new, email_masked, user_uuid, new_account, account_had_email, welcome_ctx, ai_call {seconds = max(welcomeDelaySeconds, 15), deferred} | null, whatsapp_phone, contact, funnel {name = slot title, landing_url, slug, whatsapp_group_link}, session {title, scheduled_date, start / end HH:MM, mode_label}, event_id, registration_event_id.
   - Redirect: VSL → `landingPath + '/video'`; otherwise → `/thank-you` (:883-887).
7. **Thank-you** (`ThankYouController.php:36-85, :187-204`): no payload → `/`.
   - `ThankYou.vue` fires `fbq Lead` (eventID) and `CompleteRegistration` (eventID-cr) with content_name = slot title (:188-201).
   - AI-call countdown; 7-second auto-redirect to an http(s) group link (:128, :203-239).
   - **There is no OTP step.**
8. **Wrong-number correction**: `POST /thank-you/phone` (`throttle:6,1`) → `updatePhone`.
   - Requires the payload user to be a main user with an unverified phone. Then `updateUnverifiedPortalPhone`, a fresh opt-in, and a **full welcome re-run** (:108-178).
   - It does not pass `aiCallOptIn` or `fromLanding` (both default true) or `eventId`, so an unticked AI call is placed anyway.
9. **Video** (`/{slug}/video`, `/{slug}/{slot}/video`): 404 unless the slot is VSL (:79-82).
   - Access: the matching session payload, the device cookie plus a `slot_registrations` row, or an admin. Anyone else goes to the landing (:99-116).
   - Funnel 4's slots are not VSL, so their `/video` returns 404.

### 7.7 "Do all landing pages use LeadCaptureModal?"

**For public registrant capture: yes, in both versions.**
- `LeadCaptureForm` is imported and mounted only in `LeadCaptureModal.vue` (:6, :118).
- `form.post('/register')` exists only at `LeadCaptureForm.vue:169`.
- Every design that captures a registrant mounts `<LeadCaptureModal>`, either directly or through a wrapper:
  - `cochrane-webinar/*` → `WebinarLanding.vue`;
  - `hk-data/live-demo` → `hk-data/Index.vue`.

**Exceptions and non-registrant forms:**

| Item | What it does | Status |
|---|---|---|
| `cochrane/Index.vue` `knownVisitor` skip (`router.visit` to video, :117-125) | Writes nothing: no `lead_funnels`, no registration, no Pixel/CAPI, no welcome. The return-visit attribution is lost. Fires only when a `lead_funnels` row already exists (**prod** `rememberedRegistrantOf` :233-244, prop :597). | **Live on prod `/cochrane`** (funnel 7, VSL, 344 lead_funnels rows, newest 2026-08-30). **Dead in the WT**: `SlotLanding` never passes `knownVisitor`. If revived, :630 passes an `EventFunnel` to an `EventSeries` param, causing a TypeError. |
| `DefaultVideo.vue` (WT, untracked), `cochrane/Video.vue` (+ ChatBooking) | Own `useForm` → `{video_base}/consultation` → `ConsultationController@store`. Writes `consultation_requests` only, with `lead_id` from the **session** only (no cookie). Can update an unverified profile phone and name. Caller rotation. CAPI `Schedule`. Never creates a lead or registration. VSL only. | Video step after registration |
| Cinematic `partners/apply`, `contact` (`routes/main.php:42-43`, only with `site.cinematic_home`) | `partner_applications` / `enquiries` (+ CV); founder email + WhatsApp alert. No lead or registration. | — |
| `/{slug}/supply`, `/{slug}/demo` | Read-only JSON for whitelisted slugs, cached 720 minutes. Nothing calls them in the WT. | — |
| `grade-a`, `ai-prompt-class-for-investment-testing-slot`, `hong-kong/physical-eventssss` | Embed the modal behind a per-session button, but the scaffold declares a `sessions` prop (`MakeSlotLanding.php:91`) that SlotLanding never passes. They show "No upcoming sessions yet." with no button. | **Dead as capture** |
| `Pages/Landing.vue`, `Landings/Default.vue` | Unreachable in the WT | Prod `/{slug}` only |
| Funnel-level designs (`Landings/{funnel}/Index.vue`) | WT: reachable only when `landing_design` equals the funnel slug (the upgrade-minted VSL slot), or when imported by a slot design. They read `props.events`, which SlotLanding never passes. | Prod `/{slug}` |

**But not every *registrant* comes through a landing.** The following write registrants (or funnel-tied leads) without the modal. **None** of them carries ad ids into `event_registrations`, and none fires Pixel or CAPI:

| # | Path | Writes |
|---|---|---|
| 1 | Admin Add / workflow (`RegistrationsController@store`) | `SOURCE_ADMIN` |
| 2 | CSV import | `SOURCE_IMPORT`; leads via `BulkMemberImportAction` (`lead_funnels` SOURCE_OTHER, funnel NULL, `:515-523`) |
| 3 | From Preview | `SOURCE_FROM_PREVIEW` + welcome (`fromLanding: false`) |
| 4 | Door walk-in | `SOURCE_WALK_IN` + ATTENDED |
| 5 | Zoom registrant import: every 5 minutes (`Kernel.php:388-390`; webinars with event_id, registration_url, UPCOMING / LIVE, start ≥ now − 6 h) and once on link (`LinkSessionWebinarAction.php:78`); approved registrants only | `SOURCE_ZOOM` on **new** rows only; `registered_at` = import time; `WebinarRegistrantLinker` may mint a lead + `lead_funnels` SOURCE_OTHER with the session's funnel |
| 6 | Zoom attendance reconcile `createWalkIns` (`ReconcileWebinarAttendance.php:502-527`) | `SOURCE_WALK_IN`; may mint a lead (`WebinarAttendeeLinker.php:220-233`) |
| 7 | VSL roster backfill (`FunnelsController@storeVslLead`, :2039-2111) | `lead_funnels` SOURCE_FUNNEL (new rows only) + `slot_registrations` (copies any existing ad ids) + optional video views and consultations |
| 8 | Meta Lead Ads (`SyncFlgLeadToCrmAction`, :99-113) | `lead_funnels` SOURCE_META_LEADGEN, funnel NULL, ad ids (unless a NULL-funnel row already exists); password = email (:60) |
| 9 | Property Match, Rental Estimate, WhatsApp / CTA, Messenger (keeps ad ids), LINE, Stripe, calls, manual create | `lead_funnels` funnel NULL; no `event_registrations` |

- The session **Ads tab and both session CPLs count only `source = 1`**. Paths 1–6 appear on the roster but never in the ad maths.
- **VSL registrations never create `event_registrations`.**

### 7.8 Funnel 4 worked example (production)

**Slots**

| Slot | Slug | Sort | State | Sessions | Design |
|---|---|---|---|---|---|
| 5 | `ai-masterclass` | 1 | active, public | 8 live (ids 5, 9, 10, 13, 17, 23, 31, 32); event 24 soft-deleted 2026-09-17 | Bespoke `Landings/investment-masterclass/ai-masterclass/Index.vue`: props :17-25, modal at :920 |
| 10 | `ai-prompt-class` | 4 | active | 4, all past (11, 12, 25, 28; latest 2026-09-28) | No design file, so `DefaultSlot.vue`. **The public page currently 404s** unless `?preview=1`. |
| 6 | `trx-vs-klcc-vs-bandar-sunway` | — | soft-deleted 2026-07-28 | — | — |
| 7 | `renovation` | — | soft-deleted 2026-07-28 | — | — |

**What a visitor sees on slot 5 today**
- `GET /investment-masterclass/ai-masterclass?…` auto-picks **event 31** (2026-10-14 20:00–22:00, status 1, webinar 178 status 1), with `preview = false`. The modal theme is `investment-masterclass/theme.js`. Event 32 (2026-10-28) is next.
- 245 of 268 funnel-4 registrations since 15 Sep landed on this URL.
- **AI call.**
  - Prod funnel-level rule 1 (medium 4, trigger 1, series NULL, profile 2 "训练营报名欢迎 Call", callable, offset 20 s) shows the checkbox. It fires on prod: 555 sends in total, the last at 2026-10-11 17:15:49.
  - **WT without the upgrade**: the checkbox and countdown still show (`aiCallWelcomeRule` :963-965 accepts series NULL), but **no call is placed**. `chooseScope` drops the rule, and `SendFunnelAiCall.php:135` would skip a series-less rule anyway.
  - On dev the upgrade ran, so rule 1 should now sit on slot 5, with a replica on slot 10 (derived from `SlotOperationsRepository::moveRules` :111-151; not queried).
- **WhatsApp welcome**: rule 5 (series 5) fires in both versions (848 sends; latest 17:15:49).

**Other funnel-4 URLs**
- **`/investment-masterclass`**: WT 302 → `/investment-masterclass/ai-masterclass`. Prod renders `Landings/investment-masterclass/Index.vue` with funnel-wide enrolment.

**Design-file quirks of the `ai-masterclass` design**
- **Countdown**: parses `${scheduled_date}T${start_time}:00` in the **browser's** timezone, but is labelled "Asia/Kuala_Lumpur" (:104-110).
- **Marketing copy**: "价值 RM97", "100+赢家" and "RM50,000" are hard-coded (:840).
- **CTA buttons are never disabled.**

### 7.9 Metrics

| On screen | Formula | Source | Code |
|---|---|---|---|
| Session date on the landing | `scheduled_date` of the auto-picked session | events + zoom_webinars + clock | `LandingController.php:373` |
| Session start–end | substr(start_time / end_time, 0, 5), MYT wall clock | events | `:442` |
| Slot default time · mode (DefaultSlot, non-VSL) | substr(event_series times) · mode_label | event_series | `:421` |
| Countdown d / h / m / s (ai-masterclass) | max(0, Date(start) − Date.now()), browser timezone | session prop | `ai-masterclass/Index.vue:110` |
| Thank-you AI-call countdown | max(welcomeDelaySeconds, 15); deferred = hour < 9 or ≥ 21 in user_timezone (`PlaceAiVoiceCall.php:222-231`) | funnel_automation_messages + ai_call_profiles | `LandingController.php:919-937` |
| Thank-you new vs returning | slot (or funnel) row `wasRecentlyCreated` | slot_registrations / lead_funnels | `RegisterLeadAction.php:318` |
| Thank-you WhatsApp number | '+' + (stored profile phone ?: typed) | user_profiles | `LandingController.php:827` |
| Thank-you session date / time | `toLocaleDateString('zh-CN')`; HH:MM → 12-hour, no tz conversion | events | `ThankYou.vue:53-62`; `LandingController.php:854-856` |
| Group auto-join | constant 7 s; only an `^https?://` link | slot link ?: community link | `ThankYou.vue:128` |

### 7.10 Gotchas

- **Two versions** (§0.3).
- **Deploy traps:**
  - WT code without the migration → every `/{slug}` hit and every 2-segment alias miss queries a missing table and returns **500**.
  - Without the upgrade → `/{slug}` 404s, and `register()` fails on `slot_registrations` **after** `users`, `leads` and `lead_funnels` are already committed (the production handler shows a generic flash).
  - Funnels created after the upgrade get no root alias.
- **`_fbp` / `_fbc` are effectively never captured.**
  - `EncryptCookies::$except` is empty (`EncryptCookies.php:14-16`), so Laravel nulls the Pixel's plaintext cookies.
  - Prod `lead_funnels` (2026-10-11 16:57): 13,340 rows; fbclid 1,204; fbc 1,183 (all `fb.1.%`, none without an fbclid); **fbp 0**.
  - The 21 rows with fbclid but no fbc date from 07-25 → 07-29, before the column existed.
  - fbc is rebuilt with the **registration** time, not the click time.
- **Session starts mid-form.** A visitor who loaded the page before the start and submits after it gets a 422 error page; no lead is saved and there is no fallback session. A Zoom-side CANCELLED webinar is not handled, so such a session is still auto-picked.
- **Members-only next session.** It is shown, then `register()` 404s.
- **`/sessions/{uuid}/register` for a past session** renders an enabled form (DefaultSlot disables only when `session` is null, :68), which then 422s.
- **AI-call consent.** `ai_call_opt_in` is recorded **true** when the box was never shown.
- **Hidden-field validation errors** (utm > 255, landing_url > 2048, a stale event) show only the generic flash.
- **`funnel.name` is the slot title** (WT). The browser `content_name` (slot title) differs from the CAPI one (funnel name). DefaultSlot's `<Head>` reads "{slot title} — {slot title}".
- **Poster dimensions.** `poster_width` / `poster_height` are snake_case, but SlotLanding declares camelCase props, so width and height are likely never bound (unverified).
- **"Returning" is per slot.** A person registering for a later session of the same slot sees "您已报名 ✓" and gets CAPI `status=returning`, even though a new `event_registrations` row was created.
- **Re-submits re-send every welcome**, and two tabs place two AI calls. WhatsApp marketing is re-opted-in over a STOP.
- **Staff email at the public form.** It resolves to the staff account. `adoptPortalPhone` has no staff guard. Staff still get welcomes and the AI call, but no cookie, no rotation and no journey.
- **Email path never files a merge request.** If the typed phone belongs to another account, the welcome goes to the account's **old** stored phone.
- **New account whose phone was taken.** WhatsApp goes to the typed number, but `SendFunnelAiCall` dials `user_profiles.phone` (NULL) → SKIP `no_phone` (:200-206).
- **Banned or inactive users** matched by email are reused. Merged-loser accounts are never matched (their email and phone are nulled, `LeadRepository.php:1454-1460`).
- **`mergedLandingRedirect`** ignores aliases, so a renamed merged slot's old URL 404s.
- **The landing no longer sends the physical-session ticket email**, and `EnrollLeadInFunnelSessionsAction` / `renderLanding` are dead code in the WT.
- **Lead merge does not re-point `slot_registrations`.**
- **No session capacity check exists anywhere.** The Zoom sync special-cases only the per-registrant daily limit (`SyncWebinarRegistrants.php:227-231, :312-315`).

---

## 8. Cross-page reconciliation

### 8.1 How each figure is built

| # | Figure (page) | Source | Attribution key | Allocation | Window | Date column | Code |
|---|---|---|---|---|---|---|---|
| 1 | Traffics row Spend | meta_ad_insights | row's own grain id (≠ '') | none | rolling or custom, inclusive | `date` (account day) | `AdPerformanceService.php:134-148` |
| 2 | Traffics Our leads | lead_funnels | **global** first Meta-signal row; must carry the grain id | n/a | `registered_at` in window | registered_at | `:187-196, :205, :231-235` |
| 3 | Traffics CPL / Revenue / ROAS / Buyers | + purchase_histories | same cohort | CPL = row spend / row leads | revenue **lifetime**, any currency | n/a | `:213-230, :268, :274` |
| 4 | Traffics Total revenue / Profit tile | purchase_histories | none (every ACTIVE row) | — | `purchased_at` in window | purchased_at | `CampaignsController.php:285-288, :297` |
| 5 | Dashboard KPI Ad spend | meta_ad_insights | campaigns seen on in-range funnel `lead_funnels` + campaigns tied on Campaign Mapping | none | range or all time | date | `FunnelDashboardService.php:106-107, :381-395, :405-415` |
| 6 | Dashboard KPI Leads / CPL | lead_funnels (funnel, source 9) | funnel's own row, **organic included** | spend / distinct leads | registered_at | registered_at | `:88-94, :152` |
| 7 | Dashboard Revenue / ROAS | purchase_histories | that cohort | lifetime / scope spend | lifetime | — | `:123-126, :157-158` |
| 8 | Dashboard per-session CPL | event_registrations + insights | cplForEvents | proportional | attributed reg days | created_at | `:450, :476-478` |
| 9 | Dashboard per-session Ad spend | = #10 | promotionSpendForEvents | none | promotion window | — | `:451, :481-483` |
| 10 | **Sessions "Ad spend" = Ads "Spent promoting" = Summary "Ad spend"** | event_registrations (campaign list) + insights | every campaign on this session's source = 1 rows, any date | none (whole spend) | promotion window | date | `SessionAdInsightsService.php:346-403` |
| 11 | **Sessions "CPL" = Summary "CPL"** (report) | #10 / event_registrations | this session's source = 1 rows, tracked or not | none | created_at in [since, min(until, today)] | created_at | `:552-602` |
| 12 | **Sessions Sold / ROAS = Summary Revenue / Return ×**; Ads revenue | purchase_histories.event_id | PurchaseSessionAttributor stamp | ROAS = **MYR** / #10 | payments credited to the session | — | `:473-513`; `FunnelsController.php:3518-3523`; `SessionSummaryService.php:151-154` |
| 13 | Ads headline (Leads from ads / Allocated / Session CPL) | event_registrations + insights | this session's source = 1 rows with campaign_id | proportional across **all** sessions' landing rows that day | first to last attributed day | DATE(created_at) | `:203, :225-291, :878-888` |
| 14 | Ads rows | same, at the grain | grain id | allocated; plus window spend | same | same | `:98-214` |
| 15 | Summary Funnel-month bar | meta_ad_insights (all) | none | none | 1st of month → today | date | `FunnelDashboardService.php:194-214` |

None of these removes staff, test or merged leads.

### 8.2 Figures that always agree (same code, same moment)

| Group | Figures | Why |
|---|---|---|
| A. Promotion spend | Sessions Ad spend = Ads "Spent promoting" = Summary Ad spend = Dashboard per-session Ad spend | All call `promotionSpendForEvents`. Each session sums only its own campaigns and days (:391-399), so batch size does not matter. |
| B. Report CPL | Sessions CPL = Summary CPL; "÷ N landing" = Summary "Landing page leads" | `reportCplForEvents`; Summary `$regs` uses the same bounds (:71-74) |
| C. Allocated CPL | Ads headline = Dashboard per-session CPL = Summary footnote | `cplForEvents`; global day counts plus a union window, so batch-invariant (:269-271) |
| D. Session revenue | Sessions Sold = Ads revenue block = Summary Revenue / What sold; Sessions ROAS = Return × | `revenueForEvents`, with the same MYR ÷ promo division |
| E. Roster | Sessions Registered = Summary "On the roster" = Registrations tab count | count or load of `Event::registrations()` |
| F. Landing, all-time | Sessions "N landing" = Ads "/ M" = Ads empty-state count | source = 1, no date filter |

**Caveats for all groups:** pages loaded at different moments can straddle an hourly sync, and each page uses its own "today".

### 8.3 Why one campaign or session shows different numbers

1. **Different attribution keys for the same person.**
   - Traffics credits the person's **global** first Meta-signal `lead_funnels` row.
   - Session pages credit **this session's** `event_registrations` snapshot.
   - `lead_funnels` is first-touch per funnel. So a returning funnel-4 person who comes back via a new ad gets a new session row carrying that ad, but Traffics still credits their first ad. In a returning-audience webinar funnel this is usually the largest gap.
2. **Ids lost on the Traffics side.**
   - A first-touch row with only fbclid/fbc, or with macro-nulled ids, counts on no Traffics row, but still sits on the roster and in the report-CPL divisor.
   - An earlier Lead Gen or Messenger NULL-funnel row with ad ids becomes the first touch, and the person is counted under that ad in that earlier window.
3. **Different lead groups.**
   - The Dashboard counts the funnel's source-9 rows, organic included.
   - Traffics adds Lead Gen and Messenger and drops organic.
   - The session pages count rows, not people, by `created_at`.
4. **Different campaign sets.**
   - Promotion spend includes any campaign ever named by this session's landing rows, even a single stray old click, with its full spend.
   - The Dashboard uses only campaigns seen on in-range funnel rows, plus tied campaigns.
   - Traffics uses everything in the store.
5. **Different days.** Traffics and the Dashboard use the chosen range. Promotion spend uses the slot schedule (§1.5). Allocated spend uses only days with this session's attributed registrations; days with no registration are left out of the allocated figure but counted in promotion spend.
6. **Allocation versus full spend.** Allocated figures split a shared day. Promotion spend counts it in full on every session whose window covers it. Within one slot, windows overlap only on a 12:xx handover. Cancelled siblings still act as boundaries.
7. **Production fan-out (`origin/master`).** A funnel-root sign-up writes N session rows with the same ad snapshot, across slots and possibly before a session's window. This double-counts promotion spend across rows, splits the allocated spend N ways, and drops out of the report-CPL divisor when the row predates the window. *Session 31 has 0 fan-out rows today* (§9).
8. **Revenue credited to different things.**
   - Traffics and the Dashboard count everything the cohort **ever** paid, in any currency.
   - The session pages count only payments stamped with that session (CTA tap, else last attended, else none). An ad that filled session 31 can have its buyer's money credited to session 32. Someone who paid before attending is credited to no session.
   - Session ROAS is MYR-only.
9. **Different date columns.**
   - Traffics and the Dashboard use `lead_funnels.registered_at`. The session pages use `event_registrations.created_at`.
   - Merge moves the kept row's `registered_at` earlier but leaves `created_at` alone (`LeadRepository.php:2416`), so the roster date can differ from the CPL day.
   - Merge also copies ad ids onto a kept row only if all four ad columns are blank there.
10. **The Dashboard lists only sessions scheduled inside the range** (`FunnelDashboardService.php:444-445`), and every preset ends today (`DashboardController.php:59-60`). Session 31 (14 Oct) appears only under "All time".

### 8.4 When figures from different pages can agree

- **Traffics against a session's Ad spend.**
  - Open Traffics with `?grain=campaign&from=<promo since>&to=<promo until>` and add up the rows for the campaign ids on the session's landing rows. The Registrations-tab Campaign filter lists them (`RegistrationsTab.vue:257-266`).
  - This should equal the Sessions "Ad spend" exactly: the same table and the same `SUM(spend)` per campaign over an inclusive day range.
  - It can differ only by a sync between loads, or by insights rows whose campaign id was stored as `''`.
- **Allocated spend is conserved.** For campaign C, Σ over **all** sessions (soft-deleted included) = Traffics spend for C over just the days on which C produced at least one landing registration.
- **Traffics CPL ≈ report CPL** only if all of these hold, which in practice they never do exactly:
  - C is the only campaign named and feeds only this slot;
  - every landing registrant in the window carried C and was new to Meta signals and to funnel 4;
  - no organic, staff or test registrants, and no rows created before the window;
  - the ad account is on MYT;
  - the Traffics window equals the promotion window.

### 8.5 Registration counts for one session

| Count | Definition | Where it appears | Code |
|---|---|---|---|
| Roster | all rows, any source or status | Sessions Registered, Summary "On the roster", Registrations tab | `FunnelsController.php:303`; `SessionSummaryService.php:93`; `Show.vue:103` |
| Landing (all-time) | source = 1 | Sessions "N landing", Ads "/ M" | `FunnelsController.php:332-338`; `SessionAdInsightsService.php:250` |
| Other | source ≠ 1 | Sessions "N other"; Summary "+N other" (which mixes in early landing rows) | `FunnelsController.php:339`; `SummaryTab.vue:140` |
| Landing in window | source = 1, created_at in [since, min(until, today)] | Sessions "÷ N landing", Summary "Landing page leads", geo and quality | `SessionAdInsightsService.php:573-592`; `SessionSummaryService.php:71-76` |
| Ad leads | source = 1 + non-empty campaign_id, any date | Ads "Leads from ads" | `SessionAdInsightsService.php:252-257` |
| Grain leads | source = 1 + grain id | Ads rows; `total.attributed` gates the tiles | `:114, :132`; `AdsTab.vue:280` |
| Campaign filter | `campaign_id = X`, **any source** | Registrations drawer | `RegistrationsTab.vue:257-266` |

- Expected order: roster ≥ landing ≥ ad leads, and landing ≥ landing-in-window.
- The campaign filter can exceed the Ads row count when a merge copied ad ids onto a non-landing row.

---

## 9. Session 31 worked numbers (production, 2026-10-11 ~17:30 MYT)

**Promotion window:** since 2026-10-01, until 2026-10-14 (§1.5). No overrides.

**Registrations**
- 124 rows, all `source = 1`, `status = 1`, from 124 distinct leads.
- 123 carry `campaign_id = 120248955963780194` (2026-10-01 05:26:35 → 2026-10-11 17:15:49; 5 ad sets, 17 ads).
- 1 row (2026-10-03 13:19:40) has no ids.

**That campaign appears only on slot 5:** sessions 10 (187 rows), 13 (67), 17 (209), 23 (140; last row 2026-09-30 19:44:41) and 31 (123). It does not appear on slot 10 or any other funnel. The only other landing campaign since 09-30 20:00 is `120250137116960194`, on funnel 10 / slot 16. So session 31 owns 100% of every day's landing registrations for this campaign.

**Fan-out:** 0 rows on another event within 600 s. Session 32 has 0 registrations.

**Spend data:** MYR only. Latest `date` 2026-10-11 (partial); latest `updated_at` 17:00:57. Lifetime 2026-07-30 → 10-11: 47 ads, RM 42,914.59. In the window: 23 ads, 6 ad sets.

| Day | Spend (RM) | Session-31 campaign registrations |
|---|---|---|
| 10-01 | 906.60 | 8 |
| 10-02 | 693.16 | 20 |
| 10-03 | 802.73 | 11 (plus the 1 no-id row) |
| 10-04 | 1,044.22 | 13 |
| 10-05 | 789.21 | 16 |
| 10-06 | 871.58 | 14 |
| 10-07 | 758.17 | 8 |
| 10-08 | 766.53 | 6 |
| 10-09 | 786.07 | 7 |
| 10-10 | 707.10 | 12 |
| 10-11 | 471.09 (partial) | 8 |

**What the screens should show at that moment**

| Figure | Value | How |
|---|---|---|
| Promotion spend (Sessions Ad spend = Ads promo card = Summary Ad spend) | **RM 8,596.46** | Grows through 10-14 inclusive, including spend after the 20:00 start |
| Allocated (Ads tiles, Dashboard per-session CPL, Summary footnote) | spend RM 8,596.46; attributed 123; registrations 124; **CPL RM 69.89** | Every window day had ≥ 1 session-31 registration and no other session's |
| Report CPL (Sessions CPL, Summary CPL) | *derived:* 8,596.46 ÷ 124 = **RM 69.33** | All 124 rows were created on or after 10-01 05:26, inside [10-01, today]. Arithmetic from the stated aggregates; not observed on screen. |
| Sessions "Registered / N landing" | 124 / 124; no "other" | — |
| Ads "Leads from ads" | 123 / 124 | — |
| Sold / ROAS / Return × | '—' | No credited payments until a CTA tap on 31 or an attendance stamp exists (`PurchaseSessionAttributor.php:116-122, :148-156`) |
| Show-up / Cost per attendee | '—' | Not yet past |
| Summary derived budget | round(round(monthly / 4, 2) × 14 / 7, 2) | `windowDays` = 14 (10-01..10-14). The monthly setting value was not read. |

**Dev (zs):** 84 registrations, latest 2026-10-07. Spend stops at 2026-10-08. The dev pages will not reproduce these numbers.

**Other observations:**
- Event 5 (2026-07-14) is still `status = 1` although it is in the past.
- Neither CPL query filters registration `status`.

---

## 10. Corrections to the handbook (doc drift)

### 10.1 Handbook pages

**`docs/modules_handbook/manage/meta-ads/marketing/readMe.md`**

| Line | Doc says | Code says |
|---|---|---|
| :41 | 6 KPI tiles | 7 tiles: Spend, Leads, CPL, Attributed revenue, Total revenue, ROAS, Profit (`Campaigns.vue:354-413`). Lines 278-287 already have it right. |
| :42 | Column lists | Both views also show Name, Status and a "Meta leads" column (`Campaigns.vue:144-179`) |
| :42 | Date range options | `from` / `to` windows (This month / Last month / custom) override `?range=` (`CampaignsController.php:219-239`) |
| :147 | `meta_leads` is the Ads Manager figure | Data shows about ×2 (§1.2) |
| :149 | Mixed currencies are "never added up blind" | Every reader sums across currencies |
| :244 | `tokenCandidates()` is used by SessionAdInsightsService | That service has no Graph code. The caller is `ResolveMetaAdRefsJob` (:57). |
| :309, :320 | The Sessions tab uses `cplForEvents` | It shows `report_cpl` and `promo_spend` |
| :324 | Promotion spend is "never divided" | It is divided by report leads, session ROAS, Return × and cost per attendee |
| :326 | `campaignDaySpend()` | Does not exist; it is `daySpend($idCol, …)` (`SessionAdInsightsService.php:904`) |

**`docs/modules_handbook/manage/events/funnels/readMe.md`**

| Line | Doc says | Code says |
|---|---|---|
| :126-128 | From Preview and the "Reminders off" chip | Working tree only; production lacks both columns |
| :210 | Sessions columns Date, Time, Attended | Columns are Session, Status, Ad spend, Registered, CPL, CTA, Sold, ROAS (`SessionsTab.vue:121-136`) |
| :242 | — | Matches the code |
| :308 | `/{slug}` shows the funnel's events; bare `?preview` works | WT redirects to a slot; preview needs a truthy value |
| :310 | `_fbp` / `_fbc` stored; `video_steps` drives the redirect; funnel-wide enrolment; no funnel toggle check | fbp is always null; the redirect is keyed on a VSL slot (`LandingController.php:883`); `video_steps` is unread; enrolment removed in the WT; `register()` 404s an inactive funnel or slot (:711) |
| :314 | Column "?" explains the allocation; names `campaignDaySpend()` | Wrong on both counts |
| :320 | Summary links to the allocated CPL | It is plain footnote text (`SummaryTab.vue:235-238`) |
| :322 | `geo` with `marketing.my_regions` | No such key or config. Telegram renders `geo_grouped` ("Abroad · X" / "Area unknown") (`SessionSummaryService.php:379-446, :596-608`). |
| :323 | Quality counters (three) | Five: `suspected_fake` and `agents` are missing (`:312-358`) |
| :362 | Revenue is compared to the "allocated fraction" | Session ROAS uses promo spend |
| :452 | "The same call the Sessions tab makes" | The Sessions tab does not show that number |

**`docs/modules_handbook/main/landing-lead-capture/readMe.md`**

| Line | Doc says | Code says |
|---|---|---|
| :11 | Route list | Missing `landing.session`, `landing.slot.video`, `.video.progress`, `.consultation` (`main.php:1195-1198`) |
| :28-31 | `index` → `renderLanding` | WT `index` 302-redirects; `renderLanding` is dead (the header at :6 flags the section as superseded) |
| :36-37 | No session deep link; bare `?preview` | `/sessions/{uuid}/register` exists; the 404 is also skipped for VSL and merged slots; `?preview=1` is needed |
| :38, :193 | `Landings/{funnel}/{slot}` key, "none exist yet"; local scaffold is "usable" | `landing_design` comes first; many bespoke designs exist; the scaffold has no Register button (`MakeSlotLanding.php:91`) |
| :42-43 | No DefaultVideo; FunnelVideo replaces design-less funnels | `FunnelVideo.vue:39-43` falls back to the new `DefaultVideo.vue` |
| :51 | Cookie check against `lead_funnels` | Checks `slot_registrations` for the slot (`LandingController.php:242-253`) |
| :52 | `knownVisitor` skip is live | Dead in the WT |
| :60 | RESERVED_SLUGS covers literal routes | Still only `['video']` (`Series/StoreRequest.php:36`) although `/supply` and `/demo` exist |
| :66 | `video_steps` | Unread |
| :100, :128, :172 | Funnel-wide enrolment; ad snapshot on every session; return shape | WT joins one session; `new_registration` is slot-level; it also returns `slot_registration` and `slot` |
| :113 | `thank_you` payload | Also `slot_uuid`, `new_account`, `account_had_email`, `ai_call`, `funnel.landing_url` / `whatsapp_group_link`, `session.title` |
| :126, :164 | Posts only `event`; result is "flashed" | Also posts `slot` and `funnel`; the result is stored in the session key `thank_you` |
| :127 | VSL alert keys on `EventFunnel::isVideoSalesLetter()` | Keys on the slot (`LandingController.php:1042`) |

**Other handbook pages**
- **`funnel-whatsapp/readMe.md`**
  - :16 and :67 (and `funnel-automation/readMe.md:58`): "slot welcome falls back to the funnel welcome". The WT `chooseScope` is slot-only, and the send jobs skip rules with no active slot.
  - :62: the send columns list lacks `context_event_id` (`FunnelWhatsappMessageRepository.php:196`).
- **`meta-ads/pixel/readMe.md:22, :100`** and **`leads/readMe.md:221`**: "`_fbp` / `_fbc` persisted". They are always null (EncryptCookies).
- **`zoom/readMe.md:583`**: covers only "nothing arrived". Missing:
  - "started arrived, ended lost → Live forever";
  - Q&A polling forever;
  - a manual Completed is only a partial fix;
  - `cancel()` is unused.
- **`purchase-histories/readMe.md`**: says nothing about partial refunds, the two Stripe lanes disagreeing, or unhandled disputes.
- **`manage/events/funnels/slot-operations.md:119-123`**: accurate, but the file is untracked.
- **Memory index** (`MEMORY.md`): "2 migrations owed on peta_zs_dev" is stale; they ran.

### 10.2 Code comments and docblocks

| Location | Drift |
|---|---|
| `SessionAdInsightsService.php:55-57, :198-202, :216-220` | `cplForEvents` "is what the Sessions tab reads". It does not. |
| `SessionAdInsightsService.php:309-314` | Promotion spend "must never be divided". It is. |
| `SessionAdInsightsService.php:415-423` | Session revenue "is NOT a ROAS; its denominator is the allocated share". The Sessions column is labelled ROAS and divides by promo spend. |
| `SessionAdInsightsService.php:417-419`; `FunnelDashboardService.php:31`; `EventsController.php:539-541` | "Traffics and the Dashboard share one ROAS". They do not (§8.1). |
| `SessionAdInsightsService.php:527` | Report-CPL divisor is "every landing registration in the window". It is only this session's. |
| `SessionPromotionWindow.php:33-35, :155` | "More than half … never counts one day twice". The code uses `≥ 12`. |
| `FunnelsController.php:3480-3482` | "`ad_spend` is null with no attributed registrations". It is 0.0 (:239). |
| `FunnelsController.php:3486-3488, :3509-3510` | "The Dashboard reads `ad_cpl`". It builds its own rows. |
| `FunnelsController.php:~218-225` | Hub tab list. WT funnel level is Sessions / Slots / (Journey). |
| `SessionSummaryService.php:27-34` | Same CPL-naming drift |
| `SyncMetaAdInsights.php:53-54`; `SyncMetaAdSettings.php:50-63` | "System User token first". There is no ordering. |
| `migrations/2026_07_29_210001…:41-43` | `account_id` "without the act_ prefix". Stored with `act_`. |
| `src/Marketing/MetaAdSetting.php:11` | "Written only by the 4-hourly sync". Also written by Sync now. |
| `LeadFunnelRepository.php:20-22` | "Refreshes `registered_at`". It does not. |
| `RegisterLeadAction.php:230-232, :257-259, :284-289`; `LandingController.php:684-685, :846-847, :966`; `ThankYouController.php:53` | Funnel-wide enrolment / funnel-level welcome fallback. Removed in the WT. |
| `DispatchFunnelWelcomeAction.php:26-30, :130-132, :210-215` | Funnel-level fallback. WT is slot-only (:221-224). `use Src\Event\EventSeries` (:12) is unused. |
| `EventsController.php:90-96` | "Roster not eager-loaded here". `transform()` lazy-loads it at :909. |
| `EventsController.php:141-148` | "Closures are skipped unless requested". True only for partial reloads. |
| `EventsController.php:189`; `Show.vue:42` | Engagement "null when not ended / no data". Non-null whenever a webinar exists (`WebinarEngagementBuilder.php:61-85`). |
| `EventsController.php:275-278, :293-295`; `EventRegistrationsExport.php:252-253` | "withTrashed not needed; deleted rules' sends stay visible"; "cells blank where scope never applied". Deleted rules and their sends vanish; every rule has a cell for every registrant. |
| `Show.vue:83-84` | "Opens on Registrations". Summary is the default. |
| `RegistrationsController` comment "starts no automation (D2)"; `AddRegistrationModal.vue:9-12` | Admin adds still get timed reminders; a landing registrant also gets the welcome, AI call and journey. |
| `RegistrationRosterFilter.php:8, :38-39` | "Eight filter groups". There are nine, including `manager`. |
| `LeadCaptureForm.vue:154-155` | Omitting the field means "nothing recorded as consent". The server defaults it to true. |
| `LeadCaptureModal.vue:16-18`; `LeadCaptureForm.vue:15-17`; `ThankYou.vue:13`; `RegisterLeadAction.php:33-37` | A dual-OTP verify step. None exists; the only `/login` link is commented out (`ThankYou.vue:477-494`). |
| `LandingController.php:34-36`; `SlotLanding.vue:5-8` | Funnel landings render Landing.vue. `index` redirects; `landing_design` resolves first. |
| `LandingController.php:238-240` | `rememberedRegistrantOf` docblock `@param EventFunnel`. The signature takes `EventSeries`. |
| `PurchaseSessionAttributor` docblock; `PurchaseHistory.php:192, :202` | Admin override (`EVENT_ATTRIBUTION_MANUAL`). Nothing writes it. |
| `PurchaseFulfiller.php:43-46` | "A replayed confirm re-activates a refunded row". The code prevents it. |
| `ZoomWebinarRepository.php:626` | Mentions recover-webinar as a fallback. It is manual only, with no scheduler. |
| `SessionsTab.vue:69-70, :165` | Search "by title, slot label and status". Title and status only. |
| `SessionsTab.vue:128-129, :219-221` | "Divides by exactly the number shown". False when rows predate the window. |

### 10.3 On-screen copy that misdescribes its number

- **`CplInfoButton.vue`** explains only the allocated method:
  - Spend = campaign daily spend split by registrations;
  - Leads = rows carrying `campaign_id`;
  - "Nothing is double-counted";
  - text at :29-33, :42-44, :48-50, :56-58, :69-76, :83.

  Where it is mounted:

  | Mounted on | Shows | Mismatch? |
  |---|---|---|
  | Sessions CPL header (`SessionsTab.vue:208-210`) | report CPL | **Yes**: leads are not limited to campaign rows, no allocation, and double counting does occur. Stale since commit 5785fba35 (2026-08-14); the button was last edited in e0d2c12c3 (2026-08-12). |
  | Summary CPL card (`SummaryTab.vue:120` → `KpiCards.vue:28`) | report CPL | **Yes**. The footnote below it is correct. |
  | Dashboard KPI CPL (`Dashboard.vue:127`) | range spend ÷ distinct funnel leads | **Yes**. The card hint is correct. |
  | Dashboard sessions column (`Dashboard.vue:409`) | `ad_cpl` | Would match, but the component **is not imported** (imports :1-15; removed in 0869f15ff), so no "?" renders. |
  | Ads tab (`AdsTab.vue:148`) | allocated headline | **Correct** |
  | `VslAdsTab.vue:109`, `VslSummaryTab.vue:110` | not checked | — |

- **`AdsTab.vue`**:
  - :230 "not divided into anything";
  - :273 "the spend beside it is only the allocated share";
  - :313-315 and :428-429 "same figures as the Sessions tab";
  - :419-422 incomplete gap explanation;
  - :112 "whole window" band = the registration span, not the promotion window shown at :199-209.
- **`SessionsTab.vue`** tooltips:
  - :273 "No ad spend synced" (other causes are possible);
  - the ROAS "No ad spend synced" tooltip, while non-MYR sales also give '—'.
- **`MetricInfoButton.vue:28, :41`**: "OUTBOUND link clicks only". The data is `inline_link_clicks`.
  - CPL copy (:47; `Campaigns.vue:373`) omits the first-touch rule.
  - The worked examples are hard-coded (:23-27, :36-40, :49-53), although the comment at :84 claims they come from a real row.
- **`RoasInfoButton.vue`**: accurate, except "ringgit per ringgit" assumes MYR-only revenue. Nothing explains the two Profits.
- **`Dashboard.vue`**:
  - :130 "Cost / member: Spend ÷ new members" counts any non-deleted subscription;
  - the Revenue card prints RM over all currencies (:38, :131).
- **Summary "+N from other sources"** includes landing rows created before the window.

---

## 11. Open questions

1. **Which production commit is live** after 2026-10-11 04:40 UTC? Prod `LandingController.nextRegisterableSession` (prod :355, :532) was not traced, so prod's slot auto-pick and register checks may differ from §7.4.
2. **Ad-account timezone and currency.** Run one Graph read of `act_…?fields=timezone_name,timezone_offset_hours_utc,currency` for FMX and MKT, and check whether any of the 20 connected accounts spends in another currency.
3. **`meta_leads` double count.** Read one live `actions` array per ad-day, or start storing `actions`, to confirm which types overlap and rule out ×4.
4. **Sync now on production.** What are `QUEUE_DRIVER` and `CACHE_DRIVER` in the prod `.env`? Does a manual sweep exceed 190 s and get re-delivered or failed by Horizon?
5. **Does Graph's default edge omit ARCHIVED/DELETED objects?** If so, their `meta_ad_settings` status is frozen.
6. **Canonical CPL.** Should it be the report CPL or the allocated one? `CplInfoButton` and the stale footnotes must follow that decision.
7. **Should staff, test and `is_staff` leads be excluded** from Our leads, both CPLs and the rosters?
8. **Promotion-window behaviour.** Should the window editor save `promo_ends_at` as end-of-day (the off-by-one), and stop the Ads-tab editor wiping `promo_budget`? Should cancelled siblings stop being boundaries? Should 12:xx handovers stop double-claiming the day?
9. **Roster visibility.** Is it intended that `view-leads-own` / `-team` users see and export the full roster?
10. **Messages band labels.** Should AFTER_EVENT rules read "after", and should inactive rules get columns?
11. **Status endpoint.** Should it enforce the "past only" rule for Zoom sessions server-side?
12. **Landing behaviour:**
    - Should a submit for a just-started session fall through to the next one?
    - Should `?preview` require an admin?
    - Should members-only sessions be skipped by the auto-pick?
    - Should a Zoom CANCELLED webinar count as cancelled?
13. **`_fbp` / `_fbc` fix** (add both to `EncryptCookies::$except`). This changes every CAPI event, so it needs an owner decision plus a check of current match quality in Events Manager.
14. **Re-registration and the wrong-number flow.** Should they place a second AI call and override a WhatsApp STOP? Should `adoptPortalPhone` refuse staff accounts?
15. **Funnel 4 AI-call rule after the upgrade.** It is copied to slots 5 and 10, but not to merged HK slot 16. Is that set intended? Also not checked: whether slot 16's events now carry `event_funnel_id = 4` on dev (which would put them on the dev Sessions tab).
16. **Purchase money.** Run the two `purchase_histories` SQLs in Q6 (payable, status, provider and currency split; repeat payers) to size the refund, TnG and multi-row effects on revenue.
17. **Partial refunds.** Should they be modelled? The webhook keeps the full amount; an import drops the whole row.
18. **Session 31's webinar state** right before the event: `SELECT id, status, started_at, ended_at FROM zoom_webinars WHERE event_id = 31 AND deleted_at IS NULL ORDER BY id DESC LIMIT 1`. Watch for a stuck-LIVE webinar after 14 Oct.
19. **Phone formats.** Are any `user_profiles.phone` values stored in local `0…` format on production? They would be bucketed as US.
20. **Dead scaffolds.** Do any live slots use the slugs `grade-a`, `ai-prompt-class-for-investment-testing-slot` or `physical-eventssss`? Their pages capture nobody.
21. **Legacy fan-out rows.** How many funnel-4 landing rows on older sessions came from the prod funnel-wide fan-out? Those rows inflate "landing" counts and the CPL divisor there.