# Accounting Module - API Documentation

## Overview

This document provides comprehensive API documentation for the Accounting module. The system currently uses traditional Django views with HTML templates for the web interface.

**Current Implementation:** Traditional Django views with session-based authentication  
**Future Enhancement:** REST API using Django REST Framework (DRF) for mobile/third-party integration

## Implementation Status

The accounting module is currently implemented as a Django web application with HTML views. This document outlines the API structure that would be implemented if REST API support is added via Django REST Framework.

For current web interface usage, please refer to the [User Manual](USER_MANUAL.md)

## Authentication

All API endpoints require authentication. The system uses Django's session-based authentication with token support for API clients.

### Session Authentication

For web browser access:
```bash
# Login via web interface
POST /accounts/login/
Content-Type: application/x-www-form-urlencoded

username=accountant&password=secure_password
```

### Token Authentication (If DRF Implemented)

For programmatic access:
```bash
# Obtain token
POST /api/auth/token/
Content-Type: application/json

{
    "username": "accountant",
    "password": "secure_password"
}

# Response
{
    "token": "9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b",
    "user_id": 123,
    "username": "accountant"
}

# Use token in subsequent requests
curl -H "Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b" \
     https://api.example.com/api/accounting/accounts/
```

## API Endpoints

### 1. Chart of Accounts

#### List All Accounts

**Endpoint:** `GET /api/accounting/accounts/`

**Description:** Retrieve all accounts in the Chart of Accounts

**Query Parameters:**
- `account_type` (optional): Filter by type (asset, liability, equity, income, expense)
- `is_active` (optional): Filter by status (true/false)
- `search` (optional): Search by code or name
- `page` (optional): Page number for pagination
- `page_size` (optional): Number of items per page (default: 50)

**Permissions Required:** `accounting.view_account`

**Example Request:**
```bash
curl -X GET \
  'https://api.example.com/api/accounting/accounts/?account_type=asset&is_active=true' \
  -H 'Authorization: Token YOUR_TOKEN_HERE'
```

**Example Response:**
```json
{
    "count": 45,
    "next": "https://api.example.com/api/accounting/accounts/?page=2",
    "previous": null,
    "results": [
        {
            "id": 1,
            "code": "202001",
            "name": "Loan Portfolio",
            "account_type": "asset",
            "subtype": "loan_portfolio",
            "description": "Outstanding loan balances",
            "parent_account": null,
            "is_active": true,
            "is_system_account": true,
            "current_balance": "5000000.00",
            "created_at": "2024-01-01T10:00:00Z",
            "updated_at": "2024-01-15T14:30:00Z"
        },
        {
            "id": 2,
            "code": "202002",
            "name": "Accrued Interest Receivable",
            "account_type": "asset",
            "subtype": "current_asset",
            "description": "Interest earned but not yet collected",
            "parent_account": null,
            "is_active": true,
            "is_system_account": true,
            "current_balance": "150000.00",
            "created_at": "2024-01-01T10:00:00Z",
            "updated_at": "2024-01-15T14:30:00Z"
        }
    ]
}
```

#### Get Account Details

**Endpoint:** `GET /api/accounting/accounts/{code}/`

**Description:** Retrieve details for a specific account

**Path Parameters:**
- `code`: Account code (e.g., "202001")

**Permissions Required:** `accounting.view_account`

**Example Request:**
```bash
curl -X GET \
  'https://api.example.com/api/accounting/accounts/202001/' \
  -H 'Authorization: Token YOUR_TOKEN_HERE'
```

**Example Response:**
```json
{


.

## REST API Implementation Guide

If REST API support is required, follow these steps:

### 1. Install Django REST Framework

```bash
pip install djangorestframework
pip install django-filter
```

### 2. Update Settings

```python
# settings.py
INSTALLED_APPS = [
    ...
    'rest_framework',
    'rest_framework.authtoken',
    'django_filters',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 50,
    'DEFAULT_FILTER_BACKENDS': [
        'django_filters.rest_framework.DjangoFilterBackend',
        'rest_framework.filters.SearchFilter',
        'rest_framework.filters.OrderingFilter',
    ],
}
```

### 3. Create Serializers

Create `accounting/serializers.py`:

```python
from rest_framework import serializers
from .models import Account, JournalEntry, JournalEntryLine, GeneralLedger

class AccountSerializer(serializers.ModelSerializer):
    current_balance = serializers.DecimalField(
        max_digits=15, decimal_places=2, read_only=True
    )
    
    class Meta:
        model = Account
        fields = '__all__'
        read_only_fields = ['created_at', 'updated_at', 'created_by']

class JournalEntryLineSerializer(serializers.ModelSerializer):
    account_name = serializers.CharField(source='account.name', read_only=True)
    
    class Meta:
        model = JournalEntryLine
        fields = '__all__'


