# Bank Management System - Complete Documentation

## Overview

A comprehensive, modern Bank Management System built with clean architecture, service layer pattern, and best practices for UltimatePOS AccountingReports module.

## Architecture

### Service Layer Pattern
- **BankAccountService**: Core bank account operations
- **ChequeEntryService**: Cheque management and tracking
- **BankReconciliationService**: Bank reconciliation logic

### Controller
- **BankManagementController**: RESTful API-style controller with clean separation of concerns

### Form Requests
- **StoreBankAccountRequest**: Validation for creating bank accounts
- **UpdateBankAccountRequest**: Validation for updating bank accounts
- **StoreChequeEntryRequest**: Validation for cheque entries
- **ReconcileTransactionRequest**: Validation for reconciliation

## Features

### 1. Bank Account Management

#### Create Bank Account
- Account name (unique per business)
- Account type (Asset/Liability)
- Bank details (name, account number, IFSC, branch)
- Linked account integration
- Opening balance with automatic transaction creation
- Active/Inactive status

#### Bank Account Operations
- View bank account details
- Update bank account information
- Delete bank account (with validation)
- View account statement
- Get current balance
- Account summary dashboard

### 2. Cheque Entry Management

#### Cheque Entry Features
- Create cheque entries (Issued/Received)
- Track cheque status (Pending, Cleared, Bounced, Cancelled, Deposited)
- Link to account transactions
- Cheque number validation (unique per bank account)
- Payee name tracking
- Date tracking (cheque date, presented date, cleared date, bounced date)
- Bounce reason tracking

#### Cheque Operations
- Mark cheque as cleared
- Mark cheque as bounced (with reason)
- Cancel pending cheques
- View cheque summary by bank account
- Filter cheques by type, status, date range

### 3. Bank Reconciliation

#### Reconciliation Features
- View unreconciled transactions
- Reconcile multiple transactions at once
- Bank statement reference tracking
- Cleared date tracking
- Reconciliation statement generation
- Outstanding transactions tracking

#### Reconciliation Operations
- Get unreconciled transactions list
- Reconcile transactions (mark as cleared)
- Unreconcile transactions
- Generate reconciliation statement
- View reconciliation summary

## API Endpoints

### Bank Accounts

```
GET    /accounting-reports/bank-management              - List bank accounts
GET    /accounting-reports/bank-management/get-bank-accounts - Get DataTables data
GET    /accounting-reports/bank-management/create       - Create form
POST   /accounting-reports/bank-management              - Store bank account
GET    /accounting-reports/bank-management/{id}         - Show bank account
GET    /accounting-reports/bank-management/{id}/edit    - Edit form
PUT    /accounting-reports/bank-management/{id}         - Update bank account
DELETE /accounting-reports/bank-management/{id}         - Delete bank account
GET    /accounting-reports/bank-management/{id}/statement - Get statement
GET    /accounting-reports/bank-management/{id}/manage   - Management dashboard
GET    /accounting-reports/bank-management/summary       - Get summary
```

### Cheque Entries

```
GET    /accounting-reports/bank-management/{bankAccountId}/cheque-entries - Get cheque entries
POST   /accounting-reports/bank-management/cheque-entries - Store cheque entry
POST   /accounting-reports/bank-management/cheque/{id}/mark-cleared - Mark as cleared
POST   /accounting-reports/bank-management/cheque/{id}/mark-bounced - Mark as bounced
```

### Bank Reconciliation

```
GET    /accounting-reports/bank-management/{bankAccountId}/unreconciled-transactions - Get unreconciled
POST   /accounting-reports/bank-management/{bankAccountId}/reconcile - Reconcile transactions
GET    /accounting-reports/bank-management/{bankAccountId}/reconciliation-statement - Get statement
```

## Database Schema

### ar_bank_accounts
- id
- business_id
- account_name (unique per business)
- account_type (liability/asset)
- bank_name
- account_number
- ifsc_code
- branch_name
- description
- linked_account_id (FK to accounts)
- opening_balance
- opening_date
- opening_balance_transaction_id
- is_active
- created_by
- timestamps, soft_deletes

