# Comprehensive Implementation Plan
## Features Gap Analysis & Implementation Roadmap

Based on analysis of 15 reference ERP system PDFs (4S Technology) compared against our existing Club ERP system.

---

# PART 1: GAP ANALYSIS

## Features We ALREADY Have (Fully Implemented)

| # | Feature | Our Module | Status |
|---|---------|-----------|--------|
| 1 | General Ledger & Chart of Accounts | Accounting | Full hierarchical COA, GL posting, multi-type accounts |
| 2 | Journal Entries (create/post/reverse) | Accounting | Manual + auto-posting from events |
| 3 | Trial Balance & Financial Statements | Accounting | TB, P&L, Balance Sheet, Consolidated BS |
| 4 | Cost Centers | Accounting | Full CRUD + budget allocation |
| 5 | Budgets (account + cost-center level) | Accounting | With variance analysis |
| 6 | Bank Accounts & Reconciliation | Accounting | Multi-bank, item-level reconciliation |
| 7 | Negotiable Instruments & Portfolios | Accounting | Checks, notes, portfolio management |
| 8 | Fiscal Year Management | Accounting | Create, close, multi-year |
| 9 | Period Closing | Accounting | Month open/close |
| 10 | Accounts Receivable / Payable | Accounting | AR/AP aging reports |
| 11 | Opening Balances | Accounting | Opening entries + snapshots |
| 12 | Multi-dimensional Accounting | Accounting | Configurable dimensions |
| 13 | Employee Management | HR | Full profiles, departments, job titles |
| 14 | Attendance Tracking | HR | Daily bulk entry, monthly views |
| 15 | Leave Management | HR | Request/approve, balance tracking, calendar |
| 16 | Payroll Processing | HR | Multi-period, calculate/approve/pay |
| 17 | Salary Structures & Components | HR | Template-based with components |
| 18 | Employment Contracts | HR | Create, renew, terminate |
| 19 | Social Insurance Records | HR | Form 1 & Form 6 generation |
| 20 | Tax Records | HR | Per-employee tracking |
| 21 | Employee Loans | HR | Request, approve, disburse |
| 22 | End of Service | HR | Calculate, approve, pay |
| 23 | Performance Reviews | HR | Cycles + individual reviews |
| 24 | Disciplinary Actions | HR | With appeals workflow |
| 25 | Inventory Items & Categories | Inventory | Full CRUD, hierarchical categories |
| 26 | Multiple Warehouses | Inventory | Multi-warehouse stock tracking |
| 27 | Stock Movements (in/out) | Inventory | Transaction history, balance tracking |
| 28 | Stock Transfers | Inventory | Inter-warehouse with approval |
| 29 | Stock Audits (Physical Count) | Inventory | Count, variance, adjustment approval |
| 30 | Supplier Management | Inventory | Master data, history |
| 31 | Purchase Orders (basic) | Inventory + Procurement | With approval workflow |
| 32 | Fixed Assets & Depreciation | Inventory | Asset register, depreciation |
| 33 | Low Stock Alerts | Inventory | Reorder level monitoring |
| 34 | Expiry Date Tracking | Inventory | Batch-level expiry |
| 35 | POS / Sales Transactions | Sales | Item selection, customer lookup |
| 36 | Sales Packages/Bundles | Sales | Pre-configured bundles |
| 37 | Sales Refunds | Sales | Partial/full refund |
| 38 | Sales Void | Sales | Transaction cancellation |
| 39 | Purchase Requisitions | Procurement | Create, submit, approve, convert |
| 40 | Goods Received Notes | Procurement | GRN with inspection |
| 41 | Vendor Invoices | Procurement | Entry, verification, approval |
| 42 | Three-Way Matching | Procurement | PR-GRN-Invoice matching |
| 43 | Vendor Payments | Procurement | With approval workflow |
| 44 | Returns to Vendor | Procurement | Full lifecycle tracking |
| 45 | Payment Processing (cash/check/card) | Payments | Multi-method, event-driven |
| 46 | Receipts | Receipts | Auto-generation, printing, voiding |
| 47 | Installment Plans | Installments | Auto-schedule, interest calculation |
| 48 | Cashier Queue | Cashier | Central payment processing |
| 49 | Work Schedules | HR | Template-based |
| 50 | Holidays | HR | Holiday master |
| 51 | Employee Documents | HR | Upload, verify, archive |
| 52 | Daily/Monthly Sales Reports | Sales | By day, month, item |
| 53 | Procurement Reports | Procurement | Volume, performance, overdue |

---

## Features We DON'T Have (Gaps)

### CATEGORY A: High-Impact Business Features (Core ERP Capabilities)

| # | Feature | Source PDF | Priority | Complexity |
|---|---------|-----------|----------|-----------|
| A1 | Configurable Movement Specifications Engine (26+ params per movement type) | Sales, Inventory, Purchasing | HIGH | HIGH |
| A2 | Multi-segment hierarchical item codes (XX-XX-XX-XX-XXXXXX) | Basic ERP, Inventory, Sales | MEDIUM | MEDIUM |
| A3 | Bill of Materials (BOM) / Sub-components for composite items | Basic ERP, Inventory | HIGH | HIGH |
| A4 | Supplier Price Quote solicitation & evaluation workflow | Purchasing | HIGH | MEDIUM |
| A5 | Side-by-side quote comparison across suppliers | Purchasing | HIGH | MEDIUM |
| A6 | Credit limit system for customers with auto-calculated allowed limit | Sales | HIGH | LOW |
| A7 | Supplier credit limit with auto-calculated allowed limit | Purchasing | HIGH | LOW |
| A8 | Documentary Credits (اعتمادات مستندية) | Banks | MEDIUM | HIGH |
| A9 | Letter of Guarantee management (خطابات ضمان) | Banks | MEDIUM | HIGH |
| A10 | Bank Loan management | Banks | MEDIUM | MEDIUM |
| A11 | Debit/Credit settlements across entities (cross-entity) | Purchasing, Banks | MEDIUM | MEDIUM |
| A12 | Sales Representative & Commission management | Sales | MEDIUM | MEDIUM |
| A13 | Multi-currency transactions (full support) | Basic ERP | MEDIUM | HIGH |
| A14 | Hijri/Gregorian dual calendar | Basic ERP | LOW | MEDIUM |
| A15 | Franchise-based supplier account calculation (3 methods) | Purchasing | LOW | MEDIUM |

