# Ordering a Service

## Overview

This journey covers the complete order lifecycle -- from configuring a service and proceeding through checkout, to order submission, fulfillment, and real-time status tracking. This is one of the most critical flows in the portal. An order starts in the portal, creates records in Salesforce (Order, Opportunity), and ultimately provisions a service in WHMCS. All orders require manual approval by support agents in Salesforce -- there is no automatic provisioning. Agents verify the customer's identity, double-check the information, and for internet orders, coordinate with NTT for availability and installation.

## Portal Flow

### Configuring a Service

Before reaching checkout, the user must configure their chosen service. Each service type has its own multi-step configuration wizard.

#### Internet Configuration

1. From the internet plans page, click a plan tier (Standard, Pro, or Platinum) within an offering card to start configuration at `/account/services/internet/configure`.
2. **Step 1 -- Service Configuration**: Review your selected plan details. Choose a connection access mode (IPoE with your own router, IPoE with a Home Gateway, or PPPoE). The Platinum tier shows an important notice about router requirements.
3. **Step 2 -- Installation**: Choose an installation option. Options vary by term length (one-time, 12-month, or 24-month contract) and affect whether the installation fee is spread monthly or paid upfront.
4. **Step 3 -- Add-ons**: Optionally select add-ons for your internet service. Some add-ons are bundled (included automatically with certain plans) and will be pre-selected.
5. **Step 4 -- Review Order**: See a full summary of your plan, installation option, add-ons, monthly total, and one-time total. Prices exclude 10% consumption tax. Click **Proceed to Checkout** to continue.

#### SIM / eSIM Configuration

1. From the SIM plans page, click **Select Plan** on a plan card. This navigates to `/account/services/sim/configure?planSku={sku}`.
2. **Step 1 -- Select SIM Type**: Choose between **eSIM** and **Physical SIM**. If you choose eSIM, you must enter your device's EID (a 32-digit identifier found in your phone's settings).
3. **Step 2 -- Activation**: Choose when to activate: **Immediate** (activate as soon as possible) or **Scheduled** (pick a future date). An activation fee is shown.
4. **Step 3 -- Add-ons**: Optionally select add-ons such as additional data or voice features.
5. **Step 4 -- Number Porting (MNP)**: Choose whether to port an existing phone number. If yes, provide the MNP reservation number, expiry date, carrier account number, and personal information (name, name in katakana, gender, date of birth) as required by the porting process.
6. **Step 5 -- Review Order**: See a full summary including plan, SIM type, EID (for eSIM), activation type, number porting status, add-ons, monthly total, and one-time total. An info box explains next steps (order review and ID verification within 1-2 business days). Click **Proceed to Checkout**.

#### VPN Router Configuration

1. From the VPN plans page, click a plan card for your chosen region (US or UK).
2. The configuration is simpler -- select the plan, optionally choose any add-ons or activation options, review, and proceed to checkout.

### Checkout

1. After clicking "Proceed to Checkout" from any configuration wizard, the portal builds a **checkout session**. This session stores the selected plan, add-ons, installation options, and all configuration details server-side.
2. If you are not logged in, you are redirected to the login page. Your cart data is preserved so you can continue after signing in.
3. The checkout page at `/account/order` (or `/account/checkout`) shows the title **"Checkout"** with the description "Verify your address, review totals, and submit your order."
4. For internet orders, the checkout page also checks your eligibility status. If eligibility has not been requested yet, or is pending/ineligible, a banner explains the situation and lets you request an eligibility check directly from the checkout page.

#### Checkout Requirements

The checkout page presents three requirements that must all be satisfied before you can submit:

**1. Service Address Confirmation**

- Your current address on file is displayed. You must confirm it is correct by clicking a confirmation button.
- If your address is incomplete or incorrect, you can update it before confirming.
- The address is used for service delivery (especially important for internet installation).

**2. Payment Method**

