# Lead Journey — implementation plan

**Spec:** `storage/app/workflow/PropertyLab Flow.md` (+ `.drawio.svg`), the "AI买房训练营 by Wai Kit" lead flow ·
**Written:** 2026-10-03 · **Status:** PLAN — nothing below is built unless marked ✅ ·
**Objective (the boss's words):** every sales admin / agent, on login, knows exactly what to do today; the boss can
track where every lead is and who did what.

---

## Build log

- **2026-10-03 — approved by the owner ("ok I think can proceed"); building started.**
- **Phase 0 code items DONE (uncommitted):** "Add lead" self-assign for own/team-scope creators
  (`LeadsController@store`, regression test in `LeadStoreIdentityTest`); the Leads performance panel redacts
  customer names outside the viewer's scope (`ChannelLeaderboard::forWindow(…, $viewer)`, test in
  `LeadPerformancePanelTest`). Still the owner's: roles on Setting → Roles, `event_series_offers`, copy.
- **Phase 1A Lead reps DONE (uncommitted):** migration `2026_10_03_100001_create_lead_reps_table`, `LeadRep`,
  `LeadRepRepository` (+ facade), `Lead::reps()` + delete cascade, both account-manager writers mirror into
  reps, `LeadVisibility` + `AgentLeadAssignments` rep arm, `IdentityChildMap` entries + merge dedupe,
  `leads:rollup-reps` (every 15 min; `--all` backfill), `RepsController` (+ `Reps\StoreRequest`, routes
  `manage.leads.reps.store|destroy`), Show header Reps line + `LeadRepsModal`, LeadDetailModal Reps line,
  Summary Relationship card → Reps list, Leads list `rep` filter ("Mine" / colleague). Tests:
  `tests/Feature/Lead/LeadRepsTest.php` (4). Handbook: leads `readMe.md` + roles `readMe.md`.
  Auto-reps wired: task assignees (at once, kind 2), Client Success holders (at once, kind 5 — they now SEE
  the lead, a change to the 2026-09-19 rule), Zoom closer (at once, kind 3), a deal's `closer`-role holders
  (next rollup). `LeadRep::KIND_RANK` keeps the stronger reason.
  NOT built from §9: the Leads list's Rep COLUMN still reads the derived `LeadTopRep`; Employee Performance
  "Time with leads" (Phase 5).
- **Zoom ACTUAL duration DONE (owner, 2026-10-03: "if it is past it should always show the 实际时长 in every
  part of this system"):** migration `2026_10_03_110001` (`actual_seconds` / `ended_at` / `actual_source` /
  `actual_checked_at`, backfilled from synced rows), `meeting.ended` webhook stores Zoom's start→end, the
  recordings sync stores the recording's length (never over Zoom's), `zoom:sync-actual-durations` (every
  30 min; `--all` backfill) asks Zoom per past meeting and marks unrecorded ghosts `not_held` (excluded from
  `applyHappened`). One definition — `ZoomMeeting::SECONDS_SQL` / `spokenSeconds()` / `displayMinutes()` —
  wired into ~25 readers (list in the Zoom handbook). Tests: `tests/Feature/Zoom/ZoomActualDurationTest.php` (4).
  ⚠️ Deploy owes `php artisan migrate`, then `php artisan leads:rollup-reps --all` and
  `php artisan zoom:sync-actual-durations --all --limit=1000` (`--all` alone still stops at `--limit`, default 300; production had 498 meetings on 2026-10-06) once each.