### CATEGORY B: Fixed Assets Enhancements

| # | Feature | Source PDF | Priority | Complexity |
|---|---------|-----------|----------|-----------|
| B1 | Asset categories with configurable depreciation methods per category | Fixed Assets | HIGH | MEDIUM |
| B2 | Asset location/site tracking with transfers | Fixed Assets | MEDIUM | LOW |
| B3 | Asset custody tracking (عهدة) with employee assignment | Fixed Assets | HIGH | LOW |
| B4 | Asset revaluation | Fixed Assets | MEDIUM | MEDIUM |
| B5 | Asset insurance tracking per asset | Fixed Assets | LOW | LOW |
| B6 | Multiple depreciation methods (straight-line, declining balance, production-units, sum-of-years) | Fixed Assets | HIGH | MEDIUM |
| B7 | Asset improvement/addition tracking | Fixed Assets | MEDIUM | LOW |
| B8 | Partial disposal (sell/scrap portion of asset) | Fixed Assets | LOW | MEDIUM |

### CATEGORY C: HR & Payroll Enhancements

| # | Feature | Source PDF | Priority | Complexity |
|---|---------|-----------|----------|-----------|
| C1 | Overtime system with configurable rates per period/type | HR, Wages | HIGH | MEDIUM |
| C2 | Shift management with rotation and assignment | Attendance | MEDIUM | MEDIUM |
| C3 | Fingerprint/biometric device integration | Attendance | HIGH | HIGH |
| C4 | Attendance violation auto-detection (late, early leave, absence) | Attendance | HIGH | MEDIUM |
| C5 | Permission requests (hourly leaves) | Attendance | MEDIUM | LOW |
| C6 | Mission/travel tracking | Attendance | LOW | LOW |
| C7 | Overtime request & approval workflow | Attendance | MEDIUM | LOW |
| C8 | Social insurance auto-calculation (employer + employee shares with legal limits) | Wages | HIGH | MEDIUM |
| C9 | Progressive tax bracket auto-calculation | Wages | HIGH | MEDIUM |
| C10 | Configurable allowance/deduction formulas | Wages | MEDIUM | MEDIUM |
| C11 | Employee bonus system with configurable criteria | Wages | MEDIUM | LOW |
| C12 | Salary hold/release mechanism | Wages | LOW | LOW |
| C13 | Retroactive salary adjustments | Wages | MEDIUM | MEDIUM |
| C14 | Monthly salary comparison report (variance analysis) | Wages | LOW | LOW |

### CATEGORY D: Purchasing & Procurement Enhancements

| # | Feature | Source PDF | Priority | Complexity |
|---|---------|-----------|----------|-----------|
| D1 | Internal Purchase Request → Quote → Evaluation → PO full cycle | Purchasing | HIGH | MEDIUM |
| D2 | Purchase delay/overdue delivery tracking | Purchasing | HIGH | LOW |
| D3 | Item price deviation monitoring & alerts | Purchasing | MEDIUM | LOW |
| D4 | Item vs. budget comparison for purchases | Purchasing | MEDIUM | LOW |
| D5 | Daily item purchases analysis | Purchasing | LOW | LOW |
| D6 | Supplier debt aging report | Purchasing | MEDIUM | LOW |
| D7 | Payment scheduling/installments for suppliers (جدولة) | Purchasing | MEDIUM | MEDIUM |
| D8 | Specific PO balance tracking (qty requested vs received vs remaining, delivery %) | Purchasing | HIGH | LOW |
| D9 | Items linked to suppliers cross-reference report | Purchasing | LOW | LOW |
| D10 | Movement approval workflow (بيان اعتماد الحركات) | Purchasing | MEDIUM | MEDIUM |

### CATEGORY E: Banking Enhancements

| # | Feature | Source PDF | Priority | Complexity |
|---|---------|-----------|----------|-----------|
| E1 | Check deposit and collection lifecycle tracking (issued→deposited→collected/bounced) | Banks | HIGH | MEDIUM |
| E2 | Check endorsement/transfer (تظهير) | Banks | MEDIUM | MEDIUM |
| E3 | Payment note status update with portfolio-based batch processing | Banks, Purchasing | MEDIUM | LOW |
| E4 | Paper/Check multi-criteria inquiry (by serial, number, bank, date, status) | Purchasing | MEDIUM | LOW |
| E5 | Daily cash movement report for safes/treasuries | Banks | MEDIUM | LOW |
| E6 | Payment notes analysis (summary: direct vs indirect, checks vs promissory) | Purchasing | LOW | LOW |

### CATEGORY F: Sales Enhancements

| # | Feature | Source PDF | Priority | Complexity |
|---|---------|-----------|----------|-----------|
| F1 | Customer discount rates (per-customer per-item pricing) | Sales | MEDIUM | MEDIUM |
| F2 | Sales returns with automatic warehouse stock update | Sales | HIGH | LOW |
| F3 | Multiple configurable sales movement types (invoice, return, quotation, etc.) | Sales | MEDIUM | MEDIUM |
| F4 | Sales collection notes/checks from customers | Sales | MEDIUM | MEDIUM |
| F5 | Customer account statement (detailed and summary) | Sales | HIGH | LOW |
| F6 | Customer current position report (all customers snapshot) | Sales | MEDIUM | LOW |
| F7 | Customer movement tracking in period | Sales | LOW | LOW |

### CATEGORY G: Inventory Enhancements

| # | Feature | Source PDF | Priority | Complexity |
|---|---------|-----------|----------|-----------|
| G1 | Opening balance by item per warehouse (inventory initialization) | Inventory | HIGH | LOW |
| G2 | Item price history tracking (first, current, average purchase prices) | Inventory | MEDIUM | LOW |
| G3 | Supplier-to-item code mapping (supplier part numbers) | Inventory | LOW | LOW |
| G4 | Color/variant/attribute tracking per item group | Inventory | MEDIUM | MEDIUM |
| G5 | Multiple units per item with conversion factors | Inventory | HIGH | MEDIUM |
| G6 | Contractor entity type (separate from customer/supplier) | Inventory | LOW | LOW |
| G7 | Previous years' balance auto-carry-forward | Inventory | MEDIUM | LOW |
| G8 | Configurable stock movement types | Inventory | MEDIUM | MEDIUM |

### CATEGORY H: Reporting & Export Enhancements