- The portal checks whether you have a payment method on file in WHMCS.
- If you do, your default payment method is shown (e.g., credit card ending in a given number).
- If you do not have a payment method, a button lets you open the WHMCS payment portal in a new tab to add one. After adding a card, click the refresh button on the checkout page to update the status.

**3. Identity Verification (Residence Card)**

- Japanese telecommunications regulations require identity verification.
- If you have already submitted a residence card image and it is verified or pending review, a status indicator shows this.
- If you have not submitted one, a file upload area lets you upload a photo of your residence card directly from the checkout page.
- Status values: "Not submitted", "Pending review", "Verified", or "Rejected" (with reviewer notes explaining why).

#### Order Summary and Submission

1. Below the requirements section, the **Review & Submit** section shows:
   - An estimated monthly total and one-time total.
   - A "What to expect" list: team review, possible contact for details, residence card verification before activation, charges only after approval, and confirmation by email.
2. The **Submit order** button is disabled until all three requirements are satisfied (address confirmed, payment method on file, residence card submitted).
3. Click **Submit order**. A loading state shows "Submitting..." while the order is being created.
4. If submission is successful, you are redirected to the order detail page with a success banner.
5. If submission fails (for example, due to a missing residence card or expired checkout session), an error message appears. If the failure is due to a missing residence card, you are redirected to the verification page to upload one.

### Order Confirmation and Tracking

1. After successful submission, you land on the order detail page at `/account/orders/{salesforceOrderId}?status=success`.
2. A green **"Order submitted"** banner appears at the top with these details:
   - "We've received your order and started the review process."
   - "We'll confirm everything within 1 business day."
   - "You'll get an email as soon as the order is approved."
   - "Installation scheduling happens right after approval."
3. The checkout cart is automatically cleared at this point.

#### Order Detail Page

The order detail page shows comprehensive information about your order:

- **Stats Cards**: Four cards across the top showing Order Status (with a colored status pill), Monthly cost, One-time cost, and Order Date.
- **Order Progress Timeline**: A visual step-by-step progress bar showing where the order stands. The steps vary by service type:
  - **Internet**: Submitted -> Under Review -> Scheduled -> Active
  - **SIM**: Submitted -> Processing -> Activating -> Active
  - **VPN**: Submitted -> Processing -> Active
- **Order Details Card**: Shows the service label (e.g., "Internet Service"), the full date the order was placed, and monthly/one-time pricing in large text. Below that, a list of order items with icons indicating their category (Service, Installation, Add-on, Activation) and their respective prices.
- **Next Steps**: A blue info box showing what happens next based on the current status (e.g., "We will contact you within 1 business day with next steps").
- **Installation Fee Notice**: If the order includes installation or activation items, a yellow warning box explains that standard installation is included but additional charges may apply for weekend scheduling or specialized equipment.

#### Real-Time Order Updates

- The order detail page establishes a **live connection** to the server (using Server-Sent Events). When the order status changes in Salesforce, the page automatically refreshes to show the updated status without requiring the user to reload.
- This means testers will see status changes reflected in near real-time as the backend team processes orders.

#### Order Statuses and Their Meaning

| Portal Status Label        | What It Means                                                                                    | Timeline Indicator                 |
| -------------------------- | ------------------------------------------------------------------------------------------------ | ---------------------------------- |
| **Under Review**           | The order has been submitted and the team is reviewing it.                                       | Highlighted on "Under Review" step |
| **Installation Scheduled** | For internet orders: an installation date has been set.                                          | Highlighted on "Scheduled" step    |
| **Setting Up Service**     | The backend is actively provisioning the service (creating WHMCS records, activating SIM, etc.). | Highlighted on "Activating" step   |
| **Service Active**         | The service is fully provisioned and active. The order is complete.                              | Green checkmarks on all steps      |
| **Processing**             | A general processing state for orders that do not match the above categories.                    | Highlighted on "Processing" step   |

### Orders List Page

