# SIM Manager Migration Package

This folder contains all the code, logic, and rules for the SIM Manager feature and Freebit API integration. Use this package when migrating SIM Manager functionality to a different branch.

## 📁 Folder Structure

```
sim-manager-migration/
├── backend/
│   ├── freebit-integration/          # Freebit API integration layer
│   │   ├── services/                 # Freebit API service implementations
│   │   ├── interfaces/               # TypeScript interfaces and types
│   │   └── freebit.module.ts         # NestJS module
│   ├── sim-management/               # SIM management business logic
│   │   ├── services/                 # SIM management services
│   │   ├── types/                    # Request/response types
│   │   ├── interfaces/               # Business logic interfaces
│   │   ├── sim-management.module.ts  # NestJS module
│   │   └── sim-management.service.ts # Main service facade
│   └── controllers/                  # API endpoint definitions
│       └── sim-endpoints.controller.ts
├── frontend/                         # React/Next.js components
│   ├── components/                   # SIM management UI components
│   ├── utils/                        # Frontend utilities
│   └── index.ts                      # Exports
└── docs/                             # Documentation
    ├── FREEBIT-SIM-MANAGEMENT.md     # Complete implementation guide
    └── SIM-MANAGEMENT-API-DATA-FLOW.md # API data flow documentation
```

## 🚀 Migration Steps

### 1. Backend Setup

#### Step 1.1: Copy Freebit Integration
Copy the entire `backend/freebit-integration/` folder to:
```
apps/bff/src/integrations/freebit/
```

#### Step 1.2: Copy SIM Management Module
Copy the entire `backend/sim-management/` folder to:
```
apps/bff/src/modules/subscriptions/sim-management/
```

Also copy:
```
backend/sim-management/sim-management.service.ts
```
to:
```
apps/bff/src/modules/subscriptions/sim-management.service.ts
```

#### Step 1.3: Add Controller Endpoints
The file `backend/controllers/sim-endpoints.controller.ts` contains all SIM-related endpoints. You need to:

1. **Option A**: Add these methods to your existing `SubscriptionsController`
2. **Option B**: Create a separate `SimManagementController` and register it

The endpoints are:
- `GET /api/subscriptions/:id/sim` - Get comprehensive SIM info
- `GET /api/subscriptions/:id/sim/details` - Get SIM details
- `GET /api/subscriptions/:id/sim/usage` - Get usage data
- `GET /api/subscriptions/:id/sim/top-up-history` - Get top-up history
- `POST /api/subscriptions/:id/sim/top-up` - Top up data quota
- `POST /api/subscriptions/:id/sim/change-plan` - Change plan
- `POST /api/subscriptions/:id/sim/cancel` - Cancel SIM
- `POST /api/subscriptions/:id/sim/reissue-esim` - Reissue eSIM
- `POST /api/subscriptions/:id/sim/features` - Update features
- `GET /api/subscriptions/:id/sim/debug` - Debug endpoint

#### Step 1.4: Register Modules
Ensure your main app module imports both modules:

```typescript
// apps/bff/src/app.module.ts or subscriptions.module.ts
import { FreebitModule } from "@bff/integrations/freebit/freebit.module";
import { SimManagementModule } from "@bff/modules/subscriptions/sim-management/sim-management.module";

@Module({
  imports: [
    // ... other modules
    FreebitModule,
    SimManagementModule,
  ],
  // ...
})
```

### 2. Frontend Setup

#### Step 2.1: Copy Frontend Components
Copy the entire `frontend/` folder to:
```
apps/portal/src/features/sim-management/
```

#### Step 2.2: Integrate into Subscription Page
The main component is `SimManagementSection.tsx`. Import and use it in your subscription detail page:

```typescript
import { SimManagementSection } from "@/features/sim-management";

// In your subscription detail component:
<SimManagementSection subscriptionId={subscriptionId} />
```

### 3. Environment Configuration

Add these environment variables to your `.env` file:

```bash
# Freebit API Configuration
FREEBIT_BASE_URL=https://i1-q.mvno.net/emptool/api/
# Production: FREEBIT_BASE_URL=https://i1.mvno.net/emptool/api

FREEBIT_OEM_ID=PASI
FREEBIT_OEM_KEY=your_oem_key_here
FREEBIT_TIMEOUT=30000
FREEBIT_RETRY_ATTEMPTS=3
```

### 4. Dependencies

#### Required NestJS Modules
- `@nestjs/common`
- `@nestjs/config`
- `nestjs-pino` (for logging)

#### Required Services
The SIM Manager depends on these services (ensure they exist in your branch):

1. **WHMCS Integration** (for top-up payments):
   - `WhmcsService` with `createInvoice()` and `capturePayment()` methods
   - Required for the top-up payment flow