| # | Feature | Source PDF | Priority | Complexity |
|---|---------|-----------|----------|-----------|
| H1 | Multi-format report export (Excel, PDF, CSV, HTML) | All PDFs | HIGH | MEDIUM |
| H2 | Report designer with configurable parameters | All PDFs | MEDIUM | HIGH |
| H3 | Report print preview with zoom | All PDFs | LOW | LOW |
| H4 | Supplier account statement (detailed and summary formats) | Purchasing | HIGH | LOW |
| H5 | T-account format for supplier/customer reports | Purchasing, Sales | LOW | LOW |

---

# PART 2: IMPLEMENTATION PLAN

## Phase 1: Quick Wins (Low Complexity, High Impact)
**Timeline: 2-3 weeks**
**Focus: Features that add significant value with minimal development effort**

### 1.1 Customer & Supplier Credit Limits (A6, A7)
- Add `credit_limit` column to members/suppliers tables
- Add `allowed_limit` computed field (credit_limit - total_payments)
- Add warning/block when transaction would exceed limit
- UI: Show credit status on member/supplier profile

### 1.2 Purchase Delay Tracking (D2)
- Add `expected_delivery_date` to purchase_order_items
- Create overdue delivery report (filter by date, supplier, item)
- Dashboard widget for overdue items count

### 1.3 PO Balance Tracking (D8)
- Report showing: qty_ordered vs qty_received vs qty_remaining per PO
- Delivery percentage calculation
- Filter by supplier, date range, item group

### 1.4 Customer Account Statement (F5)
- Detailed report: date, document type, description, debit, credit, running balance
- Summary report: totals only
- Filter by date range, member code

### 1.5 Supplier Account Statement (H4)
- Same as F5 but for suppliers
- Include purchase orders, invoices, payments, returns

### 1.6 Sales Returns with Warehouse Update (F2)
- Enhance refund process to auto-update inventory stock
- Create stock movement record on refund

### 1.7 Inventory Opening Balances (G1)
- Screen to enter opening stock quantities per item per warehouse
- Generate stock movement records for initialization
- Useful for new warehouse setup or year-start

### 1.8 Asset Custody Tracking (B3)
- Add `custodian_employee_id` and `location` to asset_registers
- Asset assignment/transfer form
- Report: assets by employee/location

### 1.9 Asset Location Tracking (B2)
- Add `site_location` field to assets
- Transfer form to move asset between locations
- Asset location history log

---

## Phase 2: Financial & Banking Enhancements (Medium Complexity)
**Timeline: 3-4 weeks**
**Focus: Banking operations and financial instruments**

### 2.1 Check Lifecycle Status Tracking (E1)
- Expand negotiable_instruments with status workflow: issued → deposited → collected/bounced/endorsed
- Status transition actions with date tracking
- Status history log table

### 2.2 Check Endorsement (E2)
- Add endorsement capability (transfer check to another party)
- Track endorsement chain
- Update beneficiary on endorsement

### 2.3 Payment Note Portfolio Batch Processing (E3)
- Batch status update for multiple papers in a portfolio
- Select portfolio → select papers → apply status change
- Bulk operations support

### 2.4 Paper/Check Multi-Criteria Inquiry (E4)
- Advanced search screen for all negotiable instruments
- Filter by: serial, check number, bank, date range (issue/maturity), status, party, type
- Results grid with sort/export

### 2.5 Daily Cash Movement Report (E5)
- Safe/treasury daily movement summary
- Opening balance + inflows - outflows = closing balance
- Per-safe breakdown

### 2.6 Debit/Credit Cross-Entity Settlements (A11)
- Settlement transactions between suppliers, customers, banks, safes
- Purpose types: payment, advance, adjustment
- Auto-post journal entries for both parties

### 2.7 Bank Loan Management (A10)
- Loan master: bank, amount, rate, term, start date
- Amortization schedule generation
- Payment tracking against schedule
- Outstanding balance reporting

---

## Phase 3: Procurement Cycle Enhancement (Medium Complexity)
**Timeline: 3-4 weeks**
**Focus: Complete the procurement cycle with quote management**

### 3.1 Supplier Price Quote Request (A4)
- New entity: `supplier_price_quotes`
- Create quote request linked to purchase requisition
- Send to multiple suppliers (track which suppliers were solicited)
- Supplier response entry: per-item pricing, delivery terms

### 3.2 Quote Evaluation & Comparison (A5)
- Side-by-side comparison screen
- Show all quotes for same PR on one page
- Per-item comparison: price, delivery time, terms
- Winner selection with justification

### 3.3 Quote-to-PO Conversion (D1)
- "Issue Purchase Order" action from evaluation screen
- Auto-populate PO from winning quote
- Link chain: PR → Quotes → Evaluation → PO → GRN → Invoice

### 3.4 Supplier Payment Scheduling (D7)
- Payment plans for large invoices
- Schedule: amount, due date, method (cash/check)
- Track paid vs pending installments
- Alert on upcoming/overdue payments

### 3.5 Item Price Deviation Monitoring (D3)
- Track standard/expected price per item per supplier
- Alert when invoice price deviates beyond threshold
- Deviation report: item, supplier, expected, actual, variance %

### 3.6 Purchase vs Budget Comparison (D4)
- Link purchase categories to budget accounts
- Report: budgeted amount vs actual purchases YTD
- Variance highlighting (over/under budget)

---

## Phase 4: HR & Payroll Enhancements (Medium-High Complexity)
**Timeline: 4-5 weeks**
**Focus: Attendance automation, overtime, and payroll calculation improvements**

### 4.1 Overtime System (C1)
- Overtime types: normal, holiday, night
- Configurable rate multipliers per type (1.5x, 2x, 3x)
- Overtime request submission and approval workflow
- Auto-calculate overtime pay in payroll

### 4.2 Attendance Violation Detection (C4)
- Define rules: grace period, late threshold, early leave threshold
- Auto-detect violations from attendance records vs work schedule
- Violation types: late arrival, early departure, absence, unauthorized
- Penalty rules: deductions after X violations per month

### 4.3 Permission Requests - Hourly Leaves (C5)
- Short-duration leave requests (hours, not days)
- Approval workflow
- Deduct from daily attendance hours
- Monthly summary of permissions taken

### 4.4 Social Insurance Auto-Calculation (C8)
- Egyptian social insurance rules engine
- Basic salary cap, variable salary cap
- Employer share % + Employee share %
- Auto-calculate per payroll run
- Generate Form 2 (monthly contribution)

