# Registration of Interest (ROI)

**Portal:** Manage + a public form · **Home:** a PROJECT-FEE payment item's own page → **Registration** tab (`/manage/payment-links/{uuid}?tab=registration`) · **Public:** `/roi/{token}` (`main.roi.show` / `main.roi.submit`) · **Lead:** Lead → Sales → **Registration** (only when the person has one) · **Built:** 2026-11-09 for *Forest Hill Gombak*, replacing the Google Form "Registration of Interest - New Project Launch NOV 2026".

## What it does

After a buyer pays a **project fee** (a payment item selling a `Src\Property\Project`), a WhatsApp message brings them **their own** Registration of Interest form — one link per buyer per item. They fill it in once and it **locks**.

The form asks what the Google Form asked, with the owner's three changes (2026-11-09):

1. **Prefilled.** Name, phone and email come from what the buyer typed at the **Stripe checkout** minutes ago (`purchase_histories.counterparty_name / _email / _phone`), then from the CRM (IC number, date of birth, occupation, company, address). Everything stays editable.
2. **"Own name or joint names?"** replaced "Number of Purchaser 1/2/3" — leads misread the number on the first launch night. Own name → no joint-buyer section at all. Joint → 1 or 2 more buyers (3 at most).
3. **Every purchaser signs the existing FPA consent** (the Lead → Financial Report one: IC photos + signature + PDF). A joint buyer signs on the same phone. Someone who already signed is not asked again; a buyer whose IC is on file is not asked to upload it again — **unless purchaser 1 is typed with another IC number than the one on file** (a payer naming a spouse or a child: two buyers did on the 2026-11-09/10 launch, and the form handed the developer the payer's IC under the other person's name). Then that person's IC is asked for (fixed 2026-11-10).

Per purchaser: NRIC name, NRIC/passport no., date of birth (auto-filled from a Malaysian NRIC), mobile, email, IC front & back, race (Malay / Chinese / Indian / Others), correspondence address, marital status (**Single / Married** only, owner), citizenship (Malaysian / Singaporean / Singapore PR / Other + text), occupation, company. Once per form: financing (Bank Loan / Cash / Others) and the 1st / 2nd / 3rd unit-type preference.

**Joint buyers become real people in the CRM** — resolved through the identity gate (`LeadRepository::findForIdentity` first, then `selfTypedPhoneForGate` + `firstOrCreateForIdentity`, the same path a checkout buyer takes), never inserted. A joint buyer who turns out to be the buyer again (or one person named twice) is refused BEFORE any lead is created.

## How it works

### Sending the link — a payment-automation trigger

`PaymentLinkAutomation::TRIGGER_PAID_ROI = 6` ("After payment · Registration of Interest"), in `PAID_TRIGGERS`, **project fees only** (`ROI_PAYABLE_TYPES`; `PaymentLinkAutomation::triggerAppliesToPayable()` is the one rule the tab, the form request, the dispatcher and the job all read). Template shape: `{{1}}` buyer name, `{{2}}` **the buyer's own ROI link** (`PaymentAutomationVariables::KEY_ROI_LINK`). Everything else is the standard payment automation — exactly-once claim per purchase, `effective_from` launch cutoff (buyers who paid before the rule existed are never auto-messaged; **owner, 2026-11-09: the 21 Forest Hill Gombak buyers of 11-08 are NOT sent anything**), refund / opt-out / template-approval re-checks. See [Payment Automation](/docs/modules_handbook/manage/payments/payment-automation/readMe.md).

- The rule **cannot be saved** until the item lists at least one unit type (`StoreRequest`), and the job skips with `missing_config` if an admin clears them later (`PaymentLink::roiReady()`).
- The link is minted in the JOB, after every skip (`RoiRegistrationRepository::invite()`), so a message that never goes out mints nothing. `invite()` returns the buyer's existing registration for that item — **paying twice never makes a second form**. Uniqueness is enforced under a lead-row lock, NOT a unique index: a lead merge re-points `lead_id` (IdentitySchemaCoverageTest forbids a unique index on a re-pointed column).
- ⚠️ **A WhatsApp template must be approved first.** None exists at Meta yet (2026-11-09). Without one the trigger has nothing to send.

### The form — `RoiController` + `SubmitRoiRegistrationAction`