class JournalEntrySerializer(serializers.ModelSerializer):
    lines = JournalEntryLineSerializer(many=True, read_only=True)
    
    class Meta:
        model = JournalEntry
        fields = '__all__'
        read_only_fields = ['created_at', 'updated_at', 'created_by', 'posted_at', 'posted_by']
```

### 4. Create ViewSets

Create `accounting/api_views.py`:

```python
from rest_framework import viewsets, permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import Account, JournalEntry
from .serializers import AccountSerializer, JournalEntrySerializer
from .services.accounting_service import AccountingService

class AccountViewSet(viewsets.ModelViewSet):
    queryset = Account.objects.all()
    serializer_class = AccountSerializer
    permission_classes = [permissions.IsAuthenticated]
    filterset_fields = ['account_type', 'is_active']
    search_fields = ['code', 'name']
    ordering_fields = ['code', 'name', 'created_at']

class JournalEntryViewSet(viewsets.ModelViewSet):
    queryset = JournalEntry.objects.all()
    serializer_class = JournalEntrySerializer
    permission_classes = [permissions.IsAuthenticated]
    
    @action(detail=True, methods=['post'])
    def post_entry(self, request, pk=None):
        entry = self.get_object()
        service = AccountingService()
        try:
            service.post_journal_entry(entry, request.user)
            return Response({'status': 'posted'})
        except ValidationError as e:
            return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
```

### 5. Update URLs

```python
# accounting/urls.py
from rest_framework.routers import DefaultRouter
from .api_views import AccountViewSet, JournalEntryViewSet

router = DefaultRouter()
router.register(r'accounts', AccountViewSet)
router.register(r'journal-entries', JournalEntryViewSet)

# Add to urlpatterns
urlpatterns += router.urls
```

## API Endpoints Reference

### Accounts

- `GET /api/accounting/accounts/` - List accounts
- `POST /api/accounting/accounts/` - Create account
- `GET /api/accounting/accounts/{code}/` - Get account details
- `PUT /api/accounting/accounts/{code}/` - Update account
- `PATCH /api/accounting/accounts/{code}/` - Partial update
- `DELETE /api/accounting/accounts/{code}/` - Delete account (restricted)

### Journal Entries

- `GET /api/accounting/journal-entries/` - List entries
- `POST /api/accounting/journal-entries/` - Create entry
- `GET /api/accounting/journal-entries/{id}/` - Get entry details
- `PUT /api/accounting/journal-entries/{id}/` - Update entry
- `POST /api/accounting/journal-entries/{id}/post_entry/` - Post entry to ledger
- `POST /api/accounting/journal-entries/{id}/reverse/` - Reverse entry

### Reports

- `GET /api/accounting/reports/trial-balance/` - Trial balance
- `GET /api/accounting/reports/income-statement/` - Income statement
- `GET /api/accounting/reports/balance-sheet/` - Balance sheet
- `GET /api/accounting/reports/cash-flow/` - Cash flow statement
- `GET /api/accounting/reports/account-analysis/{code}/` - Account analysis

## Authentication Examples

```bash
# Obtain token
curl -X POST https://api.example.com/api/auth/token/ \
  -H "Content-Type: application/json" \
  -d '{"username":"accountant","password":"secret"}'

# Response: {"token":"9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b"}

# Use token
curl -X GET https://api.example.com/api/accounting/accounts/ \
  -H "Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b"
```

## Permission Requirements

| Endpoint | Permission | Description |
|----------|------------|-------------|
| List/View Accounts | `accounting.view_account` | View account information |
| Create Account | `accounting.add_account` | Create new accounts |
| Modify Account | `accounting.change_account` | Edit account details |
| Delete Account | `accounting.delete_account` | Delete accounts (restricted) |
| View Journal Entries | `accounting.view_journalentry` | View entries |
| Create Journal Entry | `accounting.add_journalentry` | Create new entries |
| Post Journal Entry | `accounting.post_journalentry` | Post entries to ledger |
| Reverse Journal Entry | `accounting.reverse_journalentry` | Reverse posted entries |
| View Reports | `accounting.view_reports` | Access financial reports |
| Close Fiscal Period | `accounting.close_fiscalperiod` | Close accounting periods |

## Error Responses

All API endpoints return standard HTTP status codes:

- `200 OK` - Successful request
- `201 Created` - Resource created successfully
- `400 Bad Request` - Invalid request data
- `401 Unauthorized` - Authentication required
- `403 Forbidden` - Insufficient permissions
- `404 Not Found` - Resource not found
- `500 Internal Server Error` - Server error

Example error response:
```json
{
    "error": "Debits must equal credits",
    "field_errors": {
        "lines": ["Total debits (10000.00) do not equal total credits (9500.00)"]
    }
}
```

---

**Note:** This API documentation describes the planned REST API structure. The current system uses Django views with HTML templates. If REST API support is needed, follow the implementation guide above.

For web interface usage instructions, please see the [User Manual](USER_MANUAL.md).
