# Import bundle: WA Internal AI Agent 1.6.0 (Perfex) → Xpace Chat

Endpoint (core must implement): `POST /api/import/perfex`
Auth: header `Authorization: Bearer <bridge api key>` (the key stored in Xpace Chat `settings.crm.api_key`; the Perfex module holds the same key).
Body: one chunk. The importer sends several chunks; each is independent and repeat-safe.

```json
{
  "source": "perfex-bx_agents",
  "source_version": "1.6.0",
  "run_id": "2026-11-01T10:12:00+08:00-ab12",     // same for every chunk of one import run
  "chunk": 3, "chunks_total": 9,                   // informational
  "table": "contact",                              // which target table this chunk feeds (one table per chunk)
  "rows": [ { "...": "..." } ],                    // ≤ 500 rows, shape per table below
  "options": { "...": "..." }                      // only on the table "setting" / "brain" chunks (singletons)
}
```

Response: `{ "ok": true, "table": "contact", "inserted": n, "updated": n, "skipped": n, "errors": [{"source_id": "...", "message": "..."}] }`

Idempotency: every row carries `src_table` and `src_id`. Core keeps a small map `import_map(src_table, src_id) → new id` (add this table in core: `CREATE TABLE import_map (src_table TEXT, src_id TEXT, new_id INTEGER, PRIMARY KEY (src_table, src_id))`). A row seen before is UPDATED (not duplicated). Rows reference other imported rows by their *source* ids (`crm_lead_id`, `src_draft_id`, …); core resolves them through `import_map`, and falls back to matching by `phone_canon` for contacts.

Chunk order (the importer sends in this order so references resolve): `staff` → `channel_account` → `brain` → `setting` → `contact` → `room` → `message` → `message_template` → `draft` → `send_log` → `followup` → `schedule` → `bulk` → `bulk_recipient` → `ignore_contact` → `audit`.

---

## staff  (from `tblstaff` + `xw_settings.staff[<staffid>]` + bx_agents capabilities)

| field | from |
|---|---|
| src_table / src_id | `"tblstaff"` / staffid |
| name | firstname + " " + lastname |
| email | email |
| phone | phonenumber (digits only) |
| role | `admin` if tblstaff.admin=1; `manager` if staff holds bx_agents `view` or `approve_whatsapp`; else `salesperson` |
| rights | mapped: `view`→`view_all`, `wa_view_own`→`view_own`, `approve_whatsapp`→`approve_drafts`, `approve_campaign`→`approve_campaign`, `create_campaign`→`create_campaign`, `schedule_send`→`schedule_send`, `manage_followups`→`manage_followups`, `manage_autoreply`→`manage_autoreply`, `settings`→`settings`; admins get all |
| lang | tblstaff.default_language: `malay`→`ms`, `chinese`→`zh`, else `en` |
| crm_staff_id | staffid |
| on_leave_until, cover_staff_id (src staff id), gets_leads (in_pool), areas, tone_set | `xw_settings.staff[staffid]` profile; defaults when absent |
| active | tblstaff.active |

Only staff who are admins, hold any bx_agents right, or appear in `xw_settings.staff` / numbers are sent.

## channel_account  (from `xw_settings.numbers`, keyed by number_id; plus one `meta_cloud` row when Meta was connected)

| field | from |
|---|---|
| src_table / src_id | `"xw_number"` / number_id (string) |
| kind | `meta_cloud` if number.provider = `meta` and phone_number_id ≠ "", else `whatsapp_link` (the salesperson re-scans a QR; nothing else changes) |
| label, phone | label, phone |
| owner_kind | kind (`company` / `own`) |
| staff_id | responsible_staff_id (src staff id, 0 → null) |
| approvers | approver_ids (src staff ids) |
| state | `waiting` (every account must be re-linked or re-checked after import) |
| own_agreed_by / own_agreed_at | as stored (ISO) |
| meta | `{ "phone_number_id": ..., "legacy_number_id": "<number_id>" }` |

## brain  (singleton; chunk has `rows: []` and `options`)

`options` = `xw_ai_brain` JSON mapped 1:1: `enabled, engine (main→"anthropic" with api_key "" and a todo "re-enter key"), model, business_name, facts, chats, quick_replies, handover_topics[], never_promise, extra_rules, reply_max_chars, history_messages, max_tokens, budget_rm ← monthly_budget_rm, rate_in ← rate_in_rm, rate_out ← rate_out_rm, api_key ← decrypted xw_ai_brain_key when decryptable else ""` plus `usage` = `xw_ai_usage` JSON `{month, calls, fails, tokens_in, tokens_out, est_rm}` (core upserts `ai_usage`).

## setting  (singleton; `options` = mapped `xw_settings` + a few bx_agents options)

