# HubSpot → CRM migration runbook

How to load AdMedia's HubSpot data into a CRM database. Written while migrating staging (Nov 2026)
so the prod load and the final cut-over re-run are a checklist, not a rebuild. Update it in the
same PR whenever a loader or a decision changes.

## 1. Rules

- **HubSpot is read-only.** The loaders only read (GET, and HubSpot's batch-read POSTs). Never
  write to HubSpot.
- **The token is never stored.** Set it for one run only (`export HUBSPOT_TOKEN=<token>`) and
  `unset HUBSPOT_TOKEN` after. Never put it in `.env`, a file, a commit or this doc.
- **No shortcuts.** Everything comes from HubSpot: every record, field value, owner, date, stage
  history, link and label. Loaders write through the CRM services, so history and audit are kept
  and events are `import` (workflows skip them).
- **Dry run first.** Every command without `--apply` writes nothing and prints what it would do.
  Read the report, then run again with `--apply`.
- **Back up the database before every `--apply`** (mysqldump of `DATABASE_URL`, gzip, keep in
  `~/backups`).
- **Low server load.** Run long loads in the background at low priority, one at a time:

  ```bash
  nohup nice -n 19 ionice -c3 bash -c '<command> > ~/migration/<name>.log 2>&1; echo "exit $?" >> ~/migration/<name>.log' > /dev/null 2>&1 &
  ```

- **Re-runnable.** Records keep their HubSpot id (`hubspotId`), so a second run only adds or
  updates what changed. Never delete records to "start over" without a backup.
- **Workflows.** `--apply` refuses to run while a workflow that takes import events is on.

## 2. Before you start on prod

- **No email catcher on prod.** `EMAIL_CAPTURE_SMTP_URL` (Mailpit) is staging only. On prod real
  emails go out, so keep workflows, sequences and user invites off until the load is checked.
- **Gmail sync.** `GMAIL_INITIAL_SYNC_DAYS` is 1 on staging. Set it for prod as agreed before
  users connect Gmail (the Inbox shows only CRM-linked threads).
- **Business slug** (`--business`, e.g. `admedia`) and an **admin email** (`--as`); the audit log
  shows that admin as who made the changes.
- **Deploy master first.** All loaders below are in the backend repo.

All commands run on the server from the backend's `apps/worker` folder:

```bash
cd <backend>/apps/worker
export HUBSPOT_TOKEN=<token>
npm run -s schema:load -- --business <slug> --as <admin email> <options> [--apply] [--out file.json]
unset HUBSPOT_TOKEN
```

## 3. Steps, in order

### Setup: objects, fields, pipelines

- [ ] Custom objects from the manifests (Events, Leads, Tickets, CTA Submissions), one at a time:
      `--manifest ../../packages/core/src/schema-loader/manifests/events.json` (then
      `leads.json`, `tickets.json`, `cta-submissions.json`). CTA Submissions (HubSpot 2-72305675,
      made 4 Nov 2026) are the websites' enquiries (HUB-753): one record per form sent, linked to
      the contact. Run `--hubspot` again after it, so the websites' newer contact fields come too.
- [ ] Every HubSpot field, read live from HubSpot's properties API (types, options, groups) and
      the association labels it can pair: `--hubspot`.
- [ ] **Held back (27 Nov):** `--hubspot` also wants to change some ticket fields (group, type) and
      activity fields (`hs_email_to_email`, `hs_attachment_ids`… text → dropdown / multi-select).
      A type change on a field with values can break them, so until those are reviewed run the
      field load with `--objects contact,company,deal,cta_submission,event,lead`.
- [ ] Rollups as HubSpot has them (after `--hubspot`): `--manifest ../../packages/core/src/schema-loader/manifests/rollups.json`.
      12 fields (recent event name, number of associated events / deals / leads, …) become
      rollups the CRM keeps up to date; Number of Associated Deals counts deals (Shubham, 26 Nov).
- [ ] Pipelines must match HubSpot exactly (deals ×2, leads, tickets, task). The task pipeline
      (UUID ids, up to 64 chars): `--hubspot --objects task`.
- [ ] Dropdown values as HubSpot's (Shubham, 26 Nov): `--hubspot-dropdown-values`. Lifecycle
      stage, lead status, industry and deal type store HubSpot's internal values ("customer",
      "235932291", "NEW"); labels stay ours. Changes the options, records, field history and the
      filters, workflow steps and views that name a value. Check `[still names an old value]`
      (should be none) and `[only in HubSpot]`.