- **Phase 1B My Work DONE (uncommitted, not browser-checked):** `GET /manage/my-work` (`MyWorkController` →
  `Src\Lead\Services\MyWorkBoard` → `Pages/Manage/MyWork/Index.vue`): Do now (open action items assigned to the
  person, grouped Call · WhatsApp · Zoom/appointment · Other, overdue first, with phone / click-to-call / WhatsApp
  thread / last AI-call summary / Done), Today (appointments + 1-1 Zooms), Waiting on a reply (`ReplyOwed` over
  the person's rep leads), My leads (`lead_reps`, link to `/manage/leads?rep=me`), This week vs last week
  (`SalesEngagementReport` for one person). Boss view = `?person={uuid}` for `view-leads-all`. First entry of
  the Operations nav and first landing candidate. Handbook: `docs/modules_handbook/manage/my-work/readMe.md`.
  Tests: `tests/Feature/Manage/MyWorkTest.php` (2, fetched as Inertia XHR so they do not need the Vite dev
  server). NOT in it yet: the journey box per lead (Phase 2), the outcome form (Phase 3), sign-in landing
  straight on it (still the Hub → Operations tile → My Work).
- **Phase 2 Funnel Journey DONE (2026-10-04, uncommitted, not browser-checked).** ⚠️ Naming changed from the
  plan: `lead_journeys` / `JourneyHandoff` / `journey:advance` all COLLIDE with things that exist
  (`lead_journey_updates` + `Src\Lead\Services\CustomerJourney`, `Src\RevenueJourney\JourneyHandoff` /
  `JourneyEvent`, the `journey:*` commands), so the tracker is the **Funnel Journey**: tables `funnel_journeys` +
  `funnel_journey_events`, namespace `Src\Lead\Journey\`, config `config/funnel_journey.php`, command
  `funnel-journey:advance` (every 5 min), columns `lead_action_items.funnel_journey_id` + `handoff_kind`.
  Handbook: `docs/modules_handbook/manage/leads/funnel-journey/readMe.md` (boxes, hooks, rules, deploy list).
  - **A funnel must be switched ON** — new column `event_funnels.journey_kind` (blank = not tracked · 1 Preview
    webinar · 2 Project webinar), the **Sales flow** choice on the funnel form. Not in the original plan; needed
    because nothing else tells the two webinar funnels apart ("Paid?" = membership vs project fee, decision #17)
    and because funnels 7 / 8 / 10 must be left alone (owner: "ignore first"). `stage` is per FUNNEL
    (1 before the webinar · 2 after · 3 closed); the flowchart's stage number is `FunnelJourney::flowStage()`.
  - **Hooks (one line each, fail-soft, idempotent per ref)** in `RegisterLeadAction`, `SendFunnelWhatsAppMessage`,
    `SendFunnelAiCall`, `AiCallAftermath`, `SendAiCallFollowUp`, `AiCallbackController`, the WhatsApp "call me"
    button, `ReconcileWebinarAttendance`, `EventRegistrationRepository`, `PurchaseFulfiller`,
    `EngagementRepository::changeStatus`, `LeadActionItemRepository` — all through `FunnelJourneyHooks`.
  - **Rules:** `HandOffAfterAiCall`, `HandOffWhenNotClicked`, `HandOffWhenAiNeverReached` (added: a landing
    registrant no AI call ever reached), `SettleAttendanceAfterWebinar` (uses `SessionDueWindow::endedAt()`, so a
    live Zoom webinar is never called over), `UnpaidAfterWebinar`. A journey SLEEPS until the earliest moment a
    rule names (`wakeAt()`), so the scanner never re-reads idle rows.
  - **Hand-off** = `FunnelJourneyHandoff::toHuman()`: account manager → the registration's caller → the funnel's
    caller queue → nobody (task written UNASSIGNED, journey reads "nobody assigned"; never a guess). The picked
    person becomes the account manager when there is none (`LeadAssignment::REASON_FUNNEL_HANDOFF`). A hand-off
    task has no author, so anybody working the lead may edit / reassign it (`LeadActionItem::canEditFor()`).
  - **Surfaces:** Leads list **Journey** column, lead **Sales → Journey** tab (page + modal), **Sales flow** tag on
    My Work tasks and on the action item, "Sales flow" chip on the funnel header.
  - **Tests:** `tests/Feature/Lead/FunnelJourneyTest.php` (9, 79 assertions) + the census
    (`IdentitySchemaCoverageTest`) and ~35 neighbouring test files re-run green.
  - **NOT in Phase 2 (deliberately):** the caller queue on webinar funnels (Phase 3 — until then a webinar-funnel
    lead with no account manager is handed over unassigned; only 329 of ~12,900 leads have one), the outcome form
    (Phase 3), everything after `paid` / `unpaid` incl. the closer's hand-off (Phase 4), the boss board and a
    Journey filter on the list (Phase 5), any backfill of past registrations.
  - **Owner to-do after deploy:** `php artisan migrate`; set **Sales flow** on the Preview funnel (4) and the
    Project funnel (5); make sure the AI call profile extracts `will_attend` + `buy_intent` (else every answered
    call is "not useful" and goes to a colleague); `php artisan funnel-journey:advance --dry-run` once.
- **Phase 3 DONE (2026-10-04, uncommitted, not browser-checked).** All seven items, on top of Phase 2:
  1. **Round robin on sales-flow funnels** — the VSL caller queue (`funnel_caller_rotations` `KIND_LEAD`) now also
     serves a webinar funnel whose Sales flow is on. It takes turns on every landing registration and names the
     lead's ACCOUNT MANAGER when it has none (decision #13: `FunnelJourneyHandoff::ownerAtRegistration()`,
     `LeadAssignment::REASON_FUNNEL_ROTATION`); an existing manager is kept at no cost to the queue. Set on the
     funnel page's **Callers** box (the VSL modal, `variant="journey"`, one queue). The paid-customer queue
     (`KIND_BOOKING`) is deliberately not offered there yet — Phase 4 reads it. The journey's owner follows the
     account manager (`accountManagerChanged`).
  2. **Per-funnel wait** — `event_funnels.handoff_hours` (blank = 6), on the funnel form.
  3. **Outcome form** — `lead_action_item_outcomes` + `HandoffOutcome` + `HandoffOutcomeModal`: Spoke to them /
     No answer (task stays open, moved to tomorrow, `human_attempt` logged) / Cannot be reached. The questions are
     the AI call profile's extraction fields (`HandoffQuestions`, limited by `funnel_journey.outcome_fields`), so
     DATA 1 and DATA 2 share field names. A closing result posts "📞 电话回报" into the Discussion feed; an agreed
     time becomes a follow-up task. Opened from My Work (**Log the call**) and from the lead's Action items.
  4. **Join next time** — `event_registrations.reminders_muted_at`; both scanners skip a muted registration for
     every rule of that session; **Reminders off** chip on the roster (click to un-mute).
  5. **Recurring group post** — a GROUP rule may name a SLOT instead of one session ("Post for → Every session of
     a slot"); the scanner already claimed per rule × session, so only validation, `mapInput` and the form changed.
  6. **R2 screenshot** — built as a staff alert, not a task (an action item needs a lead): `SessionNudges` sends
     Notify `events.webinar_screenshot` an hour into a tracked session that is really live, once per session.
  7. **M1 button** — built as a generic `button_reply` on a Cloud funnel rule rather than through the
     template-menu flow (a funnel welcome is not sent through the flow engine, so no flow run is parked to match
     the tap). The tap is recognised by the message it quotes; replied once per send. ⚠️ The CONTENT is still the
     owner's: write the reply text on the welcome rule once the template with the button is approved by Meta.
  - Also: **My Work → Sales flow block** (the person's leads by who holds the ball, incl. "AI handled — no call
    needed", decision #10).
  - Also (not in the plan, found while building): **a call task the webinar overtakes closes itself** — rule
    `ExpireCallAtWebinarStart` → `FunnelJourneyHandoff::expire()`: system outcome `RESULT_EXPIRED` ("Not called in
    time"), task done by nobody, journey box `not_called`. Otherwise a "call before the webinar" task sat in My
    Work the morning after, and "handed over, nobody called" was not countable.
  - **Migrations** `2026_10_04_100004` … `100007`. **Tests:** `FunnelJourneyTest` (15, 123 assertions),
    `FunnelButtonReplyTest`, one case each added to `FunnelGroupPostTest` and `FunnelAutomationReminderTest`;
    WhatsApp folder (312), Manage/Events (42), Lead folder, census, front-end 268 — green. Failures seen and NOT
    from this work: page-render tests needing the Vite dev server (`LeadDashboardTest`, `LeadAttentionTrendTest`,
    `AnalysisGuideTest`), `DraftLiveQaAnswerTest` (12), `FunnelAutomationTest::test_email_send_skips_a_placeholder_address`.
  - **Owner to-do after deploy:** migrate; on funnels 4 and 5 set **Callers** first, then **Sales flow**; write the
    welcome rule's button reply; subscribe the webinar host to "time to post a webinar screenshot".
- **Review + fixes (2026-10-04 evening, uncommitted).** A whole-suite run diffed against a clean HEAD worktree
  (`git worktree` + `petav3_head_testing`) and three read-only review agents (sales-flow core, integration +
  authorization, Vue/payload contracts). Fixed:
  - **Regressions from Phase 1A:** a Customer Journey hand-off made its assignee a rep (= granted the lead the
    hand-off requires) → `mirrorJourneyCommitment()` and Customer Journey's `create()` calls mirror nobody; a
    FORMER account manager stayed an active rep, so a reassigned lead stayed in the old agent's list
    (`AgentLeadSearchTest`) → retired unless still tied (open task / closer / Client Success role), by person
    (`syncAccountManager($lead, $previous)`), with a backfill in `leads:rollup-reps` for managers from before reps.
    Two sqlite fixtures (`EmailChannelTest`, `EmailJourneySourceTest`) needed the `lead_reps` table.
  - **Access:** task assignees limited to the actor's group (a task grants the lead); re-saving a task revives
    nobody; Retire refuses a still-tied rep; the button reply's `{{login_link}}` is bound to the tapping number
    (it was unbound — a sign-in hole on email-verified accounts).
  - **Sales flow:** hooks run after the caller's commit; a hand-off task closes itself ("No longer needed") when
    the journey moves on; 20-minute automation grace inside the cutoff; old-session verdicts logged only;
    cancelled / rescheduled / deleted sessions; "not paid" from the webinar's end; a deal closes a journey only
    with evidence; scanner re-checks under lock; outcome form race-safe; opted-out invitation per funnel;
    `(ref_type, ref_id)` index. Button reply: first button only, no typed match while a bot runs, claim released
    on failure, ledger index. Front end: 3 MEDIUM + 8 LOW contract / UX fixes.
  - **Pre-existing on master, fixed in passing:** a one-session group post timed "after it ends" crashed the
    WhatsApp reminder scan on every tick (`RunFunnelReminders`).
  - **Owner's answers (2026-10-05):** (1) "all admins can read all leads data" — option A, WITH the Sales
    Dashboard's company-wide numbers: migration `2026_10_05_100001_grant_view_all_leads_to_sales_roles` opens the
    existing `sales-agent` / `sales-leader` roles (agency defaults in `SeedCommonRolesAction` unchanged); the
    retire-on-reassignment rule stays, now only keeping "my leads" lists right. (2) The owner will set each
    Property Closing slot's offer (Automation tab → slot → ③ → Add offer → Project fee). (3) 20-minute grace: yes.
  - **Phase 4 BUILT (2026-10-05, uncommitted, not browser-checked)** — all seven items; handbooks: Funnel Journey
    §3c–3e, Funnel Automation (*After the webinar — who a rule is FOR*, *missed_template*, *Pacing*), Funnel
    WhatsApp, Funnels, Payment Automation, Voice Agent, My Work. Migrations `2026_10_05_100003` … `100005`.
    1. **Rule conditions** — `attendance_condition` / `payment_condition` on both rule tables ("after the session
       ends" only; paid needs the Sales flow) + `cohort_condition` on AI-call rules (attended the Preview, also
       on the welcome call). One judge, `Src\Event\Support\FunnelRuleAudience`: MATCH / SKIP (claimed
       `condition_not_met`, now on `FunnelAutomationSend` too) / HOLD (a Zoom session's attendance not settled
       yet). "Paid?" re-asked in the WhatsApp and AI-call send jobs. UI: chip rows in `ScheduleFields.vue`,
       selects in the WhatsApp modal, cohort chips in the AI-call modal, chips on the rule card.
    2. **`missed_template`** on AI-call rules → `meta.missed_template` on the call → `SendAiCallFollowUp` sends
       it once approved, nothing before (never the pre-webinar M3). The four templates' COPY is still the
       owner's (Messages → Templates → Meta review).
    3. **Paid path** — rule `AssignRepWhenPaid` (next tick, after the deal exists) → `FunnelJourneyHandoff::
       toRep()`: deal's Zoom closer → the funnel's paid-customer queue (`KIND_BOOKING`, now the Callers box's
       second tab on sales-flow funnels) → account manager → nobody; sets `zoom_closer_id` (not the commission
       role); task "Book the 1-1 sales Zoom" / "member's 1-1 Zoom" (`handoff_kind = zoom`, HIGH). A Zoom booked
       for the lead → `zoom_pending` + task done by the booker; held → `zoom_done` (`ZoomMeetingRepository`
       hooks). Second payments, account-manager changes don't move a REP's journey; a closer changed by hand
       takes the task. **"Payment received" gap:** a link-less purchase (portal, manual entry) borrows the ON_PAID
       rules of the ONE active link selling the same payable (`DispatchPaymentAutomationAction::linkFor()`).
    4. **After-webinar loop** — an AI call from an "after the session ends" rule restarts the automation from
       `attended`/`no_show`/`unpaid`/`followed_up` (`ONLY_FROM_AFTER_WEBINAR`); hand-off without the webinar
       cutoff; useful = `useful_fields_after` (`buy_intent`); a useful answer → new box `followed_up`;
       `ExpireCallAtWebinarStart` and `SettleAttendanceAfterWebinar` are before-the-webinar only.
    5. **From Preview** — `event_funnels.candidate_source_funnel_id` (funnel form), `PreviewCandidates` (computed,
       never stored), `PreviewCandidatesController` (GET list / POST register; manage-events + manage-leads),
       `EventRegistration::SOURCE_FROM_PREVIEW` (6, "From Preview" — the plan's `SOURCE_JOURNEY`, renamed for
       what it says), welcome sent, Project journey opened (`preview_candidate`: no "AI never reached"
       hand-off), `candidate_marked` on the Preview journey; My Work "Review the Preview's people" card (stateless:
       a session drops off once anyone is registered from the list). The review TASK of the plan became this card
       — an action item needs a lead.
    6. **Lost reason codes** — done earlier the same day (see above).
    7. **Pacer** — `RETELL_CALLS_PER_MINUTE` (10), `RateLimited('ai-calls')` on `SendFunnelAiCall` (`retryUntil` a
       day instead of tries; quiet-hours re-dispatch keeps its lane); `ConversationalCaller::lastRefusal()` →
       `concurrency_limit` (a refusal reason) → one retry ten minutes later, then recorded (the journey then hands
       the person on).
    - **Fixed in passing:** `RuleRow.vue` printed the VSL video triggers under the wrong numbers (5/6 → 6/7); the
      session roster's registered-date icon (`CalendarDays`) was never imported; a provider-refused AI call now
      fills `refusal_reason` like every other refusal (so `applyDialledByAi()` no longer counts it as dialled).
    - **Tests (2026-10-05 night, `petav3_audit_testing`):** new — FunnelJourneyTest +3, PreviewCandidatesTest,
      FunnelAutomationReminderTest +3, FunnelAiCallAutomationTest +1, CantoneseFollowUpTemplateTest +2,
      PaymentAutomationTest +1, all green. Affected folders: Event + Manage/Events + Unit/Event 450 (1 known
      baseline), Lead + Leads 411 (6 Vite page renders), Payment + Engagement(s) 512 (0), VoiceAgent + Zoom 629
      (12 = the known `DraftLiveQaAnswerTest`), Whatsapp 312 (0), MyWork + Ceo 48 (23 = Vite page renders + the known
      CEO chat 403s). Guards `check-suite-links` and `check-migration-constants` OK. vitest: 5 files red, none
      touched by this work (Zoom Evaluation, AI Prompts preview, Property Match admin, portal-guide fingerprint,
      useSalesCoachChat).
    - **Owner to-do after deploy:** migrate; funnel 5 → Edit → "Candidates come from" = funnel 4; Callers → "付了钱的人"
      (optional); author + submit M4 / Payment received / Why didn't you attend / Follow-up (unpaid); on funnel 4
      and 5 slots add the after-ended rules (no-show WhatsApp; AI call limited to the Preview's attendees with M4
      as its missed-call message; unpaid follow-up) — then raise `RETELL_DAILY_BUDGET_USD` above the cohort's
      worst case.
  - **Decisions I took (owner to confirm):** reassigning a lead ends the old manager's access unless still tied;
    a Booked/Lost deal closes a Project journey only when its payment was recorded there (or the slot lists the
    project); 20 minutes of grace. **Left as known limits** (handbook): a registration's first caller is final;
    quiet hours do not pause the clock; verdicts processed inline; a merge keeps the winner's box.
- **Phase 5 BUILT (2026-10-05, uncommitted, not browser-checked)** — all three items + the deferred "Time with
  leads"; handbooks: Funnel Journey §6c, Funnels (Journey tab), Reports (*The sales flow board*), Pay Attention,
  Leads, Employee Performance, CEO Dashboard. No migration.
  1. **Funnel hub → Journey tab** (`JourneyBoardTab.vue`, `Src\Lead\Journey\JourneyBoard`, prop `journeyBoard` =
     `Inertia::optional`, partial reload; filters `jsession` / `jfrom` / `jto` / `jowner`; shown with a Sales flow +
     a lead level). **Two groups, on purpose:** the FLOW (boxes, milestones registered → attended → paid → REP →
     Zoom held → booked, median time per box from the log, lost reasons) counts a session's registrants or the
     journeys opened / re-registered in the range (default 30 days); the WORK (waiting for a colleague, nobody
     assigned, overdue tasks, per colleague: owned / waiting / open / overdue / done, calls + Zooms by the
     `ChannelLeaderboard` rules, booked) counts every running journey whenever it opened + those closed in the
     range. The first cut had only the flow group, which hid the oldest late task behind a date range — caught
     in self-review, pinned by a regression test.
  2. **Report** — named `SalesFlowWeeklyReport` / `sales-flow-weekly`, "Sales flow board" (the plan's
     `LeadJourneyReport` / `journey-weekly` renamed: "lead journey" already names other things here). Sunday 11pm,
     OFF until the owner enables it. Every funnel with a Sales flow, last 7 days, through the board; per colleague
     read once over all funnels (a call is counted once); overdue list (25); deals lost THIS week; AI summary
     (`ceo_sales_flow_report`, Flash). It does not replace the property-closing Sunday board — both exist.
  3. **Leads list** — filters `journey_stage` (1 / 2 / 3 = closed) · `journey_step` · `journey_owner` (`me`,
     a uuid, `none`); only funnels whose Sales flow is on; counts per option. Pay-attention flag
     `journey_overdue` ("Sales flow task overdue", We owe them): an open sales-flow task more than ONE day past
     its day — stricter than the board's "past its day", on purpose.
  4. **Time with leads** (deferred from Phase 1A) — CEO → Employee Performance → **Time with Leads**
     (`TimeWithLeadsReport`, `TimeWithLeadsController`, route `manage.ceo.employee-performance.time-with-leads.index`,
     `SectionTabs` tab, gate `view-ceo-dashboard`): per colleague over their ACTIVE `lead_reps` rows — people,
     managed, phone / Zoom / F2F minutes, minutes per person, WhatsApp, tasks, appointments, touched 7d / 30d /
     never. All-time cached figures (Sales Engagement is the per-period view); staff leads never count.
  - **Fixed in passing:** the Leads filter bar never sent the *Rep* (handled by) choice — `rep` was missing from
    `LeadFilterBar.vue`'s `SCALAR_KEYS` since Phase 1A (vitest regression added, proven red without the fix).
    On master since 2026-09-24: sorting the Leads list by the Record column as a viewer who may not see it sent
    NO order at all instead of the default one (`LeadSortableColumnsTest` was red) — `applySort()` now falls back
    to `latest()`.
  - **Tests (2026-10-05 night, `petav3_audit_testing`):** new — `JourneyBoardTest` (5: board, old registration
    still waiting, tab partial reload, Sunday report, Leads filters + flag), `TimeWithLeadsTest` (2),
    `LeadFilterBar.test.js` +1; all green. Affected folders: Lead (1 = Vite page render), Ceo 48 (23 = Vite renders
    + the known CEO chat 403s; 1 deadlock from my own parallel run, green on rerun), Report 6 (1 Vite), Manage/Leads
    194 (4 Vite + the sort test above, now green), Leads 22 (5 Vite), Event 367 (1 = the known placeholder-email
    baseline), Manage/Events 43 (0), PromptSkeleton 22 (0). vitest Leads Index + Partials 31 files / 190 green.
    Guards `check-suite-links` (67 = baseline) and `check-migration-constants` OK; Pint clean on the new PHP files;
    the six touched `.vue` files compile with `@vue/compiler-sfc`.
  - **Owner to-do after deploy:** CEO → Reports → *Sales flow board* → switch on + recipients; nothing else
    (no migration, no env).
- **Phase 6 BUILT (2026-10-05, uncommitted, not browser-checked)** — DATA 1–5; handbooks: Funnel Journey §4c,
  Funnels (Call questions box), Readiness verdict (records layer), Leads. Migrations `2026_10_05_100006` (+ the
  question sets) and `100007` (+ the answers).
  1. **Question sets** — `funnel_question_sets`, one per (funnel, moment: before the webinar · after it · paid =
     the REP's call), written on the funnel page's **Call questions** box (`CallQuestionsModal`,
     `FunnelQuestionsController`). The plan's `journey_question_sets` "per step kind" became per MOMENT: the
     three calls a person makes. Empty = the AI call's questions (unchanged behaviour). Each question: wording,
     type (text · pick one · yes/no), optional readiness area; a stable `key` survives rewording.
  2. **Answers** — `funnel_journey_answers`, one row per question answered, under its DATA point (one rule,
     `FunnelJourneyAnswer::point()`; Stage 3's 3/4 stored `data_3b` / `data_4b` per decision #11). DATA 1 / 3
     = everything the AI call learnt (not only the two "useful" fields; judgements and "unknown" skipped);
     DATA 2 / 4 = the outcome form; DATA 3+4 / 5 = the REP's outcome form on the "book the Zoom" task (the plan's
     "REP's Zoom outcome form" — the same form, asking the paid set). Not `lead_journey_events.data` as planned:
     a row per answer can be read by the readiness layer and later reports with plain indexed queries.
  3. **Readiness** — `ReadinessColumns::answered()`: an answer to a question about an area turns a grey area
     AMBER (never green — the 2026-09-19 founder rule for anything said), beside the channel readings' quotes. A
     "No" and the AI's unknown / none / undecided / not looking / not suitable colour nothing.
  4. **Summary (客户档案)** — fed through the Discussion feed it already reads (the AI call's "🤖 AI 电话回报" and
     the outcome form's "📞 电话回报", which now prints each answer beside its wording and the DATA point). No
     prompt change, so no stored Summary went stale. The lead's Journey tab shows "What they told us" per call.
  - **Fixed on the way:** the outcome form's Discussion note printed raw field names (`buy_intent: investment`),
    which an owner-written question's key would have made meaningless; a colleague's call that was not asked
    `will_attend` / `buy_intent` was logged as "attendance or buying intent still unknown" (now only a real
    "no"); an after-webinar call's "useful" now uses the after-webinar list like the AI's.
  - **Tests (2026-10-05, `petav3_audit_testing`):** `FunnelJourneyTest` +2 (the owner's questions end to end; an
    AI call's DATA 1 + the REP's paid set) and one assertion updated for the new note wording — 26 / 26 green.
    Lanes: Lead 396 (1 = Vite page render), People 95 incl. the merge census (0), Unit/Lead 48 (0), Manage/Leads
    194 (4 Vite), Leads 22 (5 Vite), VoiceAgent 86 (0), PaymentAiCall 12 (0), Event 367 (1 = the known
    placeholder-email baseline), Manage/Events 43 (0). vitest Leads Partials + Components/Leads + Events: 35 files
    / 230 green. Guards OK; Pint clean on the new classes; the four touched `.vue` files compile.
  - **After Phase 6, same day (owner's asks):** (a) ONE source of REP — the Leads list's Rep column, its sort and
    the `top_rep` filter read `lead_reps`, most engaged first (`LeadRep::byEngagement()`); the old recording-based
    "top rep" is gone. (b) The ACCOUNT MANAGER follows whoever talks to the lead most (`TopRepOwnership`, run
    by `leads:rollup-reps`; spoken time only; leads with no manager left alone; not a redistribution).
    ~~Open question: the pool includes "Support" / "App Review Demo".~~ **Answered by (c).**
  - **(c) The COMPANY ROUND ROBIN (owner, 2026-10-05):** one list the boss edits freely on Setting → Lead
    Distribution → Round Robin (order + repeats = weighting). Owner's answers: one list for the whole company;
    every new lead with no account manager, any source, takes the next turn; no second turn after payment (the
    account manager is the REP); the talks-most switch only moves a lead to somebody ON the list. Built:
    `lead_rotations` + `lead_rotation_members` (migration `2026_10_05_100008`), `LeadRotation`,
    `LeadRotationRepository` (`save`, `assignManager`), shared `RoundRobinTurn` (the VSL queues use it too),
    `AssignRoundRobinManagerJob` from `Lead::booted()` (after commit + 60 s), `REASON_ROUND_ROBIN` (11),
    `RoundRobinController` + page + strip tab, `TopRepOwnership` pool = the list. Removed: the per-funnel
    sales-flow caller queue (Callers box, `journey` modal variant, `assignRep()`); `saveCallerRotation` is
    VSL-only again; `pickRep` = closer → account manager → round robin. Docs: leads readMe *The company round
    robin*, funnel-journey §3b / §3d / §4, funnels readMe.
  - **Owner to-do after deploy:** migrate; `php artisan config:cache`; then, per funnel, write the Call questions
    (optional — the flowchart's "1) 2) 3)" were never defined; until then nothing changes). **Then set up the
    Round Robin list and switch it on** — until then no new lead gets a manager automatically and the
    talks-most switch moves nobody.

---

## 0. One sentence

Keep the automation that already works (WhatsApp, AI calls, reminders — most of Stage 1 exists), add the missing
branching (attended / paid), and put ONE new thing in the middle: a **Lead Journey** record per (lead, funnel) that
says *which box of the flowchart this person is in*, hands every "→ Human Call / Zoom" box to a named salesperson
as a task, and is what the agent's home page and the boss's board both read.

```
  automation (exists)            journey tracker (NEW)             people (exists, re-used)
  ───────────────────            ──────────────────────            ────────────────────────
  funnel rules, AI calls,   ──►  lead_journeys: stage/step/   ──►  lead_action_items (the task),
  reminders, payment hooks       owner/next_check_at + event log   round robin → account manager (= first
                                                                   lead rep) / zoom closer → LeadVisibility
                                                                   lead_reps: who handles the lead + time each
                                          │
                                          ▼
                              My Work (agent home)  ·  Journey board (boss)  ·  Reports (Sunday/Friday)
```

---

## 1. What exists vs what is missing (per flowchart box)

| Flow box | Today | Gap |
|---|---|---|
| Landing registration, "OK for AI call" tick | ✅ `RegisterLeadAction`, `lead_funnels.ai_call_opt_in` | — |
| M1 welcome WhatsApp | ✅ funnel welcome rule (Cloud template) | the **"Yes, 我已进群了" quick-reply button** and what it unlocks (the "bonus") — undefined |
| M2 "let AI call me" 2 min later (unticked) | ✅ `SendAiCallFollowUp::KIND_OPTED_OUT` (`ai_caller_optout_v1`) | — |
| AI call after registering | ✅ AI-call welcome rule, delay in seconds | the 3 questions + "generate an appointment" are NOT defined in the profile; a funnel AI call never creates an appointment |
| Picked up → auto record (DATA 1) | ✅ `AiCallAftermath::postLeadComment` → Discussion | structured DATA 1 (the 3 answers) is free text today |
| Not picked up → M3 missed-call + button | ✅ `ai_caller_missed_v2`, 1/lead/day, `/ai-callback/{token}` (7 days) | — |
| Clicked → AI call again | ✅ | — |
| **Clicked? No → Human Call / Zoom** | ❌ | no timeout, no hand-off, no task, no round robin on webinar funnels (`FunnelCallerRotation` is VSL-only) |
| Human Call / Zoom (DATA 2) | partial — calls are recorded + AI-analysed (`call_recordings`), Zoom meetings exist | no task queue, no outcome form, no "will join next time" |
| R1 reminders (24h PM · 5h group · 3h PM · 30m SMS) | ✅ before-event rules, SMS medium, group post | **group post is per SESSION** (must be re-created every week); "join next time → mute" ❌ |
| R2 15-min AI call to non-joiners | ✅ no-show nudge (AI-call medium, 2026-10-01) | — |
| R2 1-hour group screenshot | partial (a group post can carry an image) | a screenshot is a human act — needs a prompt to the host |
| Attended? (after the webinar) | ✅ `ReconcileWebinarAttendance` ~5 min after `webinar.ended` | after-ended rules cannot branch on it (`no_show_only` is for DURING the webinar only) |
| Paid? | ✅ purchases attributed to the session (`PurchaseSessionAttributor`), `PaidPipelines` | no rule condition; "paid" = the slot's offer (§7 #1) but `event_series_offers` is EMPTY in production (§1a) |
| Payment received WhatsApp | ✅ payment-item ON_PAID rule | only for purchases through a payment link (known gap) |
| Auto-assign REP → REP calls → Human Zoom | partial — `engagements.zoom_closer_id`, "Schedule Sales Zoom", Property Closing page | assignment is MANUAL today; no task |
| Unpaid: follow-up → AI call → M4 → human | ❌ (all pieces exist, no conditions, no M4 template) | conditions + M4 + hand-off |
| No-show: "why didn't you attend" → AI call | ❌ same | conditions + copy |
| Project Webinar reminders | ✅ rules | how the person gets REGISTERED on the Project Webinar session: today a CSV round-trip; becomes the reviewed candidate list (Phase 4 item 5) |
| Closing → Won / Not closed + reason | ✅ engagement Booked / Lost with free-text `lost_reason` | structured reasons (Not ready / No loan…) |
| DATA 3 / 4 / 5 | partial (Discussion comments, Zoom action plans) | no defined questions, no structured store |

Two owner decisions already taken (2026-10-02): the checkbox governs the WELCOME call only; a re-registration
re-sends the welcome (incl. the AI call).

### 1a. Production as of 2026-10-03 (read-only, `production_read`)

**The four funnels the owner wants, and what they are in the flow:**

| Funnel (id) | Role in the flow | Slots today | How people get in today |
|---|---|---|---|
| 4 · 1. Trust Nurturing – Property Investment | **Stage 1 — the Preview webinar** | 5 `AI买房训练营` (next 14 Oct · 28 Oct), 10 `AI Prompt Class` | landing page (ads) + Zoom's own form — e.g. 30 Sep: 146 landing + 37 Zoom, 183 registered / 73 attended |
| 5 · 2. Property Closing | **Stage 2 → 3 — the Project webinar** | one slot per project: 17 `ViiA residence`, 18 `Peel Lane`, 19 `Johor Shoplot` (8 Oct), 15 `Bangsar South`, 11 `Binastra Cochrane` | **bulk CSV import** (648 of 686 on 1 Oct, 738 of 768 on 29 Sep) + Zoom's form; **no landing registrations at all**. 1 Oct: 686 registered / 82 attended / 604 no-show |
| 6 · 3. After Sales Service – Reno & Tenant | bonus (outside the journey) | 9 `Renovation` (inactive) | — |
| 9 · 4. Property Knowledge Sharing | bonus (outside the journey) | 13 `Landed` | Zoom form |

Also live and NOT in the four: 7 `Cochrane 新盘避雷指南` (VSL, its own ladder + caller rotation, 344 leads), 8 `Cochrane Webinar`,
10 `HK 數據講座` (session 6 Oct, 11 registered). Decision owed: keep running outside the journey, pause after their
sessions, or fold Cochrane Webinar into Property Closing as a slot.

**What each webinar actually sells (`purchase_histories.event_id`, stamped by `PurchaseSessionAttributor`):**

| Webinar | Sold | So "Paid?" at that stage means |
|---|---|---|
| Preview (`AI买房训练营` 16 Sep: 6 sales, RM 8,261) | **memberships** — Elite RM 2,388 · AI Active Blueprint RM 299 · Implementation Day RM 499 (+ the odd ViiA) | **bought a membership** → the member's 1-1 Zoom (`MemberEntitlements`, the Pay-attention flag "No 1-1 Zoom yet" — 353 owed today) |
| Project (`ViiA` 29 Sep / `Q4 Update` 27 Sep / `Bangsar South`) | **the project fee** — ViiA RM 299 (link 7), Binastra Cochrane RM 100 (link 2), "Plus Membership CLIENT BONUS TV" RM 100 (link 6, project 52) | **paid the slot's project fee** → engagement opens at NEW (exists) → REP → 1-1 sales Zoom → booking fee to the developer → **Booked** |

**`event_series_offers` is EMPTY in production** — nobody has ever told a slot what it sells, so "Paid?" has no
definition the system can read today. Phase 0 fills it in (the Automation tab's step ④ already has the UI).

**What is already configured / running:**
- Funnel 4 slot 5: WhatsApp welcome (`ai_masterclass_welcome_1`, 759 sends), AI-call welcome (profile 2
  `训练营报名欢迎 Call`, 20 s, 466 calls), reminders 1 day + 30 min. Slot 10 has **no** rules.
- Funnel 5 slot 17 (ViiA): WhatsApp 140 min + 50 min, SMS 30 min before, SMS no-show nudge 15 min after start
  (686 sends on 1 Oct), a paused voice rule. **No welcome, no AI call, no after-ended rules.** Slot 15 (Bangsar
  South) has three reminders; slots 18 / 19 none.
- Profile 2's extraction fields already ARE Stage 1's "1) 2) 3)": `will_attend`, `looking_now`, `buy_intent`,
  `ownership`, `occupation`, … Profiles 7 / 8 (`Webinar Feedback Follow Up Call`, ZH + EN) are the paid-customer
  feedback call used by the ViiA / Binastra payment items (manual *Call now*), with `webinar_rating`,
  `project_concerns`, `project_sentiment`, … — i.e. DATA 3+4 / DATA 5 already have a question set.
- Payment items ViiA (7), Binastra (2), Plus Bonus TV (6) carry ON_PAID receipt + after-call consent form + missed-call rules.
- AI calls, last 30 days (lead calls): 132 completed · 135 no answer · 7 busy · 38 voicemail · 28 failed — ~39 % answered.
- **Hand-off surfaces are unused:** `zoom_closer_id` is NULL on all 68 paid pipelines; 6 appointments in 60 days;
  22 open action items; caller rotations exist only on the VSL funnel (208 assigned); **329 of 12,921 leads have
  an account manager** — the own-level visibility trap in §3 is real: switching agents to `own` today hides 97 % of leads.
- Staff: super-admin = Shawn, Leejie, Waikit, Zen, Kexin, Boon, Youchen, yongzhi, Support, Celeste; Dylan = legacy
  `admin`; Wayne = `marketing`. Performance teams: engagement = Kexin · Shawn · Zen · Boon; closer = Waikit + the same four.

---

## 2. Architecture decision — where the journey lives

Three candidates were weighed.

| | A · funnel rules only | **B · funnel rules + Journey tracker (recommended)** | C · Appointment Engine runner |
|---|---|---|---|
| What it is | add attended/paid conditions to the existing time-based rules | A, plus one record per (lead, funnel) holding the person's position, owner and next check | run the flow as an AE workflow (`ae:run-workflows`) |
| Hand-off to a human | nowhere to put it | `lead_action_items` + round robin, visible on My Work | `action.assign_agent` + Telegram accept/pass (proven) |
| "Where is this lead?" | not answerable | one row, one event log, one board | `ae_workflow_runs` + run logs (proven) |
| Fits the data | ✅ registrations, attendance, payments live here | ✅ | ❌ AE has its own lead book (`ae_leads`, per agency), triggers are Sheet / keyword / CTWA / Meta form, its "attended" means an APPOINTMENT, its plan editor is a straight list (branches are fixed in the compiler) |
| Fits the people | ✅ sales works in Operations → Leads | ✅ | ❌ sales would work in a second suite; every webinar registrant (~700/session) becomes an `ae_leads` row + run |
| Effort | small, but leaves the objective unmet | medium | large (new triggers, new conditions, editor changes, migration of the team's habits) |

**Recommendation: B.** The automation stays where the data is; the Journey tracker is deliberately thin (a state
+ a log + a 5-minute scanner for timeouts), and the human side re-uses what exists: `lead_action_items` (assignees,
due date, done/reopen, Telegram alert on assign), `leads.assigned_admin_id` / `engagements.zoom_closer_id` (so the
task's owner can SEE the lead under `LeadVisibility`), `FunnelCallerRotation` (generalised), the calendar.
Borrow from AE where it is better: its `human.record_outcome` nudge pattern and the Telegram accept/pass hand-off.

---

## 3. Moving the sales team off super-admin (prerequisite, Phase 0)

Today every salesperson is `super-admin` (sees everything, bypasses every gate). The plan assumes:

| Person | Role | Lead scope | Why |
|---|---|---|---|
| Boss (Wai Kit) | `super-admin` | all | CEO suite, Reports, everything |
| Sales leader (TBC — Ke Xin?) | `sales-leader` + `view-leads-all` (or `-team` once teams exist) | all / team | sees every lead, can reassign, reads the Journey board |
| Agents (Shawn, Zen, Boon …) | `sales-agent` | **own** | their own leads + any deal they hold a role on |
| Marketing | `marketing` (exists) | none | funnels + traffics only |

What changes for an agent at `view-leads-own` — and what the plan does about it:

- They see a lead ONLY if they are its account manager, hold an engagement role on it or — after Phase 1A — are one
  of its **reps** (§9) → **every hand-off in the journey must make the person one of those** (Stage 1 → account
  manager = the first rep; a Call task's assignee becomes a rep; paid path → `zoom_closer_id` + the `closer`
  engagement role, mirrored as a rep). Otherwise the task says "call Ahmad" and the lead page 403s.
- Known bug to fix first: **"Add lead" does not self-assign** (`LeadsController@store`), so an own-level agent who
  adds a person cannot open them afterwards. Also the **performance panel leak** (`/manage/leads/performance`
  has no `LeadVisibility`) — fix before handing the role out.
- The Hub shows them 3–4 suite tiles (New Project, Subsale, Operations, AI Appointment System). The plan makes
  **My Work** the landing page for sales roles so the Hub is not the first thing they meet.
- Role defaults are only applied to a NEW role or an EMPTY one (`SeedCommonRolesAction`) — on this install the
  roles exist, so the grants are edited on Setting → Roles, then `permission:cache-reset`.
- Run `php artisan db:seed --class='\RolesSeeder'` is NOT the way (it re-grants the legacy admin role); edit on the page.
- **Two steps, not one (decided 2026-10-03 after the production read).** Only 329 of 12,921 leads carry an account
  manager, so `view-leads-own` on day one would blank every agent's list. Step 1 (Phase 0): move the agents off
  `super-admin` onto `sales-agent` **with `view-leads-all`** — they lose settings, roles, deletes and the other
  suites, they keep every lead. Step 2 (after Phase 2 has been assigning owners for a few weeks): tighten to
  `view-leads-team` / `own` once the Journey board shows every active lead has an owner.

---

## 4. Phases

Each phase ships on its own and is useful on its own. Estimates are working days for one developer, excluding
Meta template review time.

### Phase 0 — decisions, roles, two bug fixes (2–3 days)

1. Answer what is still open in §7 (most of it is answered — see the decisions log there).
2. Fix "Add lead" self-assign + the performance-panel scope (both in `funnel-lead-sales-payment-audit` memory).
3. Role matrix above applied on Setting → Roles (step 1 = `sales-agent` + `view-leads-all`); one agent switched
   first, verified for a day, then the rest.
4. **Fill `event_series_offers`** (the Automation tab's step ④ — no code): slot 5 `AI买房训练营` and slot 10 sell the
   memberships (Elite · AI Active Blueprint · Implementation Day, through their payment links 1 / 4 / 5); each
   Property Closing slot sells its project fee (ViiA → link 7, Binastra → link 2, …). This is the "Paid?"
   definition the journey reads; a slot with no offer has no paid path.
5. Question sets: Stage 1's AI questions are profile 2's extraction fields already (`will_attend`, `looking_now`,
   `buy_intent`, `ownership`, `occupation`); the paid-path feedback call is profile 7 / 8. What is still missing is
   the HUMAN call's three questions (§5, `journey_question_sets`) — the owner writes them, the form renders them.
6. Author the four Stage 2/3 templates (M4, payment received for the Preview's memberships, "why didn't you attend",
   unpaid follow-up) and submit them to Meta now, so review runs while Phases 1–3 are built.

### Phase 1 — Lead reps, then "My Work": the agent's home page (9–12 days)

**1A. Lead reps (4–5 days) — owner requirement #16, full design in §9.** Built first because "my leads" on My Work,
the Leads list's *Mine* filter and own-level visibility all read it.

1. Migration `lead_reps` (§5) + model `Src\Lead\LeadRep` + `Lead::reps()`; register `lead_id` / `user_id` in
   `IdentityChildMap` (merge + purge), a dedupe beside `LeadRepository.php:1936`, delete cascade in `Lead::booted()`.
2. `LeadRepRepository` (`addRep`, `removeRep`, `syncAccountManager`) called INSIDE the two account-manager choke
   points — `LeadRepository::assign` (:158) and `LeadDistributionRepository::assign` / `moveToPool` (:33 / :76) —
   and from `mergeLeadRow` (:1700), so the account manager is always a rep without touching the seven callers.
3. `LeadVisibility::apply()` + `allows()` + `AgentLeadAssignments` gain the rep arm (§9).
4. `reps:rollup` (every 15 min; `--all` backfills once): recomputes the cached time columns from the sources
   `staffPerLead()` already reads and AUTO-ADDS a rep on the first recorded interaction.
5. UI: Reps line in the identity header (Show, LeadDetailModal); the Reps card replacing the single derived "Rep"
   on Intelligence → Summary; `LeadRepsModal` (multi-select); Leads list *Mine* filter + Reps column (the current
   `LeadTopRep` sort reads `lead_reps` instead of recomputing on every page load).
6. Tests: own-level visibility through a rep row; account-manager mirroring; rollup auto-add; merge coverage
   (`IdentitySchemaCoverageTest` is the guard that fails otherwise).

**1B. "My Work" (5–7 days).** `GET /manage/my-work` (Operations suite; the Dashboard entry and
`useOperationsLanding()` send sales roles here). One screen, five blocks, all MINE (the signed-in user), all re-using
existing readers:

| Block | Reads | Exists? |
|---|---|---|
| **Do now** — open `lead_action_items` assigned to me, grouped *Call* / *Zoom* / *Record outcome* / *Other*, overdue first, each with the lead's phone (click-to-call `CallLogButton`), WhatsApp link, last AI-call summary | `LeadActionItem` + `ActionItemsPanel` rows | ✅ model, partial UI |
| **My leads** — leads I am a rep on: journey box, last touch, my time with them | `lead_reps` (1A) + `lead_journeys` (Phase 2) | NEW |
| **Today's appointments** | `ResolvesLeadAppointments` / calendar | ✅ |
| **Waiting on my reply** | `ReplyOwed` (the Leads list's red "!") scoped to my leads (= reps) | ✅ |
| **My week** — calls · talk time · meaningful · Zooms · paid, vs last week | `SalesEngagementReport` for one person | ✅ |

Rules: the page writes nothing new; closing a task is the existing `done` endpoint with the NEW outcome form
(Phase 3). The boss's view is the same page with a person picker (`view-leads-all`), which is what makes it a
tracking surface too. Tests: one Feature test (own-scope, grouping, overdue) + one Vue test.

### Phase 2 — the Journey tracker (6–8 days)

- **`lead_journeys`** one row per (lead, funnel) — see §5. Started by `RegisterLeadAction` (fail-soft, like
  enrichment). **`lead_journey_events`** — append-only log: `event`, `from_step`, `to_step`, `ref_type/ref_id`
  (the AI call, the message, the registration, the purchase, the action item), `actor_id`, `at`.
- **Writers (hooks, all fail-soft, all idempotent per ref):**
  - `AiCallAftermath::settled/analyzed` → `ai_call_answered` (+ DATA 1 ref) / `ai_call_missed`
  - `AiCallbackController@show` → `callback_clicked`
  - `SendAiCallFollowUp` → `missed_message_sent` / `offer_sent`
  - `ReconcileWebinarAttendance` → `webinar_attended` / `webinar_no_show` (Stage 1 → 2, Stage 2 → 3)
  - `PurchaseFulfiller::fulfill` → `paid` (definition from §7)
  - `LeadActionItemRepository` done → `human_done` (+ the outcome form = DATA 2 / 4 / 5)
  - `EngagementRepository::changeStatus` → `closed_won` (Booked) / `closed_lost` (+ reason code)
- **`journey:advance` (every 5 min, `withoutOverlapping`)** — the only place time-outs live: *"M2/M3 sent, nothing
  clicked for N hours → hand to a human"*, *"webinar ended, no attendance verdict after 30 min → treat as no-show"*,
  *"Preview ended → mark as a Project-webinar candidate and open the review task"* (never a registration —
  §8, Zoom cannot be un-registered). Each rule is a small class in
  `src/Lead/Journey/Rules/`, registered in `config/journey.php`, so a new box is one class.
- **Hand-off = one method, `JourneyHandoff::toHuman($journey, $kind)`:** picks the person (round robin, §5),
  sets `leads.assigned_admin_id` (Stage 1) or `engagements.zoom_closer_id` + closer role (paid path), creates the
  `lead_action_item` (topic, due = next business hour, `source = journey`, the question set attached), fires the
  existing `leads.action_item_assigned` Telegram alert. Idempotent per (journey, step).
- **Surfaces:** a `Journey` chip on the Leads list + a `Journey` panel on the lead's Sales tab (the step, since
  when, owner, the log) — the modal shows the same (parity rule).
- Tests: a journey walks the whole Stage 1 happy path and both miss paths; hand-off idempotency; time-out rule.

### Phase 3 — Stage 1 complete (5–7 days)

1. **Round robin on webinar funnels** — generalise `FunnelCallerRotation` (today VSL-only) to any funnel, two queues
   kept (`KIND_LEAD` = nurture call, `KIND_BOOKING` = paid/REP), configured on the funnel hub (the modal exists).
2. **Hand-off rule** — "not clicked after N hours" (N per funnel, default 6h, capped at "3h before the webinar")
   and "AI call answered but NO useful information → human call" (§7 #3 / #10: useful = `will_attend` and
   `buy_intent` extracted; an answered call that got both creates no call task).
3. **Outcome form on an action item** (`lead_action_item_outcomes`): the question set's answers, `appointment_at`,
   `will_join_next_time` (bool), `no_answer` (bool). Posting it = DATA 2; it also writes a Discussion comment so the
   lead page reads it the way it reads DATA 1.
4. **"Join next time" mutes THIS session** — `event_registrations.reminders_muted_at`; both scanners
   (`RunFunnelReminders`, `RunFunnelAutomationReminders`) exclude muted rows; the roster shows a chip.
5. **Recurring group post** — allow a GROUP-audience before-event rule to be **slot-scoped** (fires for every
   session, claimed per `rule:event:group` — the key already exists), so "5 hours before, post to the group" is set
   once.
6. **R2 screenshot** — an after-start rule of a new medium `MEDIUM_TASK` that creates an action item for the webinar
   host ("post a screenshot to the group") with a one-tap upload that posts through the existing group-post job.
   (Pure automation is impossible: the screenshot is taken during the webinar.)
7. **M1 quick-reply button** — Cloud template with a quick-reply button; the reply "Yes, 我已进群了" is caught by the
   existing template-menu flow (`whatsapp-template-menu-flow`) and sends the bonus (content TBC, §7 #8).
8. The post-call "thanks" WhatsApp (`ai_caller_thanks_v2`) STAYS (§7 #7) — no work, listed so nobody removes it.

### Phase 4 — Stages 2 and 3: after the webinar (8–10 days + Meta review)

1. **Rule conditions** on both rule tables for `TRIGGER_AFTER_ENDED`: `attendance_condition`
   (any / attended / no_show — from `event_registrations.status`) and `payment_condition` (any / paid / unpaid —
   the §7 definition), mirroring the VSL `watch_condition` / `booking_condition` shape incl. the recorded
   `Skipped(condition_not_met)` verdict. Plus, on AI-call rules of any trigger, a **`cohort` condition**
   (any / attended_source_funnel — owner decision #15: the Project webinar's no-show call only rings people who
   attended a Preview session). UI: three chip groups on `ScheduleFields.vue`.
2. **Templates**: M4 (after-webinar missed call), "Payment received", "Why didn't you attend", "Follow-up (unpaid)" —
   authored on Messages → Templates, submitted to Meta (1–3 days review each). A rule-level
   `missed_template` override on AI-call rules so Stage 2/3 calls use M4, not `ai_caller_missed_v2`.
3. **Paid path** — on `paid`: journey → `JourneyHandoff::toHuman(KIND_BOOKING)` sets `zoom_closer_id` + closer role,
   creates "Call to book the Zoom" (DATA 3+4 / DATA 5 question set), payment-received WhatsApp (exists for
   payment-link purchases; extend `DispatchPaymentAutomationAction` to portal checkout + manual entries — the known
   gap). The Human Zoom is booked with the existing "Schedule Sales Zoom Meeting" (purpose 2); its outcome form
   closes the task.
4. **Unpaid / no-show paths** — rules (conditions above) + the same hand-off rule as Stage 1.
5. **Candidates from the Preview — review first, THEN register (owner decision #14).** Today the Project webinar's
   roster is a CSV round-trip (648 of 686 on 1 Oct), and the owner wants to check the list before anything is
   sent. Why "check first" is not optional: a registration row IS a Zoom registration — the import controller
   dispatches `SyncWebinarRegistrants` (`RegistrationsImportController.php:153`), the `zoom:push-registrants`
   sweep retries every 5 minutes over every upcoming webinar (`PushZoomRegistrants.php`), creating a webinar
   pushes everyone already on the roster, and Zoom then emails the confirmation plus its 1-day / 1-hour reminders.
   There is no un-register at Zoom (`EventRegistrationRepository::remove` deletes the local row only). So the
   candidate list must be **computed, never stored as registrations**:
   - A **"From Preview" button** beside Import on a Project session's Registrations tab (`RegistrationsTab.vue`),
     shown when the session's funnel names a source funnel (`event_funnels.candidate_source_funnel_id`, Property
     Closing → Trust Nurturing; set on the funnel's edit form). It opens a `PreviewCandidatesModal`: everyone
     registered on a source-funnel session since the previous Project webinar (window editable) who is NOT on this
     session (and not on another upcoming session of this funnel — shown greyed with the session name). Columns:
     name · phone · Preview session · Attended? · Paid membership? · AI-call verdict · account manager.
     Filter chips Attended / Registered only / Paid; **Attended is pre-ticked, the rest are not.**
   - **Register selected** → `EventRegistrationRepository::join()` with a new `EventRegistration::SOURCE_JOURNEY`
     (= 6, label "From Preview") so the roster says why they are there. The existing Zoom push then runs — that is
     the moment Zoom emails them, and the admin has just approved it. Unlike CSV import, this source DOES fire the
     funnel's ON_REGISTER rules (the Project webinar's own welcome), and BEFORE/AFTER-event rules reach it like any
     source (`RunFunnelReminders.php:246-262`).
   - The journey records `enrolled_project_webinar` on each person, and My Work shows the ops/marketing user one
     task per upcoming Project session: "Review N candidates for ViiA · 10 Oct" (created when the session is
     scheduled, closed when the modal is used or the session starts).
   - The CSV import stays unchanged as the fallback for people who never came through the Preview.
   ⚠️ **Cost of the Project webinar's no-show path (owner decision #15: budget raised AND warm cohort only).** 604 of
   686 did not show on 1 Oct; calling all of them at USD 0.25 / minute (`RETELL_PER_MINUTE_USD`) would be ~USD 150
   per session. The no-show AI-call rule therefore carries a **`cohort` condition** (item 1): `any` ·
   `attended_source_funnel` = the person has an ATTENDED registration on any session of the funnel's
   `candidate_source_funnel_id` (Property Closing → Trust Nurturing). Everyone else gets the no-show WhatsApp only.
   Still set `RETELL_DAILY_BUDGET_USD` above the cohort's worst case before the rule goes live.
7. **AI-call pacer (safety net — build LAST in this phase; the cohort rule in item 5 removes the burst).**
   `PlaceAiVoiceCall` fires calls as fast as the
   `redis-broadcast` lane hands them over (one process, no per-minute cap, no 429 handling); Retell refuses
   anything above the account's concurrent-call limit and the refusal is simply logged, the row FAILED, no retry
   (`RetellConversationalCaller.php:86-96`, `RetellCallMapper.php:207`). A 600-call burst 15 minutes after start
   would mostly fail. Add a `calls_per_minute` setting (`RETELL_CALLS_PER_MINUTE`, default 10 — Retell's base
   concurrency ÷ a 2-minute average call) enforced by a `RateLimited` job middleware on `SendFunnelAiCall`, plus
   **one retry 10 minutes later** when Retell's body says concurrency; and record the final refusal on the
   journey as `ai_call_refused` so the hand-off rule still fires. Paced at 10 / minute the 600 calls take an hour,
   which still lands inside the webinar — set the Project webinar's no-show rule at 15 minutes, not later.
6. **Closing** — `engagements.lost_reason_code` (`Not ready to buy`, `No loan eligibility`, `Bought elsewhere`,
   `Unreachable`, `Other`) required beside the free text; `StatusChangeModal` gains the select; Won = Booked;
   the journey closes on either.

### Phase 5 — the boss's board and reports (4–5 days)

1. **Funnel hub → Journey tab** — the flowchart as counts: how many people in each box per stage, drop-off between
   boxes, median time in box, and per salesperson: tasks open / overdue / done this week, calls made, Zooms held,
   booked. Filters: session, date range, person. Built on `lead_journeys` + `lead_journey_events` (no new
   definitions of calls/Zooms — `ChannelLeaderboard`).
2. **Report** — one `BaseReport` class, `LeadJourneyReport` (`journey-weekly`): the same board for the week, per
   person, with the AI 3-sentence summary; Sunday 11pm beside the Friday sales report. This is the frame the
   "Sunday tracking board" the boss already asked for plugs into.
3. **Leads list** — `journey` filter dimension (stage / step / owner) and the Pay-attention flag
   `journey_overdue` ("a journey task overdue > 24h").

### Phase 6 — DATA capture and AI reading (3–4 days, can run in parallel with 4–5)

- DATA 1: the three fields on the AI profile's analysis schema → `lead_journey_events.data`.
- DATA 2 / 4 / 5: the outcome form answers.
- DATA 3+4 (paid path): the REP's Zoom outcome form.
- All five feed the lead's **Summary (客户档案)** and the readiness **records** layer (`ReadinessColumns` reads
  `lead_journey_events` for Need / Decision-maker / Cash where the question maps).

**Total: ~38–50 working days** for one developer (33–44 before lead reps and the candidate review + AI-call
pacer were added on 2026-10-03), plus Meta template review. Phases 1 and 2 give the boss's
objective (a clear "what do I do") within the first two weeks; Stages 2/3 automation follows.

---

## 5. Data model (new)

```
lead_journeys
  id, uuid, lead_id (idx), event_funnel_id (idx), unique(lead_id, event_funnel_id)
  stage          uint  1 registration · 2 preview follow-up · 3 project follow-up · 4 closed
  step           string(40)  the flowchart box: registered · welcome_sent · ai_call_pending · ai_call_answered ·
                            missed_sent · offer_sent · human_pending · human_done · reminders · webinar ·
                            attended · no_show · paid · unpaid · rep_assigned · zoom_pending · closing · won · lost
  status         uint  1 active · 2 won · 3 lost · 4 stopped (unsubscribed / removed)
  owner_user_id  nullable (the person currently responsible)
  current_event_id   nullable (the session this stage is about)
  next_check_at  nullable datetime (what journey:advance looks at)
  paid_at, attended_preview_at, attended_project_at, closed_at   nullable
  lost_reason_code  nullable uint
  blame + timestamps

lead_journey_events  (append-only)
  id, lead_journey_id (idx), event string(40), from_step, to_step, ref_type, ref_id, actor_id, data json, created_at
  unique(lead_journey_id, event, ref_type, ref_id)   ← idempotency

lead_reps   (one lead → many staff; the account manager is always one row — §9)
  id, lead_id (idx), user_id (idx; users.id — the same id type as leads.assigned_admin_id; the recording tables'
  admins.id is joined through admins.user_id), unique(lead_id, user_id)
  kind          uint  1 account manager · 2 handed off (journey / action item) · 3 closer · 4 interacted · 5 manual
  source_type / source_id   nullable (the action item, engagement assignment, success role … that made them a rep)
  started_at, ended_at (nullable — a retired rep keeps its history, grants no visibility), added_by
  cached by reps:rollup: first_interaction_at, last_interaction_at, phone_seconds, zoom_seconds, f2f_seconds,
                         whatsapp_messages, tasks_done, appointments_held
  blame + timestamps
zoom_meetings                  + actual_seconds (from the participants API the recording sync already calls)

journey_question_sets          one per (funnel, step kind): the 1) 2) 3) a human / the AI asks
lead_action_item_outcomes      action_item_id, answers json, appointment_at, will_join_next_time, no_answer, blame
event_registrations            + reminders_muted_at
event_series                   + feeds_series_id (the next webinar), + handoff_hours (default 6)
funnel_whatsapp_messages / funnel_automation_messages
                               + attendance_condition, + payment_condition, + missed_template (AI-call rules)