### ar_cheque_book_entries
- id
- business_id
- bank_account_id (FK to ar_bank_accounts) - NEW
- account_id (FK to accounts) - Legacy
- cheque_number (renamed from cheque_no)
- cheque_date
- type (issued/received)
- status (pending/cleared/bounced/cancelled/deposited)
- amount
- payee_name
- description
- account_transaction_id (FK to account_transactions) - NEW
- transaction_payment_id
- presented_date
- cleared_date
- bounced_date
- bounce_reason
- created_by
- timestamps, soft_deletes

### ar_bank_reconciliation
- id
- business_id
- account_id (FK to accounts)
- account_transaction_id (FK to account_transactions) - NEW
- journal_entry_line_id (Legacy, nullable)
- transaction_date
- amount
- reference
- description
- is_cleared
- cleared_date
- cleared_by
- bank_statement_ref
- bank_statement_date
- timestamps

## Permissions Required

- `accounting.view_all` - View all bank management features
- `accounting.view_bankbook` - View bank book
- `accounting.add_cheque_entry` - Add cheque entries
- `accounting.edit_cheque_entry` - Edit cheque entries
- `accounting.delete_cheque_entry` - Delete cheque entries
- `accounting.reconcile_bankbook` - Reconcile bank transactions

## Usage Examples

### Creating a Bank Account

```php
$data = [
    'account_name' => 'HDFC Current Account',
    'account_type' => 'asset',
    'bank_name' => 'HDFC Bank',
    'account_number' => '1234567890',
    'ifsc_code' => 'HDFC0001234',
    'branch_name' => 'Main Branch',
    'linked_account_id' => 123,
    'opening_balance' => 100000,
    'opening_date' => '2025-01-01',
    'is_active' => true,
];

$bankAccount = $bankAccountService->createBankAccount($data, $businessId, $userId);
```

### Creating a Cheque Entry

```php
$data = [
    'bank_account_id' => 1,
    'cheque_number' => '000123',
    'cheque_date' => '2025-01-15',
    'type' => 'issued',
    'status' => 'pending',
    'amount' => 50000,
    'payee_name' => 'ABC Company',
    'description' => 'Payment for services',
];

$chequeEntry = $chequeEntryService->createChequeEntry($data, $businessId, $userId);
```

### Reconciling Transactions

```php
$transactionIds = [101, 102, 103];
$clearedDate = Carbon::parse('2025-01-15');
$bankStatementRef = 'STMT-2025-01-15';

$reconciled = $reconciliationService->reconcileTransactions(
    $bankAccount,
    $transactionIds,
    $clearedDate,
    $bankStatementRef
);
```

## Migration Instructions

1. Run the new migrations:
```bash
php artisan migrate --path=Modules/AccountingReports/Database/Migrations/2025_01_15_000001_add_account_transaction_id_to_bank_reconciliation.php
php artisan migrate --path=Modules/AccountingReports/Database/Migrations/2025_01_15_000002_add_bank_account_id_to_cheque_book_entries.php
```

2. Update existing cheque entries to link to bank accounts:
```sql
UPDATE ar_cheque_book_entries cbe
INNER JOIN ar_bank_accounts ba ON cbe.account_id = ba.linked_account_id
SET cbe.bank_account_id = ba.id
WHERE cbe.bank_account_id IS NULL;
```

## Best Practices

1. **Always use services** - Don't put business logic in controllers
2. **Validate input** - Use Form Requests for validation
3. **Handle exceptions** - Wrap operations in try-catch blocks
4. **Use transactions** - Wrap multi-step operations in DB transactions
5. **Log errors** - Log all errors for debugging
6. **Check permissions** - Always verify user permissions
7. **Filter by business_id** - Always filter by business_id for multi-tenant security

## Error Handling

All services throw exceptions that should be caught in controllers:
- `\Exception` - General errors with descriptive messages
- Validation errors are handled by Form Requests
- Database errors are logged and re-thrown

## Performance Considerations

- Uses eager loading for relationships
- Indexed database columns for fast queries
- Efficient DataTables queries with proper filtering
- Caching can be added for frequently accessed data

## Security Features

- Permission-based access control
- Business ID filtering (multi-tenant security)
- Input validation via Form Requests
- SQL injection protection (parameterized queries)
- XSS protection (Blade escaping)

## Future Enhancements

- Bank statement import (CSV/Excel)
- Automated reconciliation matching
- Cheque printing functionality
- Bank account balance alerts
- Reconciliation reports export
- Multi-currency support
- Bank account transfer between accounts

