# Chart of Accounts - Complete API Reference

**Date**: 2025-01-22  
**Base Path**: `/api/accounting/chart-of-accounts`

---

## 📋 All Endpoints (19 Total)

### Core Endpoints (9)

#### 1. Get All Accounts (Paginated)
```
GET /api/accounting/chart-of-accounts
```
**Query Parameters**:
- `standard` (optional): `USGAAP`, `IFRS`, or `BOTH` (default: `BOTH`)
- `includeSubAccounts` (optional): `true` or `false` (default: `false`)
- `includeInactive` (optional): `true` or `false` (default: `false`)
- `page` (optional): Page number (default: `1`)
- `limit` (optional): Items per page (default: `50`, max: `100`)

**Response**:
```json
{
  "success": true,
  "data": [...],
  "total": 100,
  "page": 1,
  "limit": 50,
  "totalPages": 2
}
```

#### 2. Get Account by Code
```
GET /api/accounting/chart-of-accounts/:accountCode
```
**Parameters**: `accountCode` (4-10 digits)

#### 3. Get Accounts by Category
```
GET /api/accounting/chart-of-accounts/category/:category
```
**Parameters**: `category` (`ASSET`, `LIABILITY`, `EQUITY`, `REVENUE`, `EXPENSE`, `OTHER`)

#### 4. Get Account Balance
```
GET /api/accounting/chart-of-accounts/:accountCode/balance
```

#### 5. Get Child Accounts
```
GET /api/accounting/chart-of-accounts/:parentCode/children
```

#### 6. Get Account Hierarchy
```
GET /api/accounting/chart-of-accounts/:rootCode/hierarchy
```

#### 7. Create Account
```
POST /api/accounting/chart-of-accounts
```
**Auth Required**: `ACCOUNTANT`, `ADMIN`, or `SYSTEM`  
**Rate Limited**: 10 requests per 15 minutes

**Request Body**:
```json
{
  "accountCode": "9999",
  "accountName": "Test Account",
  "category": "ASSET",
  "level": 1,
  "normalBalance": "DEBIT",
  "accountType": "Current Asset",
  "usgaapClassification": "Assets",
  "ifrsClassification": "Assets",
  "description": "Test account description",
  "isActive": true,
  "isSystemAccount": false
}
```

#### 8. Update Account
```
PUT /api/accounting/chart-of-accounts/:accountCode
```
**Auth Required**: `ACCOUNTANT`, `ADMIN`, or `SYSTEM`  
**Rate Limited**: 20 requests per 15 minutes

#### 9. Initialize Chart of Accounts
```
POST /api/accounting/chart-of-accounts/initialize
```
**Auth Required**: `ADMIN` or `SYSTEM`  
**Rate Limited**: 5 requests per hour

---

### Enhancement Endpoints (10)

#### 10. Bulk Create Accounts
```
POST /api/accounting/chart-of-accounts/bulk
```
**Auth Required**: `ACCOUNTANT`, `ADMIN`, or `SYSTEM`  
**Rate Limited**: 5 requests per 15 minutes

**Request Body**:
```json
{
  "accounts": [
    {
      "accountCode": "9999",
      "accountName": "Account 1",
      "category": "ASSET",
      "level": 1,
      "normalBalance": "DEBIT"
    },
    {
      "accountCode": "9998",
      "accountName": "Account 2",
      "category": "ASSET",
      "level": 1,
      "normalBalance": "DEBIT"
    }
  ],
  "skipDuplicates": true
}
```

**Response**:
```json
{
  "success": true,
  "created": 2,
  "skipped": 0,
  "errors": []
}
```

#### 11. Bulk Update Accounts
```
PUT /api/accounting/chart-of-accounts/bulk
```
**Auth Required**: `ACCOUNTANT`, `ADMIN`, or `SYSTEM`  
**Rate Limited**: 5 requests per 15 minutes

**Request Body**:
```json
{
  "updates": [
    {
      "accountCode": "9999",
      "updates": {
        "accountName": "Updated Name",
        "description": "Updated description"
      }
    }
  ]
}
```

#### 12. Search Accounts
```
GET /api/accounting/chart-of-accounts/search
```
**Query Parameters**:
- `q` (required): Search query
- `category` (optional): Filter by category
- `limit` (optional): Max results (default: `50`)
- `offset` (optional): Offset for pagination

**Example**:
```
GET /api/accounting/chart-of-accounts/search?q=cash&category=ASSET
```

#### 13. Export Accounts
```
GET /api/accounting/chart-of-accounts/export
```
**Query Parameters**:
- `format` (optional): `json` or `csv` (default: `json`)

**Example**:
```
GET /api/accounting/chart-of-accounts/export?format=csv
```

#### 14. Import Accounts
```
POST /api/accounting/chart-of-accounts/import
```
**Auth Required**: `ACCOUNTANT`, `ADMIN`, or `SYSTEM`  
**Rate Limited**: 3 requests per hour