| Xpace Chat setting | from `xw_settings` |
|---|---|
| live | live_sending |
| automation_level | `approval`→`approve_then_send`, `auto_safe`→`auto_safe` |
| assignment_rule | `round_robin`→`round_robin`, `by_area`→`by_area`, `combined`→`area_then_round_robin` |
| no_area_match | area_fallback |
| default_source, sources | same |
| optout_words, optin_words, block_list | same |
| own_keep_days | private_keep_days |
| quiet_start, quiet_end | followup_quiet_start / _end |
| monthly_cap_rm, cap_warn_pct | monthly_cap, spend_warn_pct |
| rates | `{marketing, utility, service: 0}` from rates |
| bulk_allowed, bulk_batch, bulk_gap_min, bulk_cooldown_days | campaign_enabled, campaign_batch, campaign_gap_minutes, campaign_min_days_between |
| followups_enabled, followup_max_per_stage | followup_enabled, followup_max |
| schedule_allowed, schedule_max_days | schedule_enabled, schedule_max_days |
| autoreply_enabled, autoreply_min_accuracy, autoreply_min_count, autoreply_footer, autoreply[] | autoreply_enabled && !autoreply_killed, autoreply_min_accuracy, autoreply_min_samples, autoreply_escalation, autoreply_rules (intent → keywords/answer; sent/wrong from `xw_auto_rule` rows `autoreply:<intent>` data when present) |
| pause_all | bx_agents_wa_automation_paused |
| company_name | Perfex option `companyname` |
| legacy | `{ "flood_limit_hour", "inbound_routing", "inbound_staff_id", "known_customer_approver", "templates": [pointers], "followup_steps", "followup_stage_days", "campaign_approver_ids", "meta_conn": {... without secrets}, "meta_token_present": bool }` — core stores under setting key `legacy_160` for reference; Meta access token is sent under `options.meta.access_token` only when decryptable (core stores it in its own encrypted setting), else `options.meta.needs_reenter = true` |

## contact  (from `tblleads` that appear in xw_* tables, plus `xw_consent` / `xw_optout` / `tblclients` via `xw_lead_link`)

| field | from |
|---|---|
| src_table / src_id | `"tblleads"` / lead id |
| kind | `customer` |
| name | tblleads.name |
| phone_canon | tblleads.phonenumber canonical (Malaysian: strip non-digits, `0…`→`60…`, `+`) |
| phone_hash | sha256(xw_hash_salt + phone_canon) when salt exists, else "" |
| company, area, source, stage | tblleads.company, city, source name (tblleads_sources.name), status name (tblleads_status.name) lower-cased into `enquiry|quotation|measurement|design|install|handover|closed|lost|<other>` by a simple word match, else `other` |
| consent_offers | xw_consent.agreed |
| optout_at | xw_optout.updated_at when opted_out=1 |
| blocked | 1 if phone in xw_settings.block_list |
| crm_lead_id | lead id |
| crm_customer_id | xw_lead_link.customer_id |
| salesperson_id | tblleads.assigned (src staff id) |
| notes | tblleads.description (first 2000 chars) |
| last_in_at / last_out_at | max(xw_msg.created_at) by direction for that phone |
| last_bulk_at | max(xw_campaign_recipient.sent_at) for that phone |

Phones that appear in xw_msg / xw_send_log with no lead row are sent as contacts with `src_table: "xw_phone"`, `src_id: <phone_canon>`, `name: xw_msg.contact_name or ""`.

## room  (one `customer` room per contact that has any message, draft or send_log)

| field | from |
|---|---|
| src_table / src_id | `"xw_room"` / `"lead:<lead id>"` or `"phone:<phone_canon>"` |
| kind | `customer` |
| title | contact name or phone |
| contact_src | `{src_table, src_id}` of the contact |
| channel_account_src | `"xw_number"` / number_id of the most recent xw_msg for that phone (null if none) |
| taken_over_by | xw_chat.taken_by (src staff id) |
| last_at | max message time |

## message  (from `xw_msg` + `xw_send_log` rows with status sent/would_send)

| field | from xw_msg | from xw_send_log |
|---|---|---|
| src_table / src_id | `"xw_msg"` / id | `"xw_send_log"` / id |
| room_src | the contact's room (by lead id, else phone) | same |
| channel_account_src | number_id | number_id |
| dir | direction (`in`/`out`) | `out` |
| from_contact_src / from_staff_src | in: contact; out: staff_id | decided_by of the draft when known, else null |
| via | `phone` when direction=out and staff_id>0 (phone echo), else `crm` | tag = `campaign` → `bulk`; tag = `followup` → `followup`; else `crm` |
| text | body | body |
| msg_type, media | msg_type; media null (1.6.0 stored "[image] caption" text only) | `text` |
| private, staff_only_id | private, staff_id | 0, null |
| provider_msg_id | provider_msg_id | provider_message_id or null |
| at | created_at (server local → ISO UTC using Perfex timezone) | created_at |