2. **Subscriptions Service**:
   - `SubscriptionsService` - for subscription data access

3. **Mappings Service**:
   - `MappingsModule` - for ID mapping between systems

4. **Email Service**:
   - `EmailModule` - for notifications

5. **Sim Usage Store**:
   - `SimUsageStoreService` - for caching usage data

### 5. Type Definitions

The code uses types from `@customer-portal/domain`. Ensure these types are available:

- `SimTopupRequest`
- `SimChangePlanRequest`
- `SimCancelRequest`
- `SimFeaturesRequest`
- `SimDetails`
- `SimUsage`
- `SimTopUpHistory`

If these don't exist in your domain package, they are defined in:
- `backend/sim-management/types/sim-requests.types.ts`
- `backend/freebit-integration/interfaces/freebit.types.ts`

## 📋 Freebit API Endpoints Used

The implementation uses the following Freebit APIs:

1. **PA01-01**: OEM Authentication (`/authOem/`)
2. **PA03-02**: Get Account Details (`/mvno/getDetail/`)
3. **PA04-04**: Add Specs & Quota (`/master/addSpec/`)
4. **PA05-01**: MVNO Communication Information (`/mvno/getTrafficInfo/`)
5. **PA05-02**: MVNO Quota Addition History (`/mvno/getQuotaHistory/`)
6. **PA05-04**: MVNO Plan Cancellation (`/mvno/releasePlan/`)
7. **PA05-21**: MVNO Plan Change (`/mvno/changePlan/`)
8. **PA05-22**: MVNO Quota Settings (`/mvno/eachQuota/`)
9. **PA05-42**: eSIM Profile Reissue (`/esim/reissueProfile/`)
10. **Enhanced**: eSIM Add Account/Reissue (`/mvno/esim/addAcnt/`)

## 🔧 Key Features

### SIM Management Operations
- ✅ View SIM details (ICCID, MSISDN, plan, status)
- ✅ Real-time data usage monitoring
- ✅ Data quota top-up with payment processing (1GB = ¥500)
- ✅ eSIM profile reissue
- ✅ SIM service cancellation
- ✅ Plan change functionality
- ✅ Usage history tracking
- ✅ Service options management (Voice Mail, Call Waiting, Roaming)

### Payment Flow (Top-Up)
The top-up feature includes a complete payment flow:
1. User requests top-up amount
2. WHMCS invoice created
3. Payment captured automatically
4. Freebit API called to add quota
5. Success/error handling

## 📚 Documentation

- **FREEBIT-SIM-MANAGEMENT.md**: Complete implementation guide with all features, API endpoints, and configuration
- **SIM-MANAGEMENT-API-DATA-FLOW.md**: Detailed API data flow and system architecture documentation

## ⚠️ Important Notes

1. **WHMCS Integration Required**: The top-up feature requires WHMCS integration with `createInvoice()` and `capturePayment()` methods. If these don't exist in your branch, you'll need to implement them or modify the top-up service.

2. **Module Dependencies**: The `FreebitModule` and `SimManagementModule` have circular dependencies resolved with `forwardRef()`. Ensure this pattern is maintained.

3. **Authentication**: All endpoints require authentication. The controller uses `@ApiBearerAuth()` and expects a JWT token.

4. **Validation**: Request validation uses Zod schemas. Ensure `ZodValidationPipe` is available in your validation utilities.

5. **Error Handling**: The implementation includes comprehensive error handling and user-friendly error messages.

## 🧪 Testing

After migration, test the following:

1. **SIM Details**: Verify SIM information displays correctly
2. **Usage Data**: Check that usage charts and data are accurate
3. **Top-Up**: Test the complete payment flow
4. **Plan Change**: Verify plan changes work correctly
5. **eSIM Reissue**: Test eSIM profile reissue (if applicable)
6. **Error Handling**: Test error scenarios (invalid subscription, API failures, etc.)

## 🔍 Troubleshooting

### Common Issues

1. **"Module not found" errors**: Ensure all modules are properly imported in your app module
2. **"FREEBIT_OEM_KEY is not configured"**: Add the environment variable
3. **Payment failures**: Verify WHMCS integration is working
4. **API timeouts**: Check Freebit API connectivity and increase timeout if needed

### Debug Endpoints

Use the debug endpoint to troubleshoot:
```
GET /api/subscriptions/:id/sim/debug
GET /api/debug/sim-details/:account
```

## 📞 Support

For detailed implementation information, refer to:
- `docs/FREEBIT-SIM-MANAGEMENT.md` - Complete feature documentation
- `docs/SIM-MANAGEMENT-API-DATA-FLOW.md` - API integration details

---

**Last Updated**: January 2025  
**Migration Package Version**: 1.0