1. Go to `/account/orders` to see all your orders.
2. The page shows summary statistics at the top: Total orders, Pending, Active, and Processing counts.
3. You can search orders by order number and filter by status (All, Pending, Active, Processing, Cancelled) and type (All, Internet, SIM, VPN).
4. Each order card in the list shows the order number, service type icon, status pill, items summary, and creation date. Click a card to go to its detail page.

## What Happens in Salesforce

### Order Creation

When the user clicks "Submit order," the BFF performs these steps in Salesforce:

1. **Validates the order**: Checks the user's account mapping (portal user ID to Salesforce Account ID), verifies the SKUs exist in the product catalog, and validates business rules (e.g., internet orders need at least one main service SKU, SIM orders must specify SIM type, eSIM orders must include an EID).

2. **Links to an Opportunity**: The system looks for an existing open Opportunity on the user's Account for this product type. If one exists (for example, from a previous eligibility check), the order is linked to it. If none exists, a new Opportunity is created. Either way, the Opportunity's stage is set to **"Post Processing"** (75% probability), meaning an order has been placed.

3. **Creates the Order**: A new **Order** record is created on the Account with:
   - `Status` = "Draft"
   - `Type` = the order type (Internet, SIM, VPN)
   - `OpportunityId` linking to the resolved Opportunity
   - `EffectiveDate` set to today
   - Configuration fields like `SIM_Type__c`, `Access_Mode__c`, `Activation_Type__c`, and MNP-related fields are populated from the checkout session.

4. **Creates Order Items**: For each SKU in the order, an **OrderItem** record is created, linked to the Order and the corresponding **Product2** and **PricebookEntry** records. Each item includes the unit price, quantity, and billing cycle.

5. **Notifies the support team**: A new internal Case is created in Salesforce (with Origin "Portal Notification") to alert the customer service team that a new order has been placed. This Case is for the support team only -- it does not appear in the customer's support cases list.

### Salesforce Order Fields to Check

After an order is submitted, go to the Account's related Orders list and open the new Order. Check these fields:

**Core Order Fields:**

| Field          | API Name            | Expected Value                                |
| -------------- | ------------------- | --------------------------------------------- |
| Status         | `Status`            | "Draft" immediately after submission          |
| Type           | `Type`              | "Internet", "SIM", or "VPN"                   |
| Opportunity    | `OpportunityId`     | Links to the associated Opportunity           |
| Effective Date | `EffectiveDate`     | Date the order was placed                     |
| Account        | `AccountId`         | The customer's SF Account                     |
| WHMCS Order ID | `WHMCS_Order_ID__c` | Populated after provisioning (links to WHMCS) |

**Activation Fields (updated during provisioning):**

| Field                    | API Name                        | Expected Value                                                             |
| ------------------------ | ------------------------------- | -------------------------------------------------------------------------- |
| Activation Type          | `Activation_Type__c`            | "Immediate" or "Scheduled"                                                 |
| Activation Status        | `Activation_Status__c`          | Progresses: empty → "Activating" → "Scheduled" → "Activated"               |
| Activation Scheduled At  | `Activation_Scheduled_At__c`    | Date/time if scheduled activation                                          |
| Activation Error Code    | `Activation_Error_Code__c`      | Empty if successful; error code if failed (e.g., "PAYMENT_METHOD_MISSING") |
| Activation Error Message | `Activation_Error_Message__c`   | Empty if successful; error details if failed                               |
| Activation Last Attempt  | `Activation_Last_Attempt_At__c` | Timestamp of the last provisioning attempt                                 |

**Internet-Specific Order Fields:**

| Field              | API Name                | Expected Value                      |
| ------------------ | ----------------------- | ----------------------------------- |
| Access Mode        | `Access_Mode__c`        | "IPoE-BYOR", "IPoE-HGW", or "PPPoE" |
| Internet Plan Tier | `Internet_Plan_Tier__c` | The selected plan tier              |
| Installment Plan   | `Installment_Plan__c`   | "Single", "12-Month", or "24-Month" |
| Weekend Install    | `Weekend_Install__c`    | true/false                          |
| Hikari Denwa       | `Hikari_Denwa__c`       | true/false (home phone add-on)      |