Rows with `created_lead`/`user_id`/`username` are kept as text only.

## message_template  (from `xw_message`, not archived)

| field | from |
|---|---|
| src_table / src_id | `"xw_message"` / id |
| name, body | name, body |
| kind | `free`→`plain`, `template`→`template` |
| meta_name | template_name |
| category | from `xw_settings.templates` pointer with the same name, else `utility` |
| language | pointer language, else `en` |
| status | draft→`draft`, pending→`sent_to_meta`, approved→`approved`, rejected→`rejected` |
| created_by | src staff id |

## draft  (from `xw_draft`)

| field | from |
|---|---|
| src_table / src_id | `"xw_draft"` / id |
| room_src, to_contact_src | by lead_id (recipient_type `lead`) or by phone; staff recipients (`recipient_type: staff`) are skipped and counted |
| channel_account_src | number_id |
| text / original_text | final_text (or original_text when final empty) / original_text |
| intent, drafter, note | intent, drafter (`mock`→`mock`, `ai`, `ai_check`, `ai_failed`, `ai_budget`, `followup`, else `human`), ai_note |
| status | pending→`pending`, approved→`approved`, sent→`sent`, would_send→`would_send`, rejected→`rejected`, scheduled→`scheduled`, cancelled→`cancelled`, blocked→`blocked`, other→`rejected` |
| template_name | template_hint |
| scheduled_at | wanted_send_at |
| created_by, decided_by, decided_at, reason | created_by, decided_by, decided_at, reject_reason |
| params | params_json → `params` (array) |

## send_log  (from `xw_send_log`)

`src_table "xw_send_log"`, `src_id id`, `draft_src id`, `bulk_src` = campaign id when tag=`campaign:<id>` (1.6.0 writes tag `campaign` plus recipient.log_id; importer resolves via `xw_campaign_recipient.log_id`), `channel_account_src number_id`, `to_phone`, `body`, `mode` (`dry_run`→`dryrun`, `live`), `status`, `category`, `est_cost`, `would_cost`, `provider_msg_id`, `at`.

## followup  (from `xw_followup.data` json per lead: `{count, last_at, state, stop_reason, pending_draft, series, base_at}`)

One row per lead: `src_table "xw_followup"`, `src_id lead_id`, `contact_src`, `step = count + 1`, `due_at = null` (core recomputes from rules), `draft_src = pending_draft` when > 0, `state = active→due (or prepared when pending_draft>0), stopped→stopped, done→sent`, `legacy = data`.

## schedule  (from `xw_schedule`, state scheduled/claimed only)

`src_table "xw_schedule"`, `src_id id`, `draft_src draft_id`, `run_at send_at`, `template`, `text final_text`, `approver_src approver_id`, `state scheduled`.

## bulk  (from `xw_campaign`)

| field | from |
|---|---|
| src_table / src_id | `"xw_campaign"` / id |
| name, filters | name, filters json (stage/source/area/project keys passed through as `{stages:[], sources:[], areas:[], project: ""}`) |
| template_src | message_id |
| route | `auto` |
| when_json | send_at ? `{mode:"at", at}` : `{mode:"on_approval"}` |
| state | draft, pending_approval, approved, sending, paused (paused=1), done, cancelled, rejected |
| prepared_by, approved_by | created_by, approved_by (src staff ids) |
| est_cost | est_cost |
| counts | `{people: people_count, skipped: skipped_count}` |

## bulk_recipient  (from `xw_campaign_recipient`)

`bulk_src campaign_id`, `contact_src` by lead_id else phone, `name`, `state` (queued/sent/skipped/failed), `skip_reason reason`, `send_log_src log_id`, `sent_at`.

## ignore_contact  (from `xw_ignore`)

`phone_hash`, `channel_account_src number_id`. (Hashes stay hashes: the salt `xw_hash_salt` is sent once in the `setting` chunk as `options.hash_salt` so new hashes match old ones.)

## audit  (from `bx_proposal` rows with channel = whatsapp, last 2000)

`src_table "bx_proposal"`, `src_id id`, `action "legacy_proposal"`, `ref "lead:<lead_id>"`, `after {type, source, status, proposed_by, approved_by, final_text, result, audit_line, template_name, dry_run}`, `at created_at`. Informational only.

## Not imported (by design)

`xw_example` (salesperson corrections; core re-learns), `bx_agent_runs/_rules/_tenants/_usage/_events` (back-office agents stay in bx_agents), encrypted Meta app secret / verify token / provider install key (re-entered on Connect page; the importer only flags `needs_reenter`).