**Request Body**:
```json
{
  "data": "[{\"accountCode\":\"9999\",...}]",
  "format": "json",
  "skipDuplicates": true,
  "validateOnly": false
}
```

#### 15. List Templates
```
GET /api/accounting/chart-of-accounts/templates
```

**Response**:
```json
{
  "success": true,
  "templates": ["us-banking", "ifrs-banking", "commercial", "nonprofit"],
  "data": {
    "us-banking": [...],
    "ifrs-banking": [...],
    "commercial": [...],
    "nonprofit": [...]
  }
}
```

#### 16. Apply Template
```
POST /api/accounting/chart-of-accounts/templates/:templateName
```
**Auth Required**: `ACCOUNTANT`, `ADMIN`, or `SYSTEM`  
**Rate Limited**: 5 requests per 15 minutes

**Available Templates**:
- `us-banking` - US Banking chart of accounts
- `ifrs-banking` - IFRS Banking chart of accounts
- `commercial` - Commercial business template
- `nonprofit` - Nonprofit organization template

#### 17. Soft Delete Account
```
DELETE /api/accounting/chart-of-accounts/:accountCode
```
**Auth Required**: `ACCOUNTANT`, `ADMIN`, or `SYSTEM`

**Note**: Soft delete sets `isActive: false` and stores deletion metadata. Cannot delete accounts with active children.

#### 18. Restore Account
```
POST /api/accounting/chart-of-accounts/:accountCode/restore
```
**Auth Required**: `ACCOUNTANT`, `ADMIN`, or `SYSTEM`

#### 19. Get Account History
```
GET /api/accounting/chart-of-accounts/:accountCode/history
```

**Response**:
```json
{
  "success": true,
  "accountCode": "1000",
  "history": [
    {
      "eventType": "chart_of_accounts_create",
      "action": "CREATE",
      "timestamp": "2025-01-22T10:00:00Z",
      "details": {...}
    },
    {
      "eventType": "chart_of_accounts_update",
      "action": "UPDATE",
      "timestamp": "2025-01-22T11:00:00Z",
      "details": {...}
    }
  ],
  "count": 2
}
```

---

## 🔐 Authentication & Authorization

All endpoints require authentication via JWT token in the `Authorization` header:
```
Authorization: Bearer <token>
```

**Role Requirements**:
- **Read Operations**: No special role required (authenticated users)
- **Write Operations**: `ACCOUNTANT`, `ADMIN`, or `SYSTEM` role required
- **Initialize**: `ADMIN` or `SYSTEM` role required

---

## ⚡ Rate Limiting

- **Account Creation**: 10 requests per 15 minutes
- **Account Updates**: 20 requests per 15 minutes
- **Initialize**: 5 requests per hour
- **Bulk Operations**: 5 requests per 15 minutes
- **Import**: 3 requests per hour

---

## 📊 Account Categories

- `ASSET` - Assets (normal balance: DEBIT)
- `LIABILITY` - Liabilities (normal balance: CREDIT)
- `EQUITY` - Equity (normal balance: CREDIT)
- `REVENUE` - Revenue (normal balance: CREDIT)
- `EXPENSE` - Expenses (normal balance: DEBIT)
- `OTHER` - Other accounts

---

## 🔍 Search Fields

The search endpoint searches across:
- Account code
- Account name
- Description
- Account type

---

## 📝 Import/Export Formats

### JSON Format
```json
[
  {
    "accountCode": "1000",
    "accountName": "ASSETS",
    "category": "ASSET",
    "level": 1,
    "normalBalance": "DEBIT",
    ...
  }
]
```

### CSV Format
```csv
accountCode,accountName,category,parentAccountCode,level,normalBalance,...
"1000","ASSETS","ASSET","",1,"DEBIT",...
```

---

## ✅ Error Responses

All endpoints return consistent error format:
```json
{
  "success": false,
  "error": "Error message",
  "code": "ERROR_CODE"
}
```

**Common Error Codes**:
- `NOT_FOUND` - Resource not found
- `VALIDATION_ERROR` - Validation failed
- `FORBIDDEN` - Insufficient permissions
- `RATE_LIMIT_EXCEEDED` - Too many requests

---

## 🚀 Quick Start Examples

### Get all active accounts
```bash
curl -H "Authorization: Bearer <token>" \
  http://localhost:3000/api/accounting/chart-of-accounts
```

### Search for accounts
```bash
curl -H "Authorization: Bearer <token>" \
  "http://localhost:3000/api/accounting/chart-of-accounts/search?q=cash"
```

### Export to CSV
```bash
curl -H "Authorization: Bearer <token>" \
  "http://localhost:3000/api/accounting/chart-of-accounts/export?format=csv" \
  > accounts.csv
```

### Apply US Banking template
```bash
curl -X POST \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  http://localhost:3000/api/accounting/chart-of-accounts/templates/us-banking
```

---

**Last Updated**: 2025-01-22