engagements                    + lost_reason_code
funnel_caller_rotations        funnel_type guard removed (VSL-only today)
```

Everything else is re-used: `lead_action_items` (+ `source = journey`), `leads.assigned_admin_id`,
`engagements.zoom_closer_id`, `ai_voice_calls`, `event_registrations`, `purchase_histories`, `appointments`.

---

## 6. How the boss tracks it (summary)

| Question | Where |
|---|---|
| Is every lead being worked? | Journey tab: people per box, **overdue tasks** in red, unowned leads |
| Who did what this week? | My Work (person picker) · Sales Engagement · Journey report (Sunday) |
| Where did we lose them? | Journey tab drop-off per box · `lost_reason_code` breakdown |
| Did the automation run? | existing rule stats on the Automation tab (sent / reached / problems) |
| Did the paid lead get a Zoom? | Property Closing (Zoom Closer + Sales Zoom columns) — exists |
| Who is handling this lead, and how much time has each put in? | Lead Show → **Reps card** (per rep: phone · Zoom · showroom time, WhatsApp messages, tasks, last touch) — §9 |
| How much time does each agent spend with leads? | Employee Performance → **Time with leads** (Σ `lead_reps` per agent, drill to the leads) · Journey report |

---

## 7. Decisions log

### Answered by the owner (2026-10-03)

1. **"Paid?" = what THAT slot sells**, set per slot (`event_series_offers`). Stage 2 (after the Preview webinar):
   a membership. Stage 3 (after the Project webinar): the project fee collected through Stripe at the webinar
   (e.g. ViiA RM 299) → the lead auto-enters that project's sales pipeline (exists). The 1-1 sales Zoom then asks
   the lead to pay the **booking fee to the developer** — nothing passes through us; a human marks the engagement
   **Booked**.
2. **Closing = Booked. Converted = SPA signed** (the existing Booked → Converted work).
3. **Stage 1 human call:** every lead is handed to a sales agent by round robin; the agent calls when the AI did not
   get useful information.
4. **"Clicked? No" → human after 6 hours, never later than 3 hours before the webinar.**
5. **Everyone who came to the Preview webinar goes on to the Project webinar** ("全部自动登记") — *refined the same
   afternoon by #14:* the system lists them, the admin reviews and registers; attended people are pre-ticked.
   The CSV import continues as the fallback.

### Decided by the implementer (owner said "depends on your decision"; say so if any is wrong)

6. **Paid-check timing:** the paid branch fires the moment the payment webhook lands; the UNPAID branch waits
   **2 hours after `ended_at`** so people paying right after the webinar are never chased as unpaid.
7. **The post-call "thanks" WhatsApp stays** (it is live, costs nothing, and quotes the lead's own words back —
   it doubles as the DATA 1 confirmation).
8. **M1's "Yes, 我已进群了" button:** kept; the reply is caught by the template-menu bot and sends the bonus. The
   bonus content = the owner's call (the login link / AI property report is the obvious candidate).
9. **No-show but paid → the paid path wins** (money outranks attendance; they get the REP and the Zoom).
10. **"Useful information" (Q3)** = profile 2 extracted `will_attend` AND `buy_intent` (not `unknown`). Useful → no
    call task; the owner still sees the lead under "AI handled" on My Work. Not useful / unanswered / unclicked →
    a *Call* task after the 6-hour rule.
11. **DATA numbering:** Stage 3's "DATA 3 / 4" are stored as `data_3b` / `data_4b`; the labels on screen follow the
    stage ("Stage 3 · after AI call", "Stage 3 · after human call").
12. **Stage 3 human action item** = "book the 1-1 sales Zoom / push to booking", not "remind to join the webinar".
13. **Stage 1 round robin assigns the ACCOUNT MANAGER** at registration (like the VSL `KIND_LEAD` queue), so the
    lead is visible to its agent whatever the visibility level later becomes. *With #16:* the same write also makes
    that person the lead's first **rep** — the account manager is always one of the reps (§9).

### Answered by the owner — second round (2026-10-03, afternoon)

14. **Preview → Project webinar is NOT an automatic registration.** Registering a person on the webinar pushes
    them to Zoom, and Zoom sends its own confirmation / reminder email at once — so the admin must be able to
    LOOK before anything is sent. The system prepares the **candidate list** (everyone who came through the
    Preview and is not yet on the next Project webinar); the admin reviews, ticks, and imports. This replaces the
    CSV round-trip; the CSV import itself stays as the fallback. Mechanics in Phase 4 item 5.
15. **Retell daily budget: the owner raises it — AND keeps the warm-cohort rule** (confirmed in the third round,
    2026-10-03 evening: "只打给有来过 Preview 的人 is nice"). The Project webinar's no-show AI call goes only to
    people who ATTENDED a Preview session; every other no-show gets the WhatsApp. That cuts the burst from ~600 to
    the Preview-attendee cohort (73 on the last Preview), so the **pacer** (Phase 4 item 7) drops to a safety net
    built last in Phase 4, not a prerequisite. A refused call is still recorded as `ai_call_refused`.
16. **Lead reps (NEW requirement).** The account manager is one lead → ONE admin. Add **lead reps**: one lead →
    MANY sales agents / admins, each with how long they have interacted with the lead (phone call, Zoom, F2F,
    WhatsApp…). **The account manager must always be one of the lead's reps.** Design in §9.
17. **"Paid" per webinar:** the Preview webinar's paid = a **membership** payment item (any membership); the Project
    webinar's paid = the **project** payment item only. (The owner numbers these Stage 1 / Stage 2 — the plan
    names them by webinar to avoid the off-by-one.)
18. **Funnels 7 / 8 / 10 (Cochrane VSL, Cochrane Webinar, HK): ignore for now** — the owner will move them under
    Trust Nurturing or Property Closing later. The journey code must therefore be per FUNNEL (opt-in), never
    global.
19. Two-step role change: **agreed.** Paid-check timing (webhook → paid at once; unpaid branch 2 h after end):
    **agreed.**

### Still open (none blocks Phase 0–2)

- Role matrix: who is the sales leader; what role the ops accounts (Leejie, Youchen, yongzhi, Support, Celeste)
  move to — a custom "operations" role is the clean answer.
- The spec's own copy items: M4's second line, "payment received" / "why didn't you attend" / "unpaid follow-up"
  copy, and the HUMAN call's three questions. Needed by Phase 3/4; Meta template review takes days, so earlier
  is better.

---

## 8. Risks and what limits them

- **Volume on humans.** If Q3 = everyone, Stage 1 creates ~700 tasks per session; My Work must group and the round
  robin must be weighted. Decide before building the hand-off rule.
- **Meta template review** blocks Stage 2/3 messaging by days; author the four templates in Phase 0 so review runs
  in parallel.
- **Own-level visibility surprises** after the role change — a lead with no owner is invisible to every agent.
  The Journey tab's "unowned" count is the safety net; the leader (all-level) sees them.
- **AI call cost and burst.** Stage 2/3 add up to two more calls per person per webinar, and the Project webinar's
  no-show call is ~600 people in one go. The daily budget (`RETELL_DAILY_BUDGET_USD`, default $15 ≈ 60 call-
  minutes at $0.25) refuses mid-run — the owner raises it (decision #15); Retell's concurrency limit refuses the
  rest unless the calls are paced (Phase 4 item 7). Every refusal is recorded on the journey as `ai_call_refused`
  so the hand-off rule still fires.
- **A Zoom registration cannot be taken back.** Anything that creates an `event_registrations` row on a webinar
  session is pushed to Zoom within 5 minutes and Zoom emails the person at once. The candidate flow (Phase 4
  item 5) therefore computes its list and writes nothing until the admin clicks Register; no "hold" column is
  needed as long as that stays true.
- **Two sources of "task"**: `lead_action_items` is also written by AI insights (proposals) and by hand. The journey
  marks its own (`source = journey`), and My Work groups by source so the flow's tasks are never buried.
- **The 5-minute scanners** already run three sweeps; `journey:advance` is a fourth — index `next_check_at` and
  bound each tick (500 rows), like the others.
- **Two staff id types.** Recordings, meetings and showroom rows store `admins.id`; leads, reps, action items and
  WhatsApp store `users.id`. Every rollup joins through `admins.user_id`; mixing them silently credits the wrong
  person (the Zoom dashboard and `AgentsController` already disagree with `ChannelLeaderboard` on which meetings
  count — the rep rollup follows `countableRows`, the stricter rule).

---

## 9. Lead reps — one lead, many staff, with time per person (owner requirement #16)

**What the owner asked for (2026-10-03):** the account manager is one lead → ONE admin. Add *lead reps*: a lead can
be handled by SEVERAL sales agents / admins, the account manager is always one of them, and for each rep show how
long they have interacted with the lead (phone call, Zoom, showroom, WhatsApp …).

**What already exists — read before building:**

- A DERIVED "Rep" exists today: `LeadTopRep::query()` (`src/Lead/Support/LeadTopRep.php:40-87`) sums seconds per
  (lead, admin) over `zoom_meetings`, `call_recordings` and `f2f_recordings` and keeps the top one — it is the "Rep"
  line on Intelligence → Summary (`RecordOverview.vue:343-349`) and the Leads list's Rep sort / filter.
  `LeadsController::staffPerLead()` (:4678-4723) already returns EVERY staff member with count + seconds per
  channel for one lead, and `ChannelLeaderboard::client_rows` is the same per (admin, lead) for the Operations suite.
- `lead_success_roles` (Analyst / Caller / Closer, one person per role; founder 2026-09-19) is the lead's named
  team — by its own docblock it touches neither visibility nor money.
- `engagement_assignments` is a DEAL's team and doubles as the commission split — many admins per engagement,
  already read by `LeadVisibility`.
- No lead ↔ staff many-to-many exists (`lead_admins`, `lead_owners`, `lead_reps`, `lead_watchers` … none). The
  previous one, `member_subscription_managers`, was deliberately collapsed into the single account manager on
  2026-07-18 — the new table is a different thing (who HANDLES the lead, not who owns them) and must say so.

So the gap is not the arithmetic — it exists — but: (1) nobody can be MADE a rep; it is only inferred from recordings;
(2) WhatsApp, tasks and appointments do not count; (3) one top rep is shown, not the list; (4) it does not drive
visibility; (5) Zoom time is the BOOKED length, not the actual one.

### Design

**One table, `lead_reps` (§5) = the explicit list + cached time per person.** A row exists for everyone responsible
for the lead; `reps:rollup` keeps each row's time columns fresh. Who gets a row, and when:

| How someone becomes a rep | `kind` | Written by |
|---|---|---|
| Is / becomes the **account manager** | 1 | `LeadRepository::assign` + `LeadDistributionRepository::assign` / `moveToPool` — the two choke points behind all seven writers — inside their existing transaction. When the manager changes, the old one drops to kind 4 and is RETIRED (history kept, access ended) unless a closer role, an open task or a Client Success role still ties them to the lead — *corrected 2026-10-04; the first build kept them ACTIVE, which left a moved lead in the old agent's list (see the build log).* |
| Receives a **journey hand-off** (Call / Zoom task) or is assigned any `lead_action_item` | 2 | `JourneyHandoff::toHuman()` (Phase 2); `LeadActionItemRepository` on assign / `done()` |
| Is set as **Zoom closer** or holds the `closer` engagement role on one of the lead's deals | 3 | `EngagementRepository::setZoomCloser` / `assign` |
| **Interacted**: a phone recording linked to the lead, a 1-1 Zoom with the lead that happened, a showroom session, an outbound WhatsApp written from the inbox (`created_by`), an appointment held | 4 | `reps:rollup`, on first sight |
| Added by hand on the Lead page | 5 | `LeadRepsModal` → `LeadRepRepository::addRep` |

Holders of a `lead_success_roles` role are mirrored as reps too (kind 5, `source` = the role row), so the three
"hats" sit ON the list instead of beside it. Folding `lead_success_roles` INTO `lead_reps` (a nullable `role`
column) is possible later; not now — it is three weeks old, founder-specified, and nothing here needs it.

**Time per rep — what counts, and how reliable it is** (from the inventory of all 12 interaction sources):

| Channel | Column | Reliability |
|---|---|---|
| Phone | `call_recordings.duration_seconds` (recorder-measured; clips under 60 s are hidden stubs) | reliable |
| Showroom | `f2f_recordings.duration_seconds` (badge end − start) + `agent_f2f_sessions` start / end | reliable |
| Zoom 1-1 | `zoom_meetings.duration` × 60 — the BOOKED length for app-scheduled rows, Zoom's figure for synced rows; only meetings that happened (`ChannelLeaderboard::countableRows`) | approximate → 1A also stores `actual_seconds` from the participants API the recording sync already calls and discards (`ZoomRecordingSyncService.php:746-780`) |
| WhatsApp | COUNT of outbound messages with `created_by` = the rep (NULL = AI / flow / phone); no duration exists and none is invented | count only |
| Tasks · appointments | `lead_action_items.done_by`; `appointments.assigned_admin_id` with a held outcome | count only |
| AI calls | `ai_voice_calls.duration_seconds` — shown as a separate "AI" row, never as a human rep | reliable, not a rep |

**The staff id trap:** recordings and meetings store `admins.id`; everything else stores `users.id`.
`lead_reps.user_id` is `users.id` (like `leads.assigned_admin_id`), and the rollup joins the recording tables through
`admins.user_id` (`OperationsController.php:791-793` documents the same split).

**`reps:rollup`** — every 15 minutes over leads touched since the last run; `--all` backfills once. It recomputes the
cached columns from the `staffPerLead()` sources plus the WhatsApp / task / appointment counts, inserts a kind-4 row
for a new (lead, staff) pair, and stamps `first_interaction_at` / `last_interaction_at`. Cheap: the three recording
tables are the ones `LeadTopRep` already scans on every Leads list load — this moves that work off the request.

**Visibility.** A rep sees the lead: `LeadVisibility::apply()` gains `orWhereHas('reps', active · user_id = me)` in
the OWN arm (team / group arms through their member ids), `allows()` mirrors it, and `AgentLeadAssignments`
(`assignedTo` / `lockAssignedTo`) too — or the agent app disagrees with the web. Retired reps (`ended_at` set) grant
nothing.

**Merge / purge.** Register `lead_reps.lead_id` + `user_id` in `IdentityChildMap` (`lead_success_roles` at :282 /
:487 is the template), dedupe on merge (keep the earlier `started_at`; the rollup recomputes the rest), cascade on
delete. `IdentitySchemaCoverageTest` fails CI until this is done.

**UI.**

- Identity header (`Show.vue:406-413`, `LeadDetailModal.vue:565-570`):
  `Account manager · Kexin     Reps · Zen 2h 10m · Boon 35m · + add`.
- Intelligence → Summary: the single "Rep" line becomes a **Reps card** — one row per rep with phone · Zoom ·
  showroom time, WhatsApp messages, tasks done, last touch; an "AI" row underneath; *Remove* is refused for the
  account manager ("change the account manager first").
- `LeadRepsModal` — multi-select modelled on `AssignLeadManagerModal.vue`, options from `assignableManagerOptions`
  (in-scope staff only), permission `manage-leads`.
- Leads list: a **Mine** filter (I am a rep) beside the account-manager filter; the Rep column reads `lead_reps`.
- My Work (Phase 1B): *My leads* = leads I am a rep on.
- Boss: Employee Performance → **Time with leads** per agent (Σ cached seconds, drill-down to the leads); the Journey
  report lists per agent: leads handled · hours · tasks done.

**Backfill on day one (production):** 329 account managers → kind 1; every `engagement_assignments` holder → kind 3;
`lead_success_roles` → kind 5; every (lead, admin) pair with a recording / meeting / showroom session → kind 4;
WhatsApp `created_by` pairs → kind 4. Expect a few thousand rows.

**Not in scope:** paying anyone for being a rep (commission stays on `engagement_assignments`); WhatsApp time (not
measurable); the Appointment Engine's `ae_leads` book.
