> ## Documentation Index
> Fetch the complete documentation index at: https://docs.unibee.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Data migration guide

This guide mirrors the onboarding style used in the other UniBee business-integration docs. We start with a quick orientation, then walk through import and export scenarios with actionable steps, field guidance, and links to deeper references.

***

## 1. Quick orientation

| Question                       | Answer                                                                                        |
| ------------------------------ | --------------------------------------------------------------------------------------------- |
| **Who is this for?**           | Merchants who need to migrate data into UniBee or export existing information for BI/finance. |
| **What objects can I import?** | Users, Plans, Active Subscriptions, and Subscription History.                                 |
| **What can I export?**         | Any major dataset (users, plans, subscriptions, invoices, credits, reports) via UI or API.    |
| **How do I test safely?**      | Use your Sandbox org first, verify results, then repeat in Production.                        |

> ✅ **Tip:** Download the latest template right before filling it out. Templates change as UniBee evolves—using an old file is the #1 cause of import errors.

***

## 2. First things first

1. **Download UniBee’s Excel templates** – In UniBee Admin Portal, open any data list with a `⋯ → Import` button (for example, `User Management → User List`). Click **Download template** to grab the latest Excel file. All imports use these `.xlsx` templates; they already include required columns and guidance.
2. **Minimal viable import** – For teams that just need to bring existing customers online quickly:
   * Create the plans you need (manually in **Product & Plan** or via the Plan APIs).
   * Configure your payment gateways in UniBee (Settings → Payments).
   * Import **Active Subscriptions**. The import job auto-creates any missing users, so once the subscriptions are in place, the system is ready for use.
3. **When you need more control** – Move on to importing users and plans explicitly (details below) before adding subscriptions. This is helpful when you need precise external IDs, custom metadata, or audit requirements.
4. **Backup & permissions** – Make sure you can see the `⋯ → Import` menu (Billing Admin or higher) and export the existing dataset before importing to preserve a rollback point.

***

## 3. Import playbook

### 3.1 Templates & entry points

