# System Modularization Guide

## 🎯 Modularization Principles

### Core Principle: Domain-Driven Design

Each module represents a business domain with clear boundaries and responsibilities.

---

## 📦 Module Structure Template

Each module follows this structure:

```
modules/{module-name}/
├── services/
│   └── index.js          # Business logic layer
├── controllers/
│   └── index.js          # Request handling layer
├── validations/
│   └── index.js          # Input validation rules
└── routes/
    └── index.js          # Route definitions
```

---

## 🔄 Data Flow Between Modules

### Example: Creating a Sale

```
Client Request
    ↓
Routes (sales/routes/index.js)
    ↓
Controller (sales/controllers/index.js)
    ↓
Service (sales/services/index.js)
    ↓
Inter-Module Service Calls:
  - inventory/service → Check stock
  - pricing/service → Get price
  - taxes/service → Calculate tax
  - discounts/service → Apply discount
  - shifts/service → Validate shift
    ↓
Service (sales/services/index.js) → Create Sale
    ↓
Database Models (via db object)
    ↓
Response via Controller
```

---

## 🚫 Anti-Patterns to Avoid

1. **Direct Model Access from Controllers:**
   ❌ Controller → Model
   ✅ Controller → Service → Model

2. **Cross-Module Model Imports:**
   ❌ Import models from other modules directly
   ✅ Import services from other modules

3. **Business Logic in Controllers:**
   ❌ Controller contains complex logic
   ✅ Controller delegates to Service

4. **Validation in Services:**
   ❌ Service validates request format
   ✅ Validation middleware validates, Service validates business rules

---

## ✅ Best Practices

1. **Service Layer:**
   - Contains all business logic
   - Can call other services
   - Returns data, not HTTP responses
   - Throws custom errors

2. **Controller Layer:**
   - Handles HTTP request/response
   - Calls services
   - Uses response utilities
   - Catches errors and sends HTTP responses

3. **Validation Layer:**
   - Validates input format/structure
   - Uses express-validator
   - Runs before controller

4. **Route Layer:**
   - Defines endpoints
   - Applies middlewares (auth, validation)
   - Maps routes to controllers

---

## 🔗 Module Communication Patterns

### Pattern 1: Direct Service Call

```javascript
// In sales/service
const inventoryService = require('../inventory/services');
const stock = await inventoryService.checkAvailability(productId, quantity);
```

### Pattern 2: Event-Driven (Future Enhancement)

```javascript
// In sales/service after sale creation
eventEmitter.emit('sale.created', { saleId, customerId });

// In inventory/service
eventEmitter.on('sale.created', async (data) => {
  // Update inventory
});
```

---

## 📊 Module Responsibility Matrix

| Module | Primary Responsibility | Secondary |
|--------|----------------------|-----------|
| auth | User authentication | Authorization checks |
| products | Product CRUD | Product variants, categories |
| categories | Category hierarchy | Product categorization |
| pricing | Price management | Price lookups |
| taxes | Tax calculation | Tax exemptions |
| discounts | Discount rules | Discount application |
| inventory | Stock management | Inventory movements |
| sales | Sale creation | Sale lifecycle |
| payments | Payment processing | Payment tracking |
| customers | Customer CRUD | Customer relationships |
| procurement | PO/GRN | Stock addition |
| production | BOM/Production | Stock transformation |
| returns | Return processing | Credit notes |
| shifts | Shift management | Cash tracking |
| fiscal | KRA integration | Fiscal receipts |
| reports | Data aggregation | Report generation |

---

This modular structure ensures:
- ✅ Clear separation of concerns
- ✅ Easy testing (mock services)
- ✅ Reusable components
- ✅ Maintainable codebase
- ✅ Scalable architecture

