# Accounting System - Quick Reference Guide

## Account Codes (Your Organization's Chart of Accounts)

### Assets (2XXXXX)
| Code | Account Name | Purpose |
|------|-------------|---------|
| 202001 | Loan Portfolio | Outstanding principal on all active loans |
| 202002 | Accrued Interest Receivable | Interest earned but not yet collected |
| 202003 | Cash - Main Branch | Cash on hand |
| 202004 | Bank - Main Account | Bank account balances |
| 202005 | M-Pesa Account | Mobile money balances (SasaPay) |
| 202010 | Allowance for Loan Losses | Provision for bad debts |

### Liabilities (3XXXXX)
| Code | Account Name | Purpose |
|------|-------------|---------|
| 301001 | Client Savings Deposits | Client deposits held |
| 301002 | Accrued Expenses Payable | Expenses incurred but not yet paid |

### Equity (35XXXX)
| Code | Account Name | Purpose |
|------|-------------|---------|
| 350001 | Share Capital | Owner's equity investment |
| 350002 | Retained Earnings | Accumulated profits |

### Income (4XXXXX)
| Code | Account Name | Purpose |
|------|-------------|---------|
| 401001 | Interest Income - Loans | Interest earned on loans |
| 401002 | Fee Income | Processing fees, penalties, other fees |

### Expenses (5XXXXX)
| Code | Account Name | Purpose |
|------|-------------|---------|
| 501001 | Operating Expenses | General operational costs |
| 501002 | Staff Salaries | Employee compensation |
| 501003 | Loan Loss Provision Expense | Bad debt expense |
| 502001 | Depreciation Expense | Asset depreciation |

## Automatic Journal Entries

### Loan Disbursement
**When:** Loan status → 'active'  
**Entry:**
```
DR 202001 (Loan Portfolio)     KES X,XXX
   CR 202003 (Cash)                    KES X,XXX
```

### Loan Repayment
**When:** Repayment recorded  
**Entry:**
```
DR 202003 (Cash) or 202005 (M-Pesa)  KES X,XXX
   CR 202001 (Loan Portfolio)                KES Y,YYY (principal)
   CR 401001 (Interest Income)               KES Z,ZZZ (interest)
   CR 401002 (Fee Income)                    KES W,WWW (fees+penalties)
```

### Expense Approval
**When:** Expense status → 'approved'  
**Entry:**
```
DR 501XXX (Expense Account)    KES X,XXX
   CR 202003/202004/202005            KES X,XXX
```

## Quick Commands

### Check Integration Status
```bash
python verify_accounting_integration.py
```

### View Recent Journal Entries
```python
python manage.py shell
>>> from accounting.models import JournalEntry
>>> JournalEntry.objects.all().order_by('-created_at')[:10]
```

### Check Account Balance
```python
python manage.py shell
>>> from accounting.services.accounting_service import AccountingService
>>> from accounting.models import Account
>>> from datetime import date
>>> 
>>> service = AccountingService()
>>> loan_portfolio = Account.objects.get(code='202001')
>>> balance = service.calculate_account_balance(loan_portfolio, date.today())
>>> print(f"Loan Portfolio Balance: KES {balance['net_balance']:,.2f}")
```

### Generate Trial Balance
```python
python manage.py shell
>>> from accounting.services.report_service import ReportService
>>> from datetime import date
>>> 
>>> service = ReportService()
>>> tb = service.generate_trial_balance(date.today())
>>> print(f"Debits: {tb['totals']['total_debits']}")
>>> print(f"Credits: {tb['totals']['total_credits']}")
>>> print(f"Balanced: {tb['balanced']}")
```

### View P&L Statement
```python
python manage.py shell
>>> from reports.financial_reports_service import get_profit_and_loss
>>> from datetime import date, timedelta
>>> 
>>> end = date.today()
>>> start = end - timedelta(days=30)
>>> pl = get_profit_and_loss(start, end)
>>> print(f"Source: {pl['source']}")
>>> print(f"Income: KES {pl['income']['total']:,.2f}")
>>> print(f"Expenses: KES {pl['expenses']['total_operational']:,.2f}")
>>> print(f"Net Profit: KES {pl['net_profit']:,.2f}")
```

## Report URLs (when logged in)

- **Dashboard**: `/reports/dashboard/`
- **P&L Statement**: Available in dashboard consolidated reports
- **SasaPay Reconciliation**: Available in dashboard
- **Loan Aging**: `/reports/loan-aging/`
- **Accounting Module**: `/accounting/` (if you add URL patterns)

## Troubleshooting

### "Account with code X not found"
**Solution:** Verify account exists and is active
```python
from accounting.models import Account
Account.objects.filter(code='202001', is_active=True).exists()
```

### "Debits don't equal credits"
**Cause:** Repayment allocation doesn't sum to total  
**Check:**
```python
repayment.principal_portion + repayment.interest_portion + 
repayment.fee_portion + repayment.penalty_portion == repayment.amount
```

### No journal entries for old loans
**Explanation:** Normal - signals only work for new transactions  
**Solution:** Optional - run historical migration (see INTEGRATION_GUIDE.md)

### Reports show "direct_calculation" source
**Explanation:** No GL data yet, or accounting system unavailable  
**Solution:** New transactions will create GL entries automatically

## Verification Checklist

- [ ] All critical accounts exist (202001, 202003, 202005, 401001, 401002)
- [ ] Signal handlers registered (check `accounting/apps.py::ready()`)
- [ ] New loans create journal entries
- [ ] New repayments create journal entries
- [ ] Reports can access accounting system
- [ ] Dashboard shows correct portfolio values

## Key Files

- **Integration Service**: `accounting/services/integration_service.py`
- **Signal Handlers**: `accounting/signals.py`
- **Accounting Service**: `accounting/services/accounting_service.py`
- **Report Service**: `accounting/services/report_service.py`
- **Financial Reports**: `reports/financial_reports_service.py`

## Support

For detailed information:
- **Technical Documentation**: `accounting/INTEGRATION_GUIDE.md`
- **Module Documentation**: `accounting/README.md`
- **Summary**: `ACCOUNTING_INTEGRATION_SUMMARY.md`

---

**Quick Reference v1.0.0** | January 2025