- [ ] Check "Need Contact" is a closed-lost stage (default setup does this).
- [ ] Delete any test pipeline. Compare every pipeline and stage with HubSpot (staging: 31/31).

### Step 1: users, teams, template owners

- [ ] Users from a plan file: `--users plan.json`. Memberships are made silently (no invite
      email) and linked to their HubSpot owner. HubSpot owners not in the plan who still own
      records are kept as owners only (deactivated users).

  ```json
  {
    "users": [
      { "email": "danny@admedia.com", "set": "super_admin" },
      { "email": "jeff@admedia.com", "set": "super_admin" },
      { "email": "priyanka@admedia.com", "set": "super_admin" },
      { "email": "nick@admedia.com", "set": "all_access" },
      { "email": "yan@admedia.com", "set": "all_access" },
      { "email": "manderson@publicgood.com", "set": "sales_enterprise" },
      { "email": "andy@admedia.com", "set": "sales_ae" },
      { "email": "tim@admedia.com", "set": "sales_ae" },
      { "email": "geoff.loo@admedia.com", "set": "sales_ae" },
      { "email": "david.ruiz@admedia.com", "set": "sales_ae" },
      { "email": "narine@admedia.com", "set": "sales_ae" }
    ]
  }
  ```

- [ ] Teams: `--teams` (staging: Enterprise Sales, 6 members). Teams keep HubSpot's team id, which
      the calculated "HubSpot Team" field writes.
- [ ] Sales templates (319, from HubSpot's export CSV), owners moved to the loaded users:
      `npm run -s templates:import -- --business <slug> --as <admin> --csv <export.csv> --users <owners.json> --reassign-owners [--apply]`.

### Step 2: companies, contacts, deals

- [ ] `--standard company,contact,deal` (add `--limit N` for a test). Pick lists (lifecycle stage,
      lead status, deal type) are mapped from HubSpot's internal value to ours by label. A record
      with no HubSpot owner gets no owner. A company with no name gets its domain, else its
      website host, else "Unnamed company". Deals bring their stage history.
- [ ] The report lists the fields a re-run changes, with an example each. Check them. Fields the
      CRM works out itself (calculated fields, calculations, rollups: number of sales activities,
      last contacted, number of associated deals…) keep the CRM's value on a re-run and are listed
      as `[CRM keeps its own value]`; a new record takes HubSpot's value.
- [ ] 120 deals with no data (made by the "Admedia Errors - Companies.csv" import, 9 Oct 2025) fail
      by design and are skipped.

### Step 3: leads, events, labels, links

- [ ] `--object-records lead,event,cta_submission --links all`. Leads come with their stage, stage
      history, HubSpot create date and their HubSpot primary contact (else company). A second open
      lead on the same contact is kept as in HubSpot (HUB-338 rule 5). A CTA submission keeps
      HubSpot's create date (when the form was sent) and is linked to its contact
      (`cta_submission-contact`). The websites keep sending them to HubSpot until they switch to
      the CRM, so re-run at cut-over.
- [ ] Before linking, HubSpot's association labels are matched to ours (ids set, names made
      HubSpot's, missing ones made). Check the `Labels` lines: none should be `[failed]`.
- [ ] Check that no `[label not here]` line appears after `--apply`.

### Step 4: activities

- [ ] `--activities all` (or a list: `email,note,call,task,meeting,communication`). Emails,
      notes, calls (logs only), tasks, meetings and LinkedIn / SMS / WhatsApp messages, each on
      the records HubSpot links it to, with HubSpot's owner, dates, values and attachments. Made
      as an import: no task notices, no calendar events, workflows skip them. Long run (staging:
      about 2 hours, emails most of it), so run it in the background.
- [ ] Activities HubSpot links to no record are skipped and counted (`on no record here`).
- [ ] Check the `[not kept]` and `[failed]` lines. Expected: a few attachments HubSpot itself
      no longer has (404), meetings with no end time (end set to start + 1 minute).
- [ ] Only if the database was loaded before `activities.body` became MEDIUMTEXT (staging):
      `--refresh-email-bodies` gives the emails MySQL cut at 64 KB their full body from HubSpot.

### Step 5: everything else

- [ ] **Lists** (`--lists`): HubSpot's manual and snapshot lists become static lists with
      HubSpot's members and join dates; active lists become active lists with HubSpot's filter
      written as ours (the CRM then keeps their members current). Folders come along (nested
      ones as "Parent / Child"), with each list's HubSpot creator and dates.
  - An active list whose filter segments can't do yet (owner "has ever been", "filled out a
    form", "this month") is loaded as a static list of HubSpot's members, says so in its
    description, and is kept in step with HubSpot on every re-run. Check the
    `[kept as static]` lines.
  - `[HubSpot-calculated field]` lines: filters on fields HubSpot calculates (last activity
    date, …) use their values as loaded.
  - Active lists build in the background after `--apply`. Run the dry run again afterwards:
    the `[active]` lines then compare HubSpot's member count with ours.
- [ ] **Sequences** (`--sequences`): HubSpot's sequences, **ready to use** (D-5, 28 Nov 2026:
      there is no draft status), with their steps (emails by their migrated template, tasks,
      delays in business days), send window, owner and sharing. Needs step 1's users and
      templates. Nothing sends until a user with a connected Gmail enrolls contacts, or a workflow
      that enrolls is turned on (workflows load switched off). A sequence whose step lost its
      template (one the loader didn't bring over) is refused at enroll with its problems until
      someone picks a template. HubSpot's wait before a sequence ends isn't kept (ours can't
      end on a wait). Enrollments: HubSpot's API doesn't say which step a contact is on; asked
      of Shubham (26 Nov).
- [ ] **Subscriptions** (`--subscriptions`, after step 2): HubSpot's subscription types (Marketing
      and Sales are ours; others are added) and the suppression list: contacts unsubscribed from
      all email, and hard bounces (as of 26 Nov: 33 and 335). Their events are imports, so
      workflows don't start. Re-run at cut-over after step 2.