### 4.5 Progressive Tax Calculation (C9)
- Tax brackets configuration (Egyptian tax law)
- Exemptions and deductions configuration
- Annual tax calculation with monthly distribution
- Year-end reconciliation

### 4.6 Shift Management (C2)
- Shift definitions: start time, end time, break times
- Shift rotation patterns (weekly, bi-weekly, monthly)
- Employee-to-shift assignment
- Shift calendar view

### 4.7 Overtime Request & Approval (C7)
- Pre-approval for planned overtime
- Approval workflow (supervisor → HR)
- Link approved overtime to attendance records

---

## Phase 5: Advanced Inventory & Sales Features (High Complexity)
**Timeline: 5-6 weeks**
**Focus: BOM, multi-unit, movement specifications**

### 5.1 Bill of Materials (BOM) (A3)
- New tables: `bill_of_materials`, `bom_components`
- Define composite items with their sub-components
- Component quantities and units
- BOM versioning
- Auto-deduct components on sale/production of parent item
- Component cost roll-up for pricing

### 5.2 Multiple Units per Item with Conversion (G5)
- Table: `item_units` (item_id, unit_name, conversion_factor, is_base_unit)
- Each item can have: piece, box (12 pieces), carton (48 pieces), etc.
- All movements specify unit; system converts to base unit for stock
- Purchase in one unit, sell in another

### 5.3 Item Color/Variant Tracking (G4)
- Configurable attributes per item category
- Attribute types: color, size, material, etc.
- Stock tracked per variant combination
- Item variant matrix (size × color → stock)

### 5.4 Configurable Stock Movement Types (G8)
- User-definable movement types beyond in/out/transfer
- Each type has: name, direction (in/out/neutral), affects_stock, posts_gl, requires_approval
- Movement specifications per type
- Auto-numbering per type

### 5.5 Sales Representative & Commission (A12)
- Sales rep master data
- Rep assignment to customers/transactions
- Commission rates: flat, percentage, tiered (by volume)
- Commission calculation and reporting
- Commission payment tracking

### 5.6 Per-Customer Pricing (F1)
- Customer-specific discount rates per item/category
- Price lists assignable to customer groups
- Priority: customer price > group price > default price
- Discount reason tracking

### 5.7 Sales Collection (Checks from Customers) (F4)
- Record checks/notes received from customers
- Collection portfolio management
- Status tracking: received → deposited → collected/bounced
- Link to customer account

---

## Phase 6: Configurable Movement Engine & Multi-Currency (Highest Complexity)
**Timeline: 6-8 weeks**
**Focus: System-wide configurability engine**

### 6.1 Movement Specifications Engine (A1)
This is the most complex feature - a meta-configuration system that controls behavior of all transaction types across Sales, Inventory, and Purchasing.

**Core concept:** Each "movement type" (e.g., "Sales Invoice", "Purchase Return", "Stock Transfer") has ~26 configurable parameters that control its behavior:
- Auto-numbering (start number, sequence)
- Whether it affects stock (and direction)
- Whether it posts to GL
- Which accounts to post to
- Whether it requires approval
- Which fields are mandatory
- Which party types are allowed (customer, supplier, warehouse)
- Whether it creates AR/AP entries
- Tax handling
- Discount handling
- Print template selection
- Currency handling

**Implementation approach:**
- `movement_types` table: defines all available movement types
- `movement_specifications` table: key-value parameters per movement type
- Engine class that reads specs and controls movement behavior
- UI for admin to configure each movement type's parameters
- All Sales/Inventory/Procurement modules consume specs from this engine

### 6.2 Multi-Currency Full Support (A13)
- Currency master with exchange rates (daily rates)
- Transaction currency vs. reporting currency
- Multi-currency journal entries
- Gain/loss on exchange rate differences
- Reports in both transaction and reporting currencies
- Customer/supplier balances in their currency
- Period-end revaluation of foreign currency balances

### 6.3 Multi-Segment Item Codes (A2)
- Configurable code structure (segments, lengths, separators)
- Hierarchical: Category - Sub-category - Group - Sub-group - Sequence
- Auto-generate next code within segment
- Search by any segment level
- Reports groupable by any segment

---

## Phase 7: Advanced Financial Features (High Complexity)
**Timeline: 4-5 weeks**
**Focus: Documentary credits, guarantees, advanced banking**

### 7.1 Documentary Credits (A8)
- LC master: issuing bank, beneficiary, amount, currency, terms
- LC lifecycle: opened → shipped → documents presented → paid → closed
- Margin tracking (deposit held by bank)
- Expense allocation to landed cost
- Link to purchase orders and vendor invoices

### 7.2 Letter of Guarantee (A9)
- Guarantee master: bank, beneficiary, amount, type (tender/performance/advance)
- Status lifecycle: requested → issued → active → released/called
- Margin/collateral tracking
- Expiry monitoring and renewal
- Commission/fee tracking

### 7.3 Fixed Asset Enhancements (B1, B4, B6, B7)
- Asset categories with per-category depreciation method
- Multiple methods: straight-line, declining balance, sum-of-years, units-of-production
- Asset revaluation (upward/downward with journal entry)
- Asset improvement/addition (capitalize additional costs)
- Asset insurance tracking

### 7.4 Report Export Engine (H1)
- Universal export functionality for all reports
- Formats: Excel (XLSX), PDF, CSV, HTML
- Configurable columns per export
- Scheduled report generation (email delivery)

---

## Phase 8: Reporting & Analytics Layer
**Timeline: 3-4 weeks**
**Focus: Comprehensive reporting across all modules**

### 8.1 Enhanced Purchasing Reports
- Purchase volume by supplier/item/period
- Supplier performance scoring (delivery time, price variance, quality)
- Purchase request follow-up status
- Cost center expense analysis
- Item purchases by supplier level

### 8.2 Enhanced Sales Reports
- Customer current position (all customers snapshot)
- Customer movement tracking in period
- Sales by rep with commission summary
- Item margin analysis
- Customer lifetime value

### 8.3 Enhanced Inventory Reports
- Item price history (first, current, average)
- Stock valuation by method (FIFO, weighted average, LIFO)
- Dead stock / slow-moving items
- Stock turnover analysis
- Supplier vs item cross-reference