**SIM-Specific Order Fields:**

| Field                   | API Name                 | Expected Value                                                             |
| ----------------------- | ------------------------ | -------------------------------------------------------------------------- |
| SIM Type                | `SIM_Type__c`            | "eSIM" or "Physical SIM"                                                   |
| EID                     | `EID__c`                 | 32-digit device identifier (eSIM only)                                     |
| Voice Mail              | `SIM_Voice_Mail__c`      | true/false                                                                 |
| Call Waiting            | `SIM_Call_Waiting__c`    | true/false                                                                 |
| Physical SIM Assignment | `Assign_Physical_SIM__c` | Links to SIM_Inventory\_\_c record (Physical SIM only, populated by agent) |

**MNP (Number Porting) Fields (SIM orders with MNP only):**

| Field                         | API Name                        | Expected Value                     |
| ----------------------------- | ------------------------------- | ---------------------------------- |
| MNP Application               | `MNP_Application__c`            | MNP status                         |
| MNP Reservation Number        | `MNP_Reservation_Number__c`     | The porting reservation number     |
| MNP Expiry Date               | `MNP_Expiry_Date__c`            | Reservation expiry date            |
| MNP Phone Number              | `MNP_Phone_Number__c`           | The number being ported            |
| MVNO Account Number           | `MVNO_Account_Number__c`        | Customer's current carrier account |
| Porting Last Name             | `Porting_LastName__c`           | Porting person's last name         |
| Porting First Name            | `Porting_FirstName__c`          | Porting person's first name        |
| Porting Last Name (Katakana)  | `Porting_LastName_Katakana__c`  | Last name in katakana              |
| Porting First Name (Katakana) | `Porting_FirstName_Katakana__c` | First name in katakana             |
| Porting Gender                | `Porting_Gender__c`             | Gender                             |
| Porting Date of Birth         | `Porting_DateOfBirth__c`        | Date of birth                      |

**VPN-Specific Order Fields:**

| Field      | API Name        | Expected Value |
| ---------- | --------------- | -------------- |
| VPN Region | `VPN_Region__c` | "US" or "UK"   |

**Address Snapshot (captured at order time):**

| Field               | API Name             | Expected Value                              |
| ------------------- | -------------------- | ------------------------------------------- |
| Billing Street      | `BillingStreet`      | Customer's address at time of order         |
| Billing City        | `BillingCity`        | City                                        |
| Billing State       | `BillingState`       | Prefecture                                  |
| Billing Postal Code | `BillingPostalCode`  | Postal code                                 |
| Billing Country     | `BillingCountry`     | Country                                     |
| Address Changed     | `Address_Changed__c` | true if address was updated during checkout |

### Salesforce OrderItem Fields to Check

Each line item in the order (plan, installation, add-ons, activation fee) becomes an OrderItem. Check:

| Field            | API Name                          | Expected Value                                                      |
| ---------------- | --------------------------------- | ------------------------------------------------------------------- |
| Product          | `Product2Id` / `PricebookEntryId` | Links to the correct catalog product                                |
| Unit Price       | `UnitPrice`                       | Matches the price shown during checkout                             |
| Quantity         | `Quantity`                        | Usually 1                                                           |
| Billing Cycle    | `Billing_Cycle__c`                | "Monthly" or "One-time"                                             |
| WHMCS Service ID | `WHMCS_Service_ID__c`             | Populated after provisioning (links each item to its WHMCS service) |

### Salesforce Opportunity Fields to Check

After order placement, find the linked Opportunity on the Account:

| Field              | API Name                | Expected Value                                                                                                                                                            |
| ------------------ | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Stage              | `StageName`             | "Post Processing" after order submission                                                                                                                                  |
| Commodity Type     | `CommodityType__c`      | "Personal SonixNet Home Internet", "SIM", or "VPN"                                                                                                                        |
| Opportunity Source | `Opportunity_Source__c` | Contains "Portal" (e.g., "Portal - Internet Eligibility Request", "Portal - SIM Checkout Registration")                                                                   |
| WHMCS Service ID   | `WHMCS_Service_ID__c`   | Populated after provisioning -- this is the critical field that links the Opportunity to the WHMCS subscription for lifecycle tracking (plan changes, cancellation, etc.) |
| Close Date         | `CloseDate`             | Set during order creation                                                                                                                                                 |

**Opportunity Stage Lifecycle:**

| Stage           | Meaning                                              |
| --------------- | ---------------------------------------------------- |
| Introduction    | Initial interest (e.g., eligibility check requested) |
| Ready           | Customer is eligible and ready to order              |
| Post Processing | Order has been placed, being processed               |
| Active          | Service is live and active                           |
| △Cancelling     | Cancellation has been requested                      |
| 〇Cancelled     | Service has been cancelled                           |
| Void            | Lost or not eligible                                 |

## What Happens in WHMCS

### Order Fulfillment (Provisioning)

After the Salesforce Order is created, all orders require manual review and approval by the support team in Salesforce before provisioning begins. There is no automatic provisioning -- agents verify the customer's identity, check the submitted information, and approve the order.

1. **For Internet orders**: The support team reviews the order, verifies the address and eligibility, and coordinates with NTT for availability and installation scheduling. When ready, they change the order's `Activation_Status__c` to "Activating" or "Scheduled." This triggers the provisioning process. Internet orders take longer than SIM or VPN because support agents need to coordinate with NTT for availability and installation scheduling.

2. **For SIM orders (eSIM)**: After review and residence card verification, the order's activation status is set to "Activating." The provisioning system then:
   - Creates a **Product/Service** in WHMCS linked to the user's WHMCS Client record.
   - Creates an associated WHMCS **Order** for the service.
   - Activates the SIM through the mobile network provisioning system.

3. **For SIM orders (Physical SIM)**: The flow is similar, but the order waits in "Approved" status until a physical SIM card is assigned (`Assign_Physical_SIM__c` field is populated). Once assigned, the provisioning process creates the WHMCS records and activates the service.

4. **For VPN orders**: After review, the provisioning creates a WHMCS Product/Service and Order, and the router is shipped to the customer.

### WHMCS Records Created

- **Product/Service**: A new service record is created under the user's WHMCS Client. The product is determined by the `WH_Product_ID__c` field on the Salesforce Product2 record. The service status is set to Active once provisioning succeeds. The service also gets a custom field **OpportunityId** that stores the Salesforce Opportunity ID -- this is how WHMCS links back to Salesforce for lifecycle tracking.
- **Order**: A WHMCS Order record is created that groups the service and any add-on products. The WHMCS Order ID is written back to the Salesforce Order's `WHMCS_Order_ID__c` field.
- **Invoice**: WHMCS automatically generates an invoice for the new service based on its billing cycle and pricing.

### How WHMCS and Salesforce Stay Linked After Provisioning

After provisioning, the systems are linked bidirectionally:

| Direction              | Field                          | Location               | Value                                             |
| ---------------------- | ------------------------------ | ---------------------- | ------------------------------------------------- |
| SF Order → WHMCS       | `WHMCS_Order_ID__c`            | Salesforce Order       | The WHMCS Order ID                                |
| SF OrderItem → WHMCS   | `WHMCS_Service_ID__c`          | Salesforce OrderItem   | The WHMCS Service/Product ID for each line item   |
| SF Opportunity → WHMCS | `WHMCS_Service_ID__c`          | Salesforce Opportunity | The main WHMCS Service ID (used for cancellation) |
| WHMCS Service → SF     | **OpportunityId** custom field | WHMCS Product/Service  | The Salesforce Opportunity ID                     |

This bidirectional linking is what makes cancellation work: the portal looks up the Opportunity by the WHMCS Service ID and updates its stage.