- [ ] **Field history** (`--property-history all`, after step 2; long, run in the background):
      every past value HubSpot keeps of the contacts', companies' and deals' fields (HubSpot
      keeps a limited number per field, so load it early), with date, user and source (CRM UI,
      workflow, import, integration…). It replaces the record load's "created with" rows; history
      made in the CRM stays. Deal stages keep their own history. Re-run at cut-over.
- [ ] **Goals** (`--goals`, after steps 1–2): HubSpot's goals with each person's or team's
      monthly targets. HubSpot keeps some goals once per person under one name ("Log 5 Meetings
      per Month" ten times); names are unique here, so those become one goal with each person's
      own targets. A "Date entered <stage>" goal counts deals in the month they first entered the
      stage (HubSpot also asks them to still be in it). Re-runs refresh the targets.
- [ ] **Booking pages** (`--booking-pages`, after step 1): HubSpot's meeting links as their
      owners' booking pages: meeting lengths, weekly hours, buffer (both sides), weeks ahead,
      start-time steps, extra form questions, location and headline. Addresses are
      `/book/<HubSpot slug>`, "/" becoming "-". A page is live only once its owner has connected
      Google Calendar here; until then it is switched off (`[switched off]` lines). Links HubSpot
      no longer serves (owners who left) have no settings to bring and are listed. Not kept:
      "invitee can add guests", consent checkboxes, welcome screen. HubSpot's API doesn't give the
      minimum notice: ours is 4 hours.
- [ ] **Forms** (`--forms`, after steps 1–3): HubSpot's forms of every type and their
      submissions. A form keeps its fields (each filling the same contact or company field),
      dropdown options, required marks, thank-you message or redirect, the people notified and
      its create date. HubSpot leaves a form's new contacts without an owner; here the first person
      notified owns them (else the admin loading it). Ticket questions on support forms keep their
      answers with the submission. "Captured" forms (picked up from another site's page) are made
      switched off, with the fields their submissions sent. Blog comment forms are listed: HubSpot
      exports no submissions for them. Each submission is saved on its contact (by email) with the
      note a submission makes here, dated as in HubSpot; no workflow or notification runs. Not
      kept: text and images between fields. 27 Nov 2026: 8 forms, 2 captured, 10 submissions.
- [ ] **Currencies** (`--currencies`): HubSpot's other currencies with their current rate (27 Nov:
      INR, 1 INR = 0.010533 USD in HubSpot → 1 USD = 94.94 INR here, as Account Defaults ›
      Currency shows rates). The company currency (USD) is only compared; a different one loads
      nothing. The exchange rate log gets HubSpot's date. A re-run changes nothing if the rate is
      the same.
- [ ] **Workflows** (`--workflows`, last: after lists, sequences, templates and link labels):
      HubSpot's workflows, **all switched off** (folder "HubSpot"), with their trigger
      (filter, a field changing, a record created, or by hand), re-enrollment, steps, branches and
      go-tos. A workflow with nothing left out is published (still off); one with a gap is a draft
      whose description says what is missing (e.g. a playbook trigger, creating a lead, adding to a
      multi-select, a sender whose Gmail is not connected). Workflows on Events aren't made yet.
      Each keeps its HubSpot id; a re-run makes only the missing ones. At cut-over turn on the ones
      that are on in HubSpot (`ON` in the report).
- [ ] Documents, snippets. **TBD** (HubSpot's API doesn't give them: exports needed).

### Step 6: final re-run at cut-over

- [ ] Stop work in HubSpot, re-run steps 1–5 (dry run, backup, `--apply`); only changes since the
      last load are written. Field history (`--property-history all`) rewrites all ~8 million
      rows, so run it once here, not on every re-run.
- [ ] Switch on, in this order (each needs the one before):
  1. Users: send the invites; people connect Gmail.
  2. Sequences: nothing to switch on (they load ready to use, D-5). Fix the ones whose steps
     show problems (e.g. a missing template) that are in use: a workflow that enrolls in a
     sequence can only be published once the sequence has none.
  3. Workflows: publish the drafts that were only blocked by a sequence (a draft one, before D-5,
     or one with step problems) or a user who had not accepted yet (the description says so),
     then turn on the ones that are on in HubSpot (`ON` in the `--workflows` report; 31 on
     27 Nov).
  4. Websites: Rikin switches the sites to the CRM (`docs/website-crm-switch.md`); re-run
     `--object-records cta_submission --links cta_submission-contact` for the last HubSpot
     enquiries.
- [ ] Rotate the HubSpot token and secret.

### Production run, with staging timings (27 Nov 2026)

One step at a time, each: dry run → read the report → backup → `--apply`. Backups of the staging
database took ~3 minutes (1.1 GB gzipped). Times are the staging runs (reading HubSpot dominates).

| Step                                                  | Command                                                              | Time                                      |
| ----------------------------------------------------- | -------------------------------------------------------------------- | ----------------------------------------- |
| Objects (manifests)                                   | `--manifest …events.json` (leads, tickets, cta-submissions)          | < 1 min each                              |
| Fields, labels                                        | `--hubspot --objects contact,company,deal,cta_submission,event,lead` | ~3 min                                    |
| Dropdown values                                       | `--hubspot-dropdown-values`                                          | ~2 min                                    |
| Users, teams, template owners                         | `--users plan.json`, `--teams`, `templates:import`                   | minutes                                   |
| Companies, contacts, deals                            | `--standard company,contact,deal`                                    | ~6 min                                    |
| Leads, events, CTA submissions                        | `--object-records lead,event,cta_submission`                         | ~1 min                                    |
| Links                                                 | `--links all`                                                        | ~7 min                                    |
| Activities                                            | `--activities all`                                                   | ~15 min                                   |
| Lists                                                 | `--lists`                                                            | minutes                                   |
| Sequences, subscriptions, goals, booking pages, forms | one each                                                             | minutes                                   |
| Field history                                         | `--property-history all`                                             | ~12 min read + writing ~8M rows (longest) |
| Workflows (last)                                      | `--workflows`                                                        | ~1 min                                    |

Run long ones with `nohup` (section 1) so a dropped connection doesn't stop them; read the log
for `== done`. Expect the first full production load to take an afternoon.

## 4. Decisions

| Date   | Decision                                                                                                                                                                                                                 | By      |
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- |
| 25 Nov | Only the 11 users above; roles: Super Admin, All Access (see/edit/delete all), Sales Enterprise and Sales AE (own records). Former owners kept as owners.                                                                | Shubham |
| 25 Nov | No login invites until go-live; users must not get emails from staging.                                                                                                                                                  | Shubham |
| 25 Nov | Calls: logging only for go-live (no Twilio). HubSpot calls migrate as logs, no recordings.                                                                                                                               | Shubham |
| 25 Nov | Skip the 120 empty deals from the error CSV import (keep a backup file of them).                                                                                                                                         | Shubham |
| 25 Nov | Bring everything from HubSpot; never trade completeness for speed.                                                                                                                                                       | Sarthak |
| 25 Nov | Pipelines exactly as HubSpot: Need Contact closed lost, task pipeline loaded, test pipeline deleted.                                                                                                                     | Sarthak |
| 26 Nov | A contact can have several open leads (several products or interests). Migrated leads keep them.                                                                                                                         | Shubham |
| 26 Nov | Link labels: HubSpot's label on an X→Y link names Y, so a label's `name` takes HubSpot's a→b text. HubSpot's own types keep a `hubspot:` id prefix.                                                                      | Tech    |
| 26 Nov | HubSpot's "Primary" and "… with Primary …" types are the link's primary flag, not labels.                                                                                                                                | Tech    |
| 26 Nov | Skip the 3,392 activities HubSpot links to no record (the CRM shows activities only on records); keep a backup file of them.                                                                                             | Shubham |
| 26 Nov | Built-in dropdowns store HubSpot's exact internal values; labels stay as the business named them.                                                                                                                        | Shubham |
| 26 Nov | `activities.body` is MEDIUMTEXT (16 MB): TEXT cut 8,424 long emails at 64 KB without an error (MySQL without strict mode).                                                                                               | Tech    |
| 27 Nov | HubSpot's inbox conversations (1,569 threads, 2–27 Nov) are not migrated: they are Shubham's own mailbox connected as a test (1,449 of 1,632 messages to him) plus channel tests; a person's mailbox stays private here. | Sarthak |
| 27 Nov | On a re-run, fields the CRM works out itself (calculated fields, calculations, rollups) keep the CRM's value; new records take HubSpot's.                                                                                | Tech    |

## 5. Known differences from HubSpot

- **Link dates.** HubSpot's API doesn't give when a link was made, so links show the migration
  date ("linked by import").
- **Primary company.** A contact or deal with companies always has a primary one here. If HubSpot
  marks none, the first company linked becomes primary.
- **Lead primary contact.** Contact links have no primary flag here; HubSpot's primary contact
  is the lead's main contact.
- **Meetings without an end time** (7 on staging) end 1 minute after they start: the CRM needs
  an end.
- **Activity attachments HubSpot no longer has** (9 on staging, HubSpot answers 404) are not
  copied; the activity is.
- **123 links not made:** 84 contact→deal and 39 company→deal links (and 5 event→deal) point to the
  skipped empty deals.

## 6. Staging results (25–26 Nov 2026)

| What                                   | Loaded                           |
| -------------------------------------- | -------------------------------- |
| Users                                  | 11 (+ 58 owner links, 0 invites) |
| Teams                                  | 1 (Enterprise Sales, 6)          |
| Templates with HubSpot owners          | 81 of 319                        |
| Companies                              | 14,719                           |
| Contacts                               | 54,935                           |
| Deals                                  | 1,710 (120 empty skipped)        |
| Deal stage history                     | 2,285 rows                       |
| Leads                                  | 703 (906 stage history rows)     |
| Events                                 | 209                              |
| Association labels matched             | 12                               |
| Contact ↔ company links                | 61,939                           |
| Company ↔ company links                | 172                              |
| Contact ↔ deal links                   | 916                              |
| Company ↔ deal links                   | 1,543                            |
| Deal ↔ deal links                      | 7                                |
| Lead links (contact / company / deal)  | 700 / 698 / 3                    |
| Event links (contact / company / deal) | 7,815 / 1,280 / 296              |
| Emails                                 | 96,258 (1,707 on no record)      |
| Notes                                  | 19,250 (864 on no record)        |
| Tasks                                  | 14,111 (514 on no record)        |
| Meetings                               | 4,779 (33 on no record)          |
| LinkedIn / SMS / WhatsApp messages     | 2,100 (195 on no record)         |
| Calls (logs)                           | 1,929 (79 on no record)          |
| Activity attachments                   | 7,337 (9 gone from HubSpot)      |

27 Nov 2026 re-run (HubSpot changed since 25 Nov): 47 contacts, 24 companies created; 570
contacts, 59 companies, 33 deals updated; 53 links (48 contact ↔ company, 5 CTA → contact);
267 activities (188 emails, 53 notes, 15 meetings, 9 tasks, 2 messages); CTA Submissions 200;
forms 10 + 10 submissions; workflows 57 (28 published, 29 drafts, all off; 3 on Events not
made); 118 new contact fields. Calculated fields kept the CRM's value (number of associated
deals on 6,780 contacts, times contacted 4,873, …).

Leftovers to settle before prod: 1 empty contact's lifecycle update (HubSpot 249780526215, a
Kenvue contact with no name or email: add a name in HubSpot or delete it), 16 companies with the old
lead status "IN_PROGRESS", 2 deals with KPI values not in the options.