### 8.4 Enhanced Financial Reports
- Cash flow statement
- Payment notes analysis (direct vs indirect, type breakdown)
- Treasury position report
- Budget vs actual across all departments
- Monthly comparison report (this month vs last month vs same month last year)

### 8.5 Dashboard Enhancements
- Executive dashboard: revenue, expenses, cash position, AR/AP aging
- Procurement dashboard: pending approvals, overdue deliveries, budget utilization
- HR dashboard: headcount, attendance %, leave utilization, payroll cost trends
- Inventory dashboard: stock value, movement velocity, expiry warnings

---

# PART 3: IMPLEMENTATION PRIORITIES

## Recommended Execution Order

```
Phase 1 (Quick Wins)          ← START HERE: 2-3 weeks
  ↓
Phase 2 (Banking)             ← 3-4 weeks  
  ↓
Phase 3 (Procurement Cycle)   ← 3-4 weeks
  ↓
Phase 4 (HR Enhancements)     ← 4-5 weeks
  ↓
Phase 5 (Inventory & Sales)   ← 5-6 weeks
  ↓
Phase 6 (Movement Engine)     ← 6-8 weeks (most complex)
  ↓
Phase 7 (Advanced Financial)  ← 4-5 weeks
  ↓
Phase 8 (Reporting)           ← 3-4 weeks
```

**Total estimated timeline: 30-39 weeks (~7-9 months)**

---

## Critical Path Items

These features have dependencies that affect other features:

1. **Movement Specifications Engine (A1)** - Many other features reference configurable movement types. Building this engine first would make phases 3-5 cleaner, but it's also the most complex. Recommendation: build a simplified version first, enhance later.

2. **Multiple Units per Item (G5)** - Affects all inventory movements, sales, and procurement. Should be implemented before BOM.

3. **Multi-Currency (A13)** - Touches nearly every financial transaction. Can be implemented incrementally (start with supplier/customer level, then transactions, then reporting).

4. **Credit Limits (A6, A7)** - Simple to add, but must be enforced across all transaction entry points (sales, procurement, cashier).

---

## Database Schema Additions (Key Tables Needed)

### Phase 1
```sql
-- Customer/Supplier credit limits (add columns to existing tables)
ALTER TABLE members ADD credit_limit DECIMAL(15,2) DEFAULT 0;
ALTER TABLE suppliers ADD credit_limit DECIMAL(15,2) DEFAULT 0;

-- PO delivery tracking
ALTER TABLE purchase_order_items ADD expected_delivery_date DATE NULL;

-- Asset custody
ALTER TABLE asset_registers ADD custodian_employee_id INT NULL;
ALTER TABLE asset_registers ADD site_location VARCHAR(255) NULL;
CREATE TABLE asset_custody_history (...);
```

### Phase 2
```sql
CREATE TABLE negotiable_instrument_status_history (...);
CREATE TABLE cross_entity_settlements (...);
CREATE TABLE bank_loans (...);
CREATE TABLE bank_loan_schedule (...);
```

### Phase 3
```sql
CREATE TABLE supplier_price_quotes (...);
CREATE TABLE supplier_quote_items (...);
CREATE TABLE quote_evaluations (...);
CREATE TABLE supplier_payment_schedules (...);
CREATE TABLE item_price_history (...);
```

### Phase 4
```sql
CREATE TABLE hr_overtime_types (...);
CREATE TABLE hr_overtime_requests (...);
CREATE TABLE hr_attendance_violations (...);
CREATE TABLE hr_permission_requests (...);
CREATE TABLE hr_shifts (...);
CREATE TABLE hr_shift_assignments (...);
CREATE TABLE hr_insurance_config (...);
CREATE TABLE hr_tax_brackets (...);
```

### Phase 5
```sql
CREATE TABLE bill_of_materials (...);
CREATE TABLE bom_components (...);
CREATE TABLE item_units (...);
CREATE TABLE item_attributes (...);
CREATE TABLE item_attribute_values (...);
CREATE TABLE item_variants (...);
CREATE TABLE sales_representatives (...);
CREATE TABLE sales_commissions (...);
CREATE TABLE customer_price_lists (...);
CREATE TABLE customer_item_prices (...);
```

### Phase 6
```sql
CREATE TABLE movement_types (...);
CREATE TABLE movement_specifications (...);
CREATE TABLE currencies (...);
CREATE TABLE exchange_rates (...);
CREATE TABLE item_code_segments (...);
```

### Phase 7
```sql
CREATE TABLE documentary_credits (...);
CREATE TABLE lc_documents (...);
CREATE TABLE letters_of_guarantee (...);
CREATE TABLE asset_categories (...);
CREATE TABLE asset_revaluations (...);
CREATE TABLE asset_improvements (...);
```

---

## Risk Assessment

| Risk | Impact | Mitigation |
|------|--------|-----------|
| Movement engine complexity | Could delay Phase 6 significantly | Start with simplified version; enhance iteratively |
| Multi-currency GL impact | Affects all financial reports | Implement incrementally; start with transaction recording, then reporting |
| BOM stock deduction performance | Complex queries for nested BOMs | Limit BOM depth; cache component lists |
| Credit limit enforcement gaps | Users bypass limits via different screens | Centralize limit check in a service class called by all transaction entry points |
| Attendance device integration | Hardware-dependent, varied protocols | Abstract via interface; support common protocols (ZKTeco, etc.) |
| Data migration for new features | Existing data needs mapping to new structures | Write migration scripts with safe defaults; don't block existing operations |

---

## Success Metrics per Phase

| Phase | Key Metric |
|-------|-----------|
| 1 | Credit limits actively preventing over-credit transactions; PO delivery tracking in use |
| 2 | 90%+ of check lifecycle managed in system vs. manual tracking |
| 3 | Full PR→Quote→Eval→PO cycle operational; deviation alerts active |
| 4 | Overtime auto-calculated in payroll; violation detection reducing manual review |
| 5 | BOM items selling correctly with component deduction; multi-unit purchases flowing |
| 6 | All new movement types configurable without code changes |
| 7 | Documentary credits fully tracked; multi-method depreciation running |
| 8 | Executive dashboards replacing manual Excel reports |

---

---

# PART 4: النشاط الرياضي (SPORTS ACTIVITY) MODULE ENHANCEMENTS

## Current State Assessment

The sports/activity ecosystem spans 16+ modules that already cover most player and admin requirements:

| Requirement | Module | Status |
|-------------|--------|--------|
| Subscribe to sport | ActivitySubscriptions | ✓ Full monthly billing, group-type pricing |
| Evaluation & group placement | TrainingGroups + Sessions | ✓ Age/gender/skill/trainer/time/size (private=1, small=2-5, group=6-15, team=16+) |
| Switch groups | TrainingGroups | ✓ transferPlayer endpoint with status tracking |
| Book grounds for private matches | Reservations | ✓ Facility conflict detection, multi-booker-type, calendar |
| Free-time entry (pool, etc.) | PlayerAffairs + PoolManagement | ✓ free_swim booking type, access_window_minutes, attendance |
| Membership pricing | Pricing + ActivityPricing | ✓ Tiers by player_type and group_type |
| Invitation books (carnets) | Carnets | ✓ QR code, print, replacement flow |
| Medical forms with scans & expiry | PlayerAffairs | ✓ certificate_type, exam_date/expiry, document_id, approval workflow |
| Pool grid system (cells/lanes) | FacilityGrids | ✓ Generic grid: pool/court/generic, zones, H/V selection |
| Academy/trainer agreements | AcademyContracts | ✓ revenue_share/fixed_rent/hybrid, settlement generation |
| Monthly pool plans (per-day, per-hour) | FacilityGrids | ✓ plan_month, day_of_week, start/end time per zone |
| Facility financial dashboard | FacilityDashboards + PoolManagement | ✓ Day/week/month/custom filters, revenue stats |
| Trainer/trainee attendance | Sessions | ✓ session_attendance, makeup credits |
| Notifications framework | Notifications | ✓ SMS templates, bulk, logs |
| Coach management | Coaches | ✓ Employment types, payment models, availability |

## Gaps to Address

### GAP S1: Carnet Guest Entry & Usage Tracking (HIGH PRIORITY)
**Problem:** Carnets are issued to members but there's no mechanism to track when a guest actually uses an invitation entry. Members get an "invitation book" — they should be able to bring friends who can use club facilities (free-time only: pool free_swim, court bookings, ping pong, etc.) using their carnet allocation.

**Requirements:**
- Each carnet has a configurable number of guest entries (e.g., 10 invitations per carnet)
- When a guest enters using a member's carnet, the system records: which member's carnet, guest name/phone, entry time, which facility, which activity
- Guest entries are limited to free-time/recreational activities only (no academy/training)
- Guest pricing may differ from member pricing
- Members can see their remaining invitation balance
- Admin can view all guest entries per carnet, per member, per date range

**Implementation:**
```sql
-- Add invitation tracking to carnets
ALTER TABLE carnets ADD COLUMN total_invitations INT UNSIGNED NOT NULL DEFAULT 10;
ALTER TABLE carnets ADD COLUMN used_invitations INT UNSIGNED NOT NULL DEFAULT 0;

-- Guest entry log
CREATE TABLE carnet_guest_entries (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    carnet_id BIGINT UNSIGNED NOT NULL,
    member_id BIGINT UNSIGNED NOT NULL,
    guest_name VARCHAR(200) NOT NULL,
    guest_phone VARCHAR(30) NULL,
    guest_national_id VARCHAR(20) NULL,
    entry_date DATE NOT NULL,
    entry_time TIME NOT NULL,
    exit_time TIME NULL,
    facility_id BIGINT UNSIGNED NULL,
    activity_type VARCHAR(50) NOT NULL COMMENT 'free_swim, court_booking, recreation',
    reservation_id BIGINT UNSIGNED NULL COMMENT 'linked reservation if applicable',
    amount_paid DECIMAL(10,2) NOT NULL DEFAULT 0,
    payment_id BIGINT UNSIGNED NULL,
    notes TEXT NULL,
    recorded_by BIGINT UNSIGNED NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_cge_carnet (carnet_id),
    INDEX idx_cge_member (member_id),
    INDEX idx_cge_date (entry_date),
    CONSTRAINT fk_cge_carnet FOREIGN KEY (carnet_id) REFERENCES carnets(id),
    CONSTRAINT fk_cge_member FOREIGN KEY (member_id) REFERENCES members(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```

**Module changes:**
- Carnets module: add `guest-entry` route, controller action, view
- Reservations module: add `booker_type = 'carnet_guest'` support
- PoolManagement: allow `carnet_guest` booking type for free_swim slots
- Pricing: guest-via-carnet fee configuration

---

### GAP S2: Automated Notification Triggers (HIGH PRIORITY)
**Problem:** The Notifications module has the SMS sending infrastructure but no automated triggers. Players/members should receive notifications about session changes, medical expiry, payment reminders, etc.

**Requirements:**
- Medical certificate expiry approaching (7 days, 3 days, expired)
- Training session cancelled/rescheduled
- Subscription payment due reminder (5 days before, on due date, overdue)
- Group change/transfer confirmation
- Reservation confirmation/reminder (day before)
- Carnet invitation balance low (2 remaining)
- Academy announcements
- Membership renewal reminder
- Attendance summary (weekly/monthly)
- Pool schedule change notification

**Implementation:**
```sql
CREATE TABLE notification_triggers (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    trigger_code VARCHAR(50) NOT NULL UNIQUE,
    trigger_name_ar VARCHAR(200) NOT NULL,
    event_name VARCHAR(100) NOT NULL COMMENT 'EventBus event to listen to',
    template_id BIGINT UNSIGNED NULL,
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    channel VARCHAR(20) NOT NULL DEFAULT 'sms' COMMENT 'sms, push, both',
    config_json JSON NULL COMMENT 'timing config: days_before, repeat, etc.',
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_nt_event (event_name),
    INDEX idx_nt_active (is_active)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE notification_subscriptions (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    player_id BIGINT UNSIGNED NULL,
    member_id BIGINT UNSIGNED NULL,
    trigger_code VARCHAR(50) NOT NULL,
    is_opted_in TINYINT(1) NOT NULL DEFAULT 1,
    channel_preference VARCHAR(20) NULL DEFAULT 'sms',
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_ns_player (player_id),
    INDEX idx_ns_member (member_id),
    INDEX idx_ns_trigger (trigger_code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```