### Where to Find Records in WHMCS

- Go to the **Client** record (search by email or client ID).
- Under **Products/Services**, look for the newly created service. It should match the plan name from the Salesforce order.
- Check the service's **Custom Fields** -- the **OpportunityId** field should contain the Salesforce Opportunity ID.
- Under **Orders**, find the order associated with the new service.
- Check that the billing cycle and pricing match what was shown during checkout.

## What Happens If Something Goes Wrong

### Payment Method Missing

If the user does not have a valid payment method in WHMCS at the time of provisioning, the order's `Activation_Error_Code__c` is set to "PAYMENT_METHOD_MISSING." The provisioning system will not retry until the error condition is resolved. The user needs to add a payment method through the portal's billing section, and the support team can then re-trigger provisioning.

### Provisioning Failure

If the WHMCS service creation or SIM activation fails, the order's `Activation_Error_Code__c` and `Activation_Error_Message__c` fields are populated with details about the failure. The support team can investigate and manually retry or resolve the issue.

### Order Validation Failure

If an order fails validation (e.g., invalid SKUs, missing required configuration), the submission fails at checkout time and the user sees an error message. No Salesforce Order is created.

### Checkout Session Expiry

Checkout sessions have an expiration time. If a user takes too long to complete checkout, the session expires and they will need to restart the configuration process.

## Key Things to Verify

### Order Placement

1. **End-to-end flow**: For each service type (Internet, SIM eSIM, SIM Physical, VPN), go through the full flow: browse plans, configure, checkout, submit. Verify the order is created successfully.
2. **Checkout requirements**: Verify the Submit button stays disabled until all three requirements are met (address confirmed, payment method on file, residence card submitted/pending).
3. **Address confirmation**: Test with a complete address and with an incomplete address. The incomplete case should prompt the user to update their address.
4. **Payment method check**: Test with a user who has a payment method and one who does not. The "no payment method" case should show instructions to add one.
5. **Residence card check**: Test with each status -- not submitted (shows upload), pending (shows waiting), verified (shows green check), rejected (shows message with reviewer notes).

### Salesforce Verification

6. **Order record**: After submitting, find the Order in Salesforce. Verify all fields: Status = "Draft", correct order type, correct Account, and correct configuration fields (SIM type, access mode, etc.).
7. **Order Items**: Verify each SKU from the checkout cart appears as an OrderItem with the correct Product2, unit price, and quantity.
8. **Opportunity**: Verify an Opportunity is linked to the Order and its stage is "Post Processing."
9. **MNP data**: For SIM orders with number porting, verify all MNP fields are populated on the Order (reservation number, expiry, porting name, etc.).

### Order Tracking

10. **Real-time updates**: With the order detail page open, have someone change the order's activation status in Salesforce. The page should update automatically within a few seconds without a manual refresh.
11. **Progress timeline**: Verify the timeline matches the order's current status. Test each status transition and confirm the correct step is highlighted.
12. **Status labels**: Confirm that Draft/Pending Review shows "Under Review," Scheduled shows "Installation Scheduled," Activating shows "Setting Up Service," and Activated shows "Service Active."

### WHMCS Provisioning

13. **Service creation**: After the order is activated/provisioned, verify a matching Product/Service exists in WHMCS under the correct Client record, with the correct product, billing cycle, and price.
14. **Order creation**: Verify a WHMCS Order was created and an invoice was generated.
15. **Error handling**: Test the "payment method missing" scenario -- remove the user's payment method, trigger provisioning, and verify the error code appears on the Salesforce Order. Then add a payment method and re-trigger to verify recovery.

### Orders List

16. **Filtering**: Submit several orders of different types and statuses. Verify the search, status filter, and type filter all work correctly on the My Orders page.
17. **Summary stats**: Verify the counts for Total, Pending, Active, and Processing match the actual orders.
18. **Navigation**: Click an order card and verify it navigates to the correct order detail page.