| Task name                   | Portal entry                                                           | Template                                                                                |
| --------------------------- | ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| `UserImport`                | **User Management → User List → ⋯ → Import**                           | [Download template](https://api.unibee.dev/import/template/user_import)                 |
| `ActiveSubscriptionImport`  | **Subscription → Subscription List → ⋯ → Import active subscription**  | [Download template](https://api.unibee.dev/import/template/active_subscription_import)  |
| `HistorySubscriptionImport` | **Subscription → Subscription List → ⋯ → Import subscription history** | [Download template](https://api.unibee.dev/import/template/history_subscription_import) |

> Plan imports currently have **no UI**. If you need to bulk-create plans, call the Plan APIs directly (for example, `POST /merchant/plan/create`). Imported plans land in `Edit` status, so you can review them before activating.

All templates are Excel files (≤ 20 MB). Use UTF‑8 when exporting CSV versions to avoid encoding issues.

### 3.1 User import

| Field                    | Required      | Description & tips                                                                           |
| ------------------------ | ------------- | -------------------------------------------------------------------------------------------- |
| `Email`                  | ✅             | Primary identifier. Must be unique per merchant.                                             |
| `ExternalUserId`         | ➖ Recommended | Keep your legacy system’s user ID here for reconciliation and future sync jobs.              |
| `FirstName` / `LastName` | ➖             | Display name shown in UniBee UI and exports.                                                 |
| `Address`, `Phone`       | ➖             | Optional profile fields; populate them if you want support teams to see legacy contact info. |

* **After import**: Users are created in `ACTIVE` status. Existing users can only be overwritten if they were previously imported by the same admin (UniBee tags each record with `ImportBy<memberId>` to enforce this). No webhook fires; check Activity Logs for `ImportNew` / `ImportOverride`.

### 3.2 Plan import (API workflow)

* **How it works**: There is no “Import plan” button in the UI today. Use the Plan APIs (`/merchant/plan/create`, `/merchant/plan/edit`, etc.) to bulk-create plans based on the Excel template. For example:

```bash theme={null}
curl --location --request POST "https://api.unibee.dev/merchant/plan/create" \
  --header "Authorization: Bearer $UNIBEE_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{
    "productId": 123,
    "planName": "Pro Plan",
    "internalName": "pro_plan_internal",
    "externalPlanId": "legacy-plan-001",
    "amount": 9900,
    "currency": "USD",
    "intervalUnit": "month",
    "intervalCount": 1
  }'
```

* **Key fields**: `ExternalPlanId`, `PlanName`, `InternalName`, `ProductName`, `PlanType`, `PlanAmount`, `Currency`, `IntervalUnit`, `IntervalCount`, plus optional `Metadata` and trial settings.
* **After import**: Plans stay in **Edit** status until you review and activate them. This lets you double-check pricing and descriptions before customers see them. Duplicates update descriptive/trial fields. No webhook fires; audit via Activity Logs.

### 3.3 Active subscription import

This is the heavy-lifter for migrations—you import a user’s ongoing subscription along with gateway/payment info.

#### UI workflow

1. Go to **Subscription → Subscription List**.
2. Click the `Import` button in the top-right corner and choose **Import active subscription**.
3. Download the Excel template if needed, fill in the rows, upload the file, and monitor the task in the Task Drawer.

#### API workflow

You can also call the API directly to import a single subscription:

```bash theme={null}
curl --location --request POST "https://api.unibee.dev/merchant/subscription/active_subscription_import" \
  --header "Authorization: Bearer $UNIBEE_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{
    "externalSubscriptionId": "legacy-sub-1001",
    "planId": 456,
    "email": "user@example.com",
    "gateway": "stripe",
    "stripeUserId": "cus_123",
    "stripePaymentMethod": "pm_123",
    "currentPeriodStart": "2024-07-01 00:00:00",
    "currentPeriodEnd": "2024-08-01 00:00:00",
    "billingCycleAnchor": "2024-07-01 00:00:00",
    "firstPaidTime": "2024-06-15 00:00:00",
    "createTime": "2024-06-01 00:00:00"
  }'
```

| Field                                               | Required     | Description & tips                                                                                  |
| --------------------------------------------------- | ------------ | --------------------------------------------------------------------------------------------------- |
| `ExternalSubscriptionId`                            | ✅            | External identifier from your legacy system; needed for overrides and debugging.                    |
| `Email` / `ExternalUserId`                          | ✅ (pick one) | Used to locate or auto-create the user. Provide both when possible so you’re safe if emails change. |
| `PlanId` / `ExternalPlanId`                         | ✅ (pick one) | Must reference an existing UniBee plan. When using `ExternalPlanId`, ensure it already exists.      |
| `Gateway`                                           | ✅            | e.g., `stripe`, `paypal`, `wire_transfer`. The gateway must be configured in UniBee.                |
| `GatewayPaymentType`                                | ➖            | Required for gateways that expose sub-types (e.g., Payssion).                                       |
| `StripeUserId` + `StripePaymentMethod`              | ➖            | Needed to keep Stripe auto-charge working.                                                          |
| `PaypalVaultId` or `PaypalAgreementToken`           | ➖            | Needed to keep PayPal auto-charge working.                                                          |
| `Quantity`                                          | ➖            | Defaults to 1; useful for seat-based subscriptions.                                                 |
| `CountryCode`, `VatNumber`, `TaxPercentage`         | ➖            | Recommended for VAT/GST compliance.                                                                 |
| `CurrentPeriodStart` / `CurrentPeriodEnd`           | ✅            | UTC timestamps; `End` must be greater than “now”.                                                   |
| `BillingCycleAnchor`, `FirstPaidTime`, `CreateTime` | ✅            | Control proration, reporting, and the next renewal.                                                 |
| `Features`                                          | ➖            | JSON column for custom features/metadata.                                                           |

* **After import**:
  * Subscription status = `Active`, type = `UniBeeControl`.
  * UniBee issues a zero-amount “catch-up” invoice so reports stay consistent.
  * User defaults (country, gateway, payment method) update.
  * Webhooks fire:
    * `subscription.import.created` (new record)
    * `subscription.import.override` (overwriting an existing import by the same admin)
    * Downstream events triggered by the zero invoice, such as `invoice.paid` and `user.metric.update`, so your billing system sees a consistent timeline.
  * Overrides are only allowed when the original subscription was imported by the same admin (metadata guard).

### 3.4 Subscription history import

Use this to backfill past billing cycles (for example, when you want N months of historical revenue in UniBee).

#### UI workflow

1. Go to **Subscription → Subscription List**.
2. Click the `Import` button and select **Import subscription history**.
3. Download the template, fill it out, upload, and track the background task just like other imports.

#### API workflow

Alternatively, import a single record via API:

```bash theme={null}
curl --location --request POST "https://api.unibee.dev/merchant/subscription/history_subscription_import" \
  --header "Authorization: Bearer $UNIBEE_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{
    "externalSubscriptionId": "legacy-sub-1001",
    "planId": 456,
    "email": "user@example.com",
    "gateway": "stripe",
    "currentPeriodStart": "2024-05-01 00:00:00",
    "currentPeriodEnd": "2024-06-01 00:00:00",
    "totalAmount": 9900
  }'
```

| Field                                      | Required     | Description & tips                                              |
| ------------------------------------------ | ------------ | --------------------------------------------------------------- |
| `ExternalSubscriptionId`                   | ✅            | Use the same ID as the active subscription so history lines up. |
| `PlanId` / `ExternalPlanId`                | ✅            | Points to the plan used during that billing period.             |
| `Email` / `ExternalUserId`                 | ✅ (pick one) | Same behavior as active import.                                 |
| `Gateway`                                  | ✅            | Stored for auditing; UniBee does not charge anything here.      |
| `CurrentPeriodStart`, `CurrentPeriodEnd`   | ✅            | Both must be in the past and `End > Start`.                     |
| `TotalAmount`                              | ✅            | Period amount in cents.                                         |
| `Quantity`, `CountryCode`, `TaxPercentage` | ➖            | Optional context for analytics.                                 |

* **After import**:
  * UniBee creates an `Expired` subscription record plus a timeline slice for reporting.
  * It does **not** create a live subscription or trigger billing—it is purely historical.
  * Duplicate rows are rejected unless they belong to the same admin import.
  * No webhook fires; rely on Activity Logs.

### 3.5 Import flow (same for every task)

1. Download the template → fill one row per record.
2. Upload the file via the modal. UniBee immediately enqueues a background job.
3. Monitor progress in the Task Drawer (`Queued → Running → Succeeded/Failed`).
4. Download the annotated result file and check the `ImportResult` column.
5. Fix failed rows only, then re-upload.

***

## 4. Export playbook

### 4.1 Exports from list pages

Every major list has `⋯ → Export`. Apply filters first (date range, plan, status) and UniBee will export just that slice.

* **Users**: `userId`, `externalUserId`, `email`, `status`, `countryCode`, `defaultGatewayId`, timestamps.
* **Plans**: `planId`, `externalPlanId`, `planName`, `planType`, `amount`, `currency`, `interval`, trial info.
* **Subscriptions**: `subscriptionId`, `externalSubscriptionId`, `planName`, `status`, `gateway`, `amount`, `currency`, `currentPeriodStart/End`, `userId`.
* **Transactions / Invoices**: invoice/payment IDs, statuses, `totalAmount`, `taxAmount`, `currency`, `paymentMethod`, `gateway`, timestamps.

Exports run as background tasks; download them from the Task Drawer when they turn green.

### 4.2 Reports & Export Reports center

For standardized report packs (subscription inventory, invoice ledger, credit balance history, etc.), go to **Reports & Export Reports**. These jobs use a fixed schema suitable for finance/compliance and can be rerun for any historical period.

### 4.3 API-driven exports

Need automation? Use two endpoints:

1. `POST /merchant/task/new_export` with task name (e.g., `UserExport`, `SubscriptionExport`, `InvoiceExport`, `CreditTransactionExport`, `PlanExport`, `DiscountExport`, `UserDiscountExport`, `MultiUserDiscountExport`). Include:
   * `payload`: filters (date range, plan IDs, statuses, etc.).
   * `exportColumns` (optional): specify exact columns.
   * `format`: `xlsx` (default) or `csv`.
2. `GET /merchant/task/list` to poll for status and retrieve `downloadUrl`.

Need a field dictionary? Call `/merchant/task/export_column_list` with the task name to get every column key plus human-readable descriptions.

***

## 5. Validation & go-live checklist

1. **Spot-check** – Open a few imported users/plans/subscriptions in the UI to confirm values (amounts, cycles, payment method, etc.).
2. **Billing smoke test** – For active subscriptions, trigger a manual invoice or wait for the next renewal to ensure auto-charge succeeds with the imported payment token.
3. **Audit trail** – `Admin Management → Activity Logs` shows `ImportNew`, `ImportOverride`, and export events. Download logs if you need compliance evidence.
4. **Communicate** – Share final task IDs and validation notes with finance/support so everyone knows when UniBee becomes the source of truth.

***

## 6. Troubleshooting & support

* **Upload rejected immediately** → Most likely an outdated template or renamed columns. Download a fresh copy and reapply your data.
* **“Task not found”** → Check spelling/casing of the `task` parameter (e.g., `ActiveSubscriptionImport`).
* **Gateway errors** → Ensure Stripe/PayPal gateways are configured in UniBee; imports validate tokens against your credentials.
* **Task stuck in “Running”** → Large files can take several minutes. If still running after \~30 minutes, download the task log or contact UniBee Support with the task ID.
* **Encoding issues** → Save CSV files in UTF‑8, especially if your data includes non-English characters.

Need help? Contact UniBee Support or your onboarding manager with the task ID, template, and a couple of sample rows for faster diagnosis.

***

## 7. Related resources

* [User import/export walkthrough](/documentation/user-management/export-import-user-data)
* [Subscription import API reference](/api-reference/subscription-import/active-subscription-importallows-repetition-imports)
* [Reporting overview](/documentation/reports-and-export-reports/reports-and-export-reports)