**EventBus listeners to add in Notifications/bootstrap.php:**
- `session.cancelled` → notify enrolled players
- `session.rescheduled` → notify enrolled players
- `medical.expiry_approaching` → notify player (cron-driven)
- `subscription.payment_due` → remind player (cron-driven)
- `group.player_transferred` → notify player of new group
- `reservation.confirmed` → confirm to booker
- `reservation.reminder` → day-before reminder (cron-driven)
- `carnet.low_balance` → notify member (triggered on usage)
- `membership.renewal_due` → remind member (cron-driven)

**Cron job additions:** Add scheduled checks in `cli.php cron` for time-based triggers (medical expiry, payment due dates, reservation reminders).

---

### GAP S3: Enhanced Facility Dashboard with Full Date Range & PDF Export (MEDIUM PRIORITY)
**Problem:** Current FacilityDashboards only supports day/week/month/custom filters. The admin wants: Daily, Weekly, Monthly, Yearly, 5 Years filters + downloadable PDF report.

**Requirements:**
- Add "yearly" and "5 years" filter options
- Financial details: total revenue, revenue by activity type, revenue by booker type, revenue by payment method
- User details: total unique visitors, new vs returning, members vs guests, peak hours
- Occupancy rate by time slot
- Coach utilization stats
- PDF export of the full dashboard with the current filter applied

**Implementation:**
- Extend `FacilityDashboardController@show` with `yearly` and `5years` filter modes
- Add `FacilityDashboardController@exportPdf` endpoint
- Create PDF generation service using the existing template engine (render HTML → convert to PDF using wkhtmltopdf or dompdf)
- Add revenue breakdown by: activity_type, booker_type, payment_method
- Add user analytics: unique visitors, member vs non-member ratio, peak hours heatmap

**Routes to add:**
```php
['GET', '/facilities/{id:\d+}/dashboard/export', 'FacilityDashboards\Controllers\FacilityDashboardController@exportPdf', ['auth'], 'facility.dashboard'],
```

**Schema for pool-specific dashboard (extend PoolDashboardController similarly):**
- Same extended filters (yearly, 5-year)
- Lane-specific revenue
- Academy session revenue vs free_swim revenue
- Coach performance (sessions taught, attendance rate)
- PDF export

---

### GAP S4: Membership-Based Access Control & Members-Only Time Slots (MEDIUM PRIORITY)
**Problem:** Pool/facility time slots should distinguish between "members-only" times and "open" times. Members get special pricing in all activities. The system needs to enforce this at booking time.

**Requirements:**
- Facilities can mark specific time slots as "members_only"
- During members-only time, only members (with active membership + valid card) can enter/book
- Members get member-specific pricing across all activities (pool, courts, recreation)
- Non-members pay higher rates during open times
- Carnet guests follow guest pricing (configurable: same as member or separate tier)

**Implementation:**
```sql
ALTER TABLE facility_time_slots ADD COLUMN access_type VARCHAR(20) NOT NULL DEFAULT 'open' COMMENT 'open, members_only, vip';
ALTER TABLE facility_time_slots ADD COLUMN member_price DECIMAL(10,2) NULL COMMENT 'Override price for members';
ALTER TABLE facility_time_slots ADD COLUMN guest_price DECIMAL(10,2) NULL COMMENT 'Override price for carnet guests';
```

**Service changes:**
- `FacilityPricingService`: add membership check → apply member/guest/public pricing tier
- `ReservationService@store`: validate access_type against booker_type
- `PoolBookingController@store`: check membership validity for members-only slots

---

### GAP S5: Pool Grid Drag-Select UI Enhancement (MEDIUM PRIORITY)
**Problem:** Admin wants to select multiple cells using mouse drag, or select full lanes horizontally/vertically, then assign trainer/academy/trainees to them. The backend supports this (zone_selection_type: cells/row/column/all + zone_selection_json) but the frontend needs an interactive drag-select UI.

**Requirements:**
- Visual grid representation of the pool (rows × columns matching physical dimensions)
- Click to select single cell
- Click + drag to select multiple cells (rectangular selection)
- Click lane header to select full horizontal lane
- Click column header to select full vertical lane
- Selected cells highlight in a chosen color
- After selection: modal/form to assign trainer, academy, age group, gender, max occupants, time slot
- Real-time visual feedback showing which zones are occupied/free/conflicting
- Color coding by academy/trainer/activity type

**Implementation:**
- New JavaScript component in FacilityGrids/Views using vanilla JS (no framework — matches project convention)
- Mouse events: `mousedown` → start selection, `mousemove` → extend selection, `mouseup` → finalize
- AJAX POST to existing `/facility-grids/{id}/schedules` endpoint
- Conflict detection via existing `/facility-grids/{id}/schedules/conflicts` API

---

### GAP S6: Player Evaluation & Skill Rating System (LOW PRIORITY)
**Problem:** Sessions module has `type = 'assessment'` but there's no structured scoring/rating model to formally evaluate players and recommend group placement.

**Requirements:**
- Configurable evaluation criteria per sport (speed, technique, endurance, teamwork, etc.)
- Numeric scoring (1-10) or categorical (beginner/intermediate/advanced/elite)
- Evaluation history per player per discipline
- Coach submits evaluation → system suggests group placement based on score + age + gender preferences
- Player can view their progression over time

**Implementation:**
```sql
CREATE TABLE evaluation_criteria (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    discipline_id BIGINT UNSIGNED NOT NULL,
    criterion_name_ar VARCHAR(200) NOT NULL,
    criterion_name_en VARCHAR(200) NULL,
    max_score INT NOT NULL DEFAULT 10,
    weight DECIMAL(3,2) NOT NULL DEFAULT 1.00,
    sort_order INT NOT NULL DEFAULT 0,
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_ec_discipline (discipline_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE player_evaluations (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    player_id BIGINT UNSIGNED NOT NULL,
    discipline_id BIGINT UNSIGNED NOT NULL,
    session_id BIGINT UNSIGNED NULL COMMENT 'assessment session if applicable',
    evaluator_coach_id BIGINT UNSIGNED NULL,
    evaluation_date DATE NOT NULL,
    overall_score DECIMAL(5,2) NULL,
    skill_level VARCHAR(20) NULL COMMENT 'beginner, intermediate, advanced, elite',
    recommended_group_type VARCHAR(20) NULL,
    recommended_group_id BIGINT UNSIGNED NULL,
    scores_json JSON NOT NULL COMMENT '[{criterion_id, score, notes}]',
    coach_notes TEXT NULL,
    status VARCHAR(20) NOT NULL DEFAULT 'draft' COMMENT 'draft, submitted, approved',
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_pe_player (player_id),
    INDEX idx_pe_discipline (discipline_id),
    INDEX idx_pe_date (evaluation_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```