- `show()`: open → `Main/Roi/Form` (prefill + `BuyerOnFile`: is the buyer's consent signed? is their IC on file, and WHOSE — `icIdNumber`, normalized, so the form shows the upload the moment purchaser 1 is typed with another number); submitted → `Main/Roi/Submitted`, which shows **nothing** of what was submitted (the link is a forwardable bearer token).
- `SubmitRequest`: every Google-Form question is required per purchaser. The buyer's signature is required only when their consent is unsigned, their IC photos only when not on file **for the number typed** (`BuyerOnFile::icOnFileFor()`: both sides held, and the IC number on file — the signed consent's `snapshot_id_number`, else the profile's — matches, letters and digits only) — the SAME `BuyerOnFile` reading the form used to hide them. Joint buyers always give both. Different email and phone per purchaser; each unit type ranked once; a rank is required only if the item lists that many types.
- `SubmitRoiRegistrationAction::execute()`:
  1. resolves every purchaser to a lead (all lookups before any write);
  2. `backfillContact()` — fills the person's BLANK email / phone / name only (guarded against another account's value);
  3. signs each unsigned consent through `LeadConsentRepository::generateLink()` + `sign()` — the consent form's own writer, PDF or nothing (`ConsentPdfFailedException` → "press Submit again"; a consent that did sign stays signed and is skipped on retry);
  4. points each purchaser row at IC photos the **consent or profile** already owns (`idPhotos()`); only when neither has any (an imported consent still waiting for its files) are this form's uploads stored, on the PROFILE — so the privacy purge that reaches the consent and profile reaches every IC photo. **When the IC on file is somebody else's** (`BuyerOnFile::belongsToSomeoneElse()`), the uploads are used instead and kept on the **REGISTRATION**, never the payer's profile; `LeadRepository::purgeStorage()` reaches them through `roi_registrations`. ⚠️ Still open: a payer with NO consent yet signs it with the typed person's name and IC (the consent is per lead), and the profile's blank occupation / company / IC are filled from them — there is no "I am paying for a family member" option;
  5. `RoiRegistrationRepository::submit()` — writes the registration + purchaser rows under a row lock (a double tap cannot write twice), fills the profile's BLANK occupation / company, and **locks** (`STATUS_SUBMITTED`);
  6. activity: `TYPE_ROI_SUBMITTED` on the buyer, `TYPE_ROI_JOINT_BUYER` on each joint buyer.
- The address stays on the ROI (free text); it is not written into the structured `addresses` table.

### Staff side — Registration tab (`PaymentLinkRoiController`)

- **Settings** (`PUT {id}/roi`, `manage-sales`): title (default "Registration of Interest — {item}"), terms (plain text, shown above "I agree"), unit types (one per line).
  - **The terms are laid out from the text itself** (`Components/Roi/RoiTerms.vue`), so the admin learns no markup: lines starting `1.` / `2)` become numbered rows with badges (an unnumbered line between two of them continues the one above); lines before the first are the introduction, its first line a heading when there are several; lines after the last are the closing statement, set apart because the "I agree" tick answers it. No numbered lines → plain paragraphs. **Never a scroll box**: on a phone a capped box showed 3 of the 7 terms. Plain field writes on `payment_links` (`roi_title`, `roi_terms`, `roi_unit_types` JSON) through `PaymentLinkRepository::update()`.
- **Preview** (`GET {id}/roi/preview`) renders the buyer's form with `preview: true` — submit switched off. Shares `RoiForm::props()` with the real form, so what staff see is what buyers get.
- **List**: one row per registration (Waiting = link sent / Submitted), Copy link while waiting, purchasers with consent ✓, financing, preferences. **View** opens `RoiRegistrationModal` (every field + IC photos); **Edit** (`PUT {id}/roi/{registrationId}`, `manage-sales`) corrects the answers and each purchaser's typed details — not who they are (lead, consent, photos). Logged as `TYPE_ROI_EDITED` (coalesced).
- **Excel / CSV** (`GET {id}/roi/export`) → `RoiRegistrationsExport`: one row per registration, purchasers 1–3 side by side. Every cell is TEXT (`StringValueBinder`) — no money in it, and an IC number left to Excel becomes `9.01E+11`.
- **IC photos** (`GET {id}/roi/{registrationId}/documents/{mediaId}`) stream inline, only for a photo a purchaser of THAT registration points at, and only for an admin `LeadVisibility` allows to see the buyer — the FPA documents' rule.
- All routes are addressed under the item and scoped to project-fee items (`projectItem()`), so another item's registration is a 404.