---

### GAP S7: Pool Monthly Plan Naming & Cloning (LOW PRIORITY)
**Problem:** Monthly plans exist via `plan_month` column but there's no formal "plan" entity that groups all schedules for a month and gives it a name like "خطة حمام السباحة - يناير". Also no ability to clone last month's plan as a starting point for the new month.

**Requirements:**
- Named monthly plans: "Swimming Pool Plan - January 2026"
- Plan status: draft → active → archived
- Clone plan from previous month (copy all zone schedules)
- Diff view: what changed between this month and last month
- Working days configuration per plan (exclude Fridays or custom)
- Day/night hours definition per day of week

**Implementation:**
```sql
CREATE TABLE facility_monthly_plans (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    grid_id BIGINT UNSIGNED NOT NULL,
    plan_month VARCHAR(7) NOT NULL COMMENT 'YYYY-MM',
    plan_name_ar VARCHAR(200) NOT NULL,
    plan_name_en VARCHAR(200) NULL,
    status VARCHAR(20) NOT NULL DEFAULT 'draft' COMMENT 'draft, active, archived',
    working_days_json JSON NOT NULL DEFAULT '["1","2","3","4","5","6"]' COMMENT 'day numbers 0-6',
    day_hours_start TIME NOT NULL DEFAULT '06:00:00',
    day_hours_end TIME NOT NULL DEFAULT '14:00:00',
    night_hours_start TIME NOT NULL DEFAULT '14:00:00',
    night_hours_end TIME NOT NULL DEFAULT '22:00:00',
    cloned_from_id BIGINT UNSIGNED NULL,
    notes TEXT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    created_by BIGINT UNSIGNED NULL,
    UNIQUE KEY uq_fmp_grid_month (grid_id, plan_month),
    INDEX idx_fmp_status (status),
    CONSTRAINT fk_fmp_grid FOREIGN KEY (grid_id) REFERENCES facility_grids(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Link existing zone schedules to plan
ALTER TABLE facility_zone_schedules ADD COLUMN plan_id BIGINT UNSIGNED NULL AFTER plan_month;
ALTER TABLE facility_zone_schedules ADD INDEX idx_fzs_plan_id (plan_id);
```

---

## Cross-Module Integration Map

```
                    ┌────────────────────┐
                    │   Notifications    │
                    │ (automated triggers)│
                    └────────┬───────────┘
                             │ EventBus listeners
    ┌────────────────────────┼─────────────────────────┐
    │                        │                         │
    ▼                        ▼                         ▼
┌─────────┐          ┌─────────────┐          ┌──────────────┐
│Sessions │          │PlayerAffairs│          │ActivitySubscr.│
│attendance│─────────▶│medical expiry│─────────▶│payment due   │
│cancelled │          │card status   │          │pricing       │
└────┬────┘          └──────┬──────┘          └──────┬───────┘
     │                      │                        │
     ▼                      ▼                        ▼
┌─────────┐          ┌─────────────┐          ┌──────────────┐
│Coaches  │          │   Carnets   │          │   Pricing    │
│scheduling│         │guest entries │          │member/guest  │
│payments │          │usage tracking│          │tier pricing  │
└─────────┘          └──────┬──────┘          └──────────────┘
                            │
                            ▼
                    ┌───────────────┐
                    │  Reservations │
                    │carnet_guest   │
                    │booker_type    │
                    └───────┬───────┘
                            │
                            ▼
                    ┌───────────────┐          ┌──────────────┐
                    │FacilityGrids  │          │FacilityDash. │
                    │drag-select UI │──────────▶│yearly/5yr    │
                    │monthly plans  │          │PDF export    │
                    └───────────────┘          └──────────────┘
```

## Accounting Integration Points

All financial events from sports activities must post to the General Ledger via EventBus:

| Event | GL Debit | GL Credit | Existing? |
|-------|----------|-----------|-----------|
| Activity subscription paid | Cash/Bank | Revenue - Sports Activities | ✓ via payment.completed |
| Reservation booking paid | Cash/Bank | Revenue - Facility Rentals | ✓ via payment.completed |
| Pool booking paid | Cash/Bank | Revenue - Pool | ✓ via payment.completed |
| Guest entry via carnet paid | Cash/Bank | Revenue - Guest Fees | **NEW** |
| Coach monthly payment | Expense - Coaching | Cash/Bank | **NEW** |
| Academy settlement (revenue share) | Revenue - Academy | Cash/Bank (academy payout) | ✓ via academy settlement |
| Carnet replacement fee | Cash/Bank | Revenue - Carnet Services | ✓ via payment_request |

**New accounting events to wire:**
1. `carnet_guest.entry_paid` → post journal entry for guest fee revenue
2. `coach.payment_processed` → post journal entry for coaching expense
3. All new financial events should follow existing pattern in `Accounting/bootstrap.php`

---

## Implementation Priority for Sports Enhancements

```
GAP S1 (Carnet Guest Entries)        ← HIGH: enables invitation book usage   [1-2 weeks]
  ↓
GAP S2 (Notification Triggers)       ← HIGH: players need to be informed     [2-3 weeks]
  ↓
GAP S3 (Dashboard + PDF Export)      ← MEDIUM: admin reporting needs         [1-2 weeks]
  ↓
GAP S4 (Members-Only Access)         ← MEDIUM: pricing/access enforcement    [1 week]
  ↓
GAP S5 (Grid Drag-Select UI)         ← MEDIUM: UX improvement for pool admin [1-2 weeks]
  ↓
GAP S6 (Player Evaluation System)    ← LOW: formal scoring model             [1-2 weeks]
  ↓
GAP S7 (Monthly Plan Naming/Clone)   ← LOW: plan management convenience     [1 week]
```

**Total estimated: 8-13 weeks for all sports enhancements**

---

## Architecture Notes

All new features should follow existing conventions:
- Module structure: `app/Modules/{Name}/` with Controllers, Models, Services, Views
- Route registration in `Routes.php`
- Permissions registered in `bootstrap.php`
- Events dispatched for cross-module integration (especially GL posting)
- Arabic-first UI with RTL layout
- Plain PDO queries (no ORM relations)
- Migration naming: `Phase_NN_NNN_description.php`