### Stripe checkout fields

`WebhookProcessor::recordHostedLinkPayment()` (live webhook + link import) now keeps the checkout **name** and **email** on the payment beside the phone (`counterparty_name`, new `counterparty_email`, migration `2026_11_09_100003`). Same rule as the phone: a fact about the transfer, never written onto the CRM's record of the person. Payments recorded before 2026-11-09 have no checkout name/email; their form prefills from the CRM.

## Data

| Table | Holds |
|---|---|
| `roi_registrations` | One per (payment item, buyer lead): `token` (the `/roi/{token}` link), `status` (1 waiting / 2 submitted), `ownership` (1 own / 2 joint), `financing`, `preference_1..3` (unit-type labels as typed in settings), `purchase_history_id`, `submitted_at` / `submitted_ip`. |
| `roi_purchasers` | One per buyer named on it (`position` 1–3): `lead_id`, `lead_consent_id`, the typed details, `race` / `marital_status` / `citizenship` (+`citizenship_other`), `id_front_media_id` / `id_back_media_id` (consent's or profile's media). |
| `payment_links.roi_*` | `roi_title`, `roi_terms`, `roi_unit_types` (JSON list). |
| `purchase_histories.counterparty_email` | The email typed at a gateway-hosted checkout. |

Identity map: `roi_registrations.lead_id` and `roi_purchasers.lead_id` are MERGE_REPOINT / PURGE_DELETE_BY_LEAD (`IdentityChildMap`).

## Related files

**Backend**
- `src/Roi/RoiRegistration.php`, `src/Roi/RoiPurchaser.php` — models + constants (STATUSES, OWNERSHIPS, FINANCINGS, RACES, MARITAL_STATUSES, CITIZENSHIPS)
- `src/Roi/Repositories/RoiRegistrationRepository.php` (+ `src/Roi/Facades/`) — `invite()`, `submit()`, `update()`, `currentFor()`
- `src/Roi/Support/BuyerOnFile.php` (consent signed? IC on file?), `RoiForm.php` (the form's shared props), `RoiRegistrationPresenter.php` (the ONE row shape for tab, lead tab and export)
- `src/Roi/Exceptions/RoiLockedException.php`
- `app/Actions/Roi/SubmitRoiRegistrationAction.php`
- `app/Http/Controllers/Main/Roi/RoiController.php`, `app/Http/Requests/Main/Roi/SubmitRequest.php`
- `app/Http/Controllers/Manage/Payment/PaymentLinkRoiController.php`, `app/Http/Requests/Manage/Payment/PaymentLinkRoi/{SettingsRequest,UpdateRequest}.php`
- `app/Exports/RoiRegistrationsExport.php`
- Trigger wiring: `src/Payment/PaymentLinkAutomation.php`, `src/Payment/Support/PaymentAutomationVariables.php`, `app/Actions/Payment/DispatchPaymentAutomationAction.php`, `app/Jobs/Automation/SendPaymentAutomationWhatsApp.php`, `app/Http/Requests/Manage/Payment/PaymentLinkAutomations/StoreRequest.php`
- `app/Services/Stripe/WebhookProcessor.php` — checkout name + email on the payment

**Frontend**
- Public: `resources/js/Pages/Main/Roi/Form.vue`, `Submitted.vue`; `resources/js/Components/Roi/PurchaserFields.vue`, `SignaturePad.vue`, `RoiTerms.vue`
- Staff: `resources/js/Pages/Manage/Payment/Links/Partials/Tabs/RoiTab.vue`, `Partials/RoiRegistrationModal.vue`; `Show.vue` (Registration tab); `AutomationTab.vue` + `AutomationRuleFormModal.vue` (the trigger)
- Lead: `resources/js/Pages/Manage/Leads/Partials/Tabs/RoiRegistrationsTab.vue`, `composables/useLeadTabs.js` (Sales → Registration)

**Migrations**
- `2026_11_09_100001_create_roi_registration_tables`, `2026_11_09_100002_add_roi_settings_to_payment_links`, `2026_11_09_100003_add_counterparty_email_to_purchase_histories`

**Tests**
- `tests/Feature/Payment/RoiRegistrationTest.php` — the link sent once per item, the rule refused without unit types, checkout prefill, a joint submission (new lead + both consents signed + lock), a joint buyer who is the buyer again refused with no stray lead.
