# Backend Development Phases & Batches

## 🎯 Development Strategy

This document outlines the phased approach to building the Smart POS backend system. Each phase builds upon the previous one, ensuring a stable foundation before adding complexity.

---

## 📊 Phase Overview

| Phase | Focus | Duration Estimate | Priority |
|-------|-------|------------------|----------|
| **Phase 0** | Foundation Setup | 1-2 days | Critical |
| **Phase 1** | Core Authentication & Users | 2-3 days | Critical |
| **Phase 2** | Product Management | 3-4 days | Critical |
| **Phase 3** | Basic Inventory | 4-5 days | Critical |
| **Phase 4** | Basic Sales & POS | 5-7 days | Critical |
| **Phase 5** | Payments Integration | 3-4 days | High |
| **Phase 6** | Inventory Enhancements | 3-4 days | High |
| **Phase 7** | Enterprise Features (Pricing, Taxes, Categories) | 5-7 days | High |
| **Phase 8** | Discounts & Promotions | 3-4 days | Medium |
| **Phase 9** | Procurement & GRN | 4-5 days | Medium |
| **Phase 10** | Production Management | 4-5 days | Medium |
| **Phase 11** | Returns & Credit Notes | 3-4 days | High |
| **Phase 12** | Shift & Cash Management | 3-4 days | High |
| **Phase 13** | KRA eTIMS Integration | 4-5 days | High |
| **Phase 14** | Customer Management | 2-3 days | Medium |
| **Phase 15** | Reporting & Analytics | 5-7 days | Medium |
| **Phase 16** | Testing & Optimization | 5-7 days | Critical |

**Total Estimated Duration:** 60-85 days (12-17 weeks)

---

## 🔧 Phase 0: Foundation Setup

**Goal:** Establish core infrastructure and development environment

**Tasks:**
- ✅ Database models created (DONE)
- ✅ Project structure established (DONE)
- ✅ Environment configuration (DONE)
- ✅ Error handling utilities (DONE)
- ✅ Logging setup (DONE)
- ✅ Response utilities (DONE)
- ✅ Authentication middleware (DONE)
- ✅ Validation middleware (DONE)
- Set up testing framework (Jest/Mocha)
- Create seed data scripts
- Set up API documentation (Swagger/OpenAPI)
- Configure CI/CD pipeline (optional)

**Deliverables:**
- Working server startup
- Database connection established
- Basic health check endpoint
- Development environment fully configured

**Dependencies:** None

**Acceptance Criteria:**
- Server starts without errors
- Database connects successfully
- All tables created
- Health check returns 200 OK

---

## 🔐 Phase 1: Core Authentication & Users

**Goal:** Implement user authentication and authorization system

**Tasks:**
- Implement auth service (login, loginWithPin, getUserById, hasPermission)
- Create auth controllers (login, loginWithPin, getProfile, refreshToken)
- Create auth validations (login, loginWithPin)
- Create auth routes (POST /auth/login, POST /auth/login-pin, GET /auth/profile)
- Create user management service (createUser, updateUser, deleteUser, listUsers)
- Create user controllers (CRUD operations)
- Create user validations
- Create user routes
- Implement role-based middleware (requireRole, requireAnyRole)
- Create seed script for default admin user
- Add password reset functionality (optional)

**Deliverables:**
- User can login with username/password
- User can login with username/PIN (quick POS login)
- JWT token generation and validation
- Role-based access control working
- User CRUD operations
- System logs user actions

**Dependencies:** Phase 0

**Acceptance Criteria:**
- Login endpoint returns JWT token
- Protected routes require valid token
- Role-based access works correctly
- Password hashing verified
- User CRUD operations functional

---

## 📦 Phase 2: Product Management

**Goal:** Core product and variant management

**Tasks:**
- Implement product service (create, read, update, delete, list)
- Implement product variant service
- Create product controllers (CRUD)
- Create product validations
- Create product routes (RESTful endpoints)
- Implement product search/filtering
- Add product image upload (basic)
- Create seed data for sample products

**Deliverables:**
- Product CRUD operations
- Product variant CRUD operations
- Product listing with pagination
- Product search functionality
- SKU uniqueness validation

**Dependencies:** Phase 1 (authentication)

**Acceptance Criteria:**
- Can create/read/update/delete products
- Product variants work correctly
- SKU uniqueness enforced
- Product search returns results
- Product listing paginated

---

## 📊 Phase 3: Basic Inventory (Quantity-Based)

**Goal:** Implement quantity-based inventory tracking (Layer 1)

**Tasks:**
- Implement inventory service (getQuantity, adjustQuantity, checkAvailability)
- Create inventory controllers (getInventory, adjustInventory)
- Create inventory validations
- Create inventory routes
- Implement reorder level checks
- Create inventory movement service (recordMovement)
- Add inventory listing with filters
- Create inventory adjustment functionality (with role check)

**Deliverables:**
- Inventory quantity tracking
- Inventory adjustments (manager/admin only)
- Reorder level alerts
- Inventory movements logged
- Inventory listing/querying

**Dependencies:** Phase 2 (products)

**Acceptance Criteria:**
- Can check product inventory quantity
- Inventory adjustments work correctly
- Inventory movements created on changes
- Reorder alerts trigger correctly
- Only authorized users can adjust inventory

---

## 🛒 Phase 4: Basic Sales & POS (Core POS Functionality)

**Goal:** Implement basic POS sales operations

**Tasks:**
- Implement sale service (createSale, getSale, listSales, cancelSale)
- Implement sale item service (addItem, removeItem, updateQuantity)
- Create sale controllers (create, read, update, cancel)
- Create sale validations
- Create sale routes
- Implement inventory reservation (on sale creation)
- Implement inventory release (on sale cancellation)
- Calculate sale totals (subtotal, tax using default_vat_rate, total)
- Generate invoice numbers
- Add sale listing with filters (date, customer, status)
- Link sales to cashier (user_id)

**Deliverables:**
- Create POS sale
- Add/remove items from sale
- Calculate totals
- Cancel sale (before payment)
- Inventory reservation/release
- Invoice number generation
- Sale listing and filtering

**Dependencies:** Phase 2 (products), Phase 3 (inventory)

**Acceptance Criteria:**
- Can create sale with items
- Totals calculated correctly
- Inventory reserved on sale creation
- Sale can be cancelled (inventory released)
- Invoice numbers unique
- Sales linked to cashier

---

## 💳 Phase 5: Payments Integration

**Goal:** Implement payment processing

**Tasks:**
- Implement payment service (createPayment, processPayment, listPayments)
- Create payment controllers (create, process, list)
- Create payment validations
- Create payment routes
- Integrate Paystack API (initialize, verify transaction)
- Implement cash payment processing
- Implement mobile money payment (mock/stub)
- Implement payment status tracking
- Link payments to sales
- Calculate remaining balance on sale
- Auto-update sale status when fully paid
- Create payment webhook handler (Paystack)

**Deliverables:**
- Multiple payment methods (Cash, Paystack, Mobile)
- Payment processing
- Payment status tracking
- Sale payment tracking
- Auto-sale status update on full payment

**Dependencies:** Phase 4 (sales)

**Acceptance Criteria:**
- Can process cash payments
- Paystack integration working
- Payment status updates correctly
- Sale status changes to PAID when fully paid
- Multiple partial payments supported

---

## 🔄 Phase 6: Inventory Enhancements (UID-Based)

**Goal:** Implement UID-based inventory tracking (Layer 2)

**Tasks:**
- Implement inventory item service (createItem, getByUID, updateStatus, scanItem)
- Create inventory item controllers (create, getByUID, updateStatus)
- Create inventory item validations
- Create inventory item routes
- Implement UID generation service
- Implement barcode/QR code generation
- Sync quantity and UID layers
- Update sale service to link sale items to inventory items
- Implement inventory item status transitions
- Add UID scanning endpoint

**Deliverables:**
- UID-based inventory tracking
- UID generation
- Barcode/QR code support
- Sale items linked to inventory items
- Inventory item status management

**Dependencies:** Phase 3 (basic inventory), Phase 4 (sales)

**Acceptance Criteria:**
- Can create inventory items with UIDs
- Can scan item by UID/barcode
- Sale items linked to specific UIDs
- Quantity and UID layers stay in sync
- Status transitions work correctly

---

## 🏷️ Phase 7: Enterprise Features (Pricing, Taxes, Categories)

**Goal:** Implement pricing, tax management, and category systems

**Sub-Phase 7A: Categories**
- Implement category service (CRUD, hierarchical navigation)
- Create category controllers and routes
- Implement product-category assignment
- Create category validations

**Sub-Phase 7B: Pricing**
- Implement price list service (CRUD)
- Implement product price service (createPrice, getPrice, getPriceForCustomer)
- Create pricing controllers and routes
- Implement price lookup logic (customer price list → variant price → product price)
- Create pricing validations
- Add effective date handling

**Sub-Phase 7C: Taxes**
- Implement tax rate service (CRUD)
- Implement tax category service
- Implement tax exemption service
- Create tax calculation service (calculateTax)
- Create tax controllers and routes
- Integrate tax calculation into sale service
- Create tax validations

**Deliverables:**
- Category hierarchy management
- Product categorization
- Multiple price lists
- Customer-specific pricing
- Quantity-based pricing
- Tax rate management
- Tax category assignment
- Tax exemption handling
- Tax calculation in sales

**Dependencies:** Phase 2 (products), Phase 4 (sales)

**Acceptance Criteria:**
- Categories work hierarchically
- Products can be in multiple categories
- Price lookup works correctly
- Tax calculation accurate
- Exemptions applied correctly

---

## 🎁 Phase 8: Discounts & Promotions

**Goal:** Implement discount and promotion system

**Tasks:**
- Implement discount service (createDiscount, validateDiscount, applyDiscount)
- Implement discount rule service
- Create discount controllers (CRUD, apply)
- Create discount validations
- Create discount routes
- Integrate discount application into sale service
- Implement discount validation (dates, usage limits, rules)
- Track discount usage
- Implement discount calculation (percentage, fixed, buy-X-get-Y)

**Deliverables:**
- Discount code management
- Discount rule configuration
- Discount application in sales
- Usage tracking
- Discount validation

**Dependencies:** Phase 4 (sales), Phase 7 (pricing, categories)

**Acceptance Criteria:**
- Can create discounts with rules
- Discount codes work in sales
- Usage limits enforced
- Discount calculation correct
- Rules (product/category/customer) work

---

## 📥 Phase 9: Procurement & GRN

**Goal:** Implement purchase orders and goods receipt

**Tasks:**
- Implement vendor service (CRUD)
- Implement purchase order service (CRUD, status management)
- Implement GRN service (createGRN, processGRN)
- Create procurement controllers
- Create procurement validations
- Create procurement routes
- Integrate GRN with inventory (add stock on GRN)
- Generate inventory items with UIDs on GRN
- Support GRN without PO (open-market)
- Add GRN item cost tracking

**Deliverables:**
- Vendor management
- Purchase order management
- GRN creation and processing
- Stock addition via GRN
- UID generation on GRN

**Dependencies:** Phase 2 (products), Phase 6 (UID inventory)

**Acceptance Criteria:**
- Can create vendors
- Can create POs (optional)
- Can create GRN with/without PO
- Stock added correctly on GRN
- Inventory items created with UIDs
- Costs tracked in GRN items

---

## 🏭 Phase 10: Production Management

**Goal:** Implement BOM and production system

**Tasks:**
- Implement BOM service (createBOM, getBOM, updateBOM)
- Implement BOM item service
- Implement production order service (create, checkAvailability, confirmProduction)
- Create production controllers
- Create production validations
- Create production routes
- Implement RM inventory check before production
- Implement production confirmation (consume RM, create FG)
- Generate FG inventory items with UIDs
- Create production movements (PRODUCTION_CONSUME, PRODUCTION_OUTPUT)

**Deliverables:**
- BOM management
- Production order creation
- RM availability check
- Production confirmation
- FG creation from production
- RM consumption tracking

**Dependencies:** Phase 2 (products), Phase 6 (inventory)

**Acceptance Criteria:**
- Can create BOMs
- Production order checks RM availability
- Production confirmation consumes RM and creates FG
- Inventory movements created correctly
- Production is atomic (all or nothing)

---

## ↩️ Phase 11: Returns & Credit Notes

**Goal:** Implement return processing and credit notes

**Tasks:**
- Implement return service (createReturn, completeReturn, getReturn)
- Implement return item service
- Create return controllers
- Create return validations
- Create return routes
- Implement UID scanning for returns (validate belongs to original sale)
- Integrate returns with inventory (update status to RETURNED)
- Create return inventory movements
- Generate credit notes
- Link credit notes to fiscal receipts
- Calculate return amounts

**Deliverables:**
- Return creation and processing
- UID validation for returns
- Inventory update on return
- Credit note generation
- Return listing and tracking

**Dependencies:** Phase 4 (sales), Phase 6 (inventory)

**Acceptance Criteria:**
- Can create returns
- Returned UIDs validated
- Inventory updated correctly
- Credit notes generated
- Return amounts calculated correctly

---

## 👤 Phase 12: Shift & Cash Management

**Goal:** Implement cashier shift and cash drawer management

**Tasks:**
- Implement shift service (openShift, closeShift, getCurrentShift, getShift)
- Implement cash count service
- Create shift controllers
- Create shift validations
- Create shift routes
- Integrate shifts with sales (require shift for sales)
- Implement opening cash count
- Implement closing cash count
- Calculate cash discrepancy
- Add mid-shift cash counts
- Link sales to shifts

**Deliverables:**
- Shift open/close functionality
- Cash count tracking
- Cash discrepancy calculation
- Shift-based sales tracking
- Shift listing and reporting

**Dependencies:** Phase 1 (users), Phase 4 (sales)

**Acceptance Criteria:**
- Cashiers can open/close shifts
- Opening cash recorded
- Closing cash recorded with discrepancy
- Sales require open shift
- Cash counts tracked correctly

---

## 🧾 Phase 13: KRA eTIMS Integration

**Goal:** Integrate with KRA eTIMS for fiscal receipts

**Tasks:**
- Research KRA eTIMS API documentation
- Implement KRA API client service
- Implement fiscal receipt service (createFiscalReceipt, fiscaliseSale, fiscaliseReturn)
- Create fiscal controllers
- Create fiscal validations
- Create fiscal routes
- Implement async fiscalisation (queue system)
- Store KRA receipt numbers and QR codes
- Handle fiscalisation failures
- Support B2C and B2B receipts
- Store customer PIN in fiscal receipt (not customer table)

**Deliverables:**
- Fiscal receipt generation
- KRA API integration
- Async fiscalisation
- Receipt QR code storage
- Failure handling

**Dependencies:** Phase 4 (sales), Phase 11 (returns)

**Acceptance Criteria:**
- Can generate fiscal receipts
- KRA API calls successful
- Receipt numbers stored
- QR codes stored
- Failed fiscalisation handled gracefully

---

## 👥 Phase 14: Customer Management

**Goal:** Implement customer management (optional customers)

**Tasks:**
- Implement customer service (create, read, update, delete, list)
- Create customer controllers (CRUD)
- Create customer validations
- Create customer routes
- Integrate customer lookup in sales
- Link customers to price lists
- Support customer tax exemptions
- Add customer search
- Customer listing with filters

**Deliverables:**
- Customer CRUD operations
- Customer search
- Customer price list assignment
- Customer tax exemptions
- Customer-linked sales

**Dependencies:** Phase 7 (pricing, taxes)

**Acceptance Criteria:**
- Can create/read/update/delete customers
- Customer search works
- Price lists assigned correctly
- Tax exemptions work
- Sales can link to customers

---

## 📈 Phase 15: Reporting & Analytics

**Goal:** Implement reporting and analytics

**Tasks:**
- Implement report service (generateReport, getReportTypes)
- Create report controllers
- Create report routes
- Implement sales reports (by date, product, customer, cashier)
- Implement inventory reports (fast-moving, slow-moving, reorder alerts)
- Implement profit/loss reports
- Implement tax reports (for KRA)
- Implement shift reports
- Add report filters (date range, category, etc.)
- Export reports (CSV, PDF - optional)

**Deliverables:**
- Sales reports
- Inventory reports
- Financial reports
- Tax reports
- Shift reports
- Report filtering

**Dependencies:** All previous phases

**Acceptance Criteria:**
- Reports generate correctly
- Filters work properly
- Data aggregation accurate
- Report performance acceptable

---

## 🧪 Phase 16: Testing & Optimization

**Goal:** Comprehensive testing and performance optimization

**Tasks:**
- Write unit tests for services
- Write integration tests for API endpoints
- Write database transaction tests
- Performance testing (load testing)
- Database query optimization
- Index review and optimization
- API response time optimization
- Error handling review
- Security audit
- Documentation completion
- Code review and refactoring

**Deliverables:**
- Test suite (unit + integration)
- Performance benchmarks
- Optimized queries
- Security hardened
- Complete API documentation

**Dependencies:** All previous phases

**Acceptance Criteria:**
- Test coverage > 80%
- API response times < 200ms (average)
- No security vulnerabilities
- All edge cases handled
- Documentation complete

---

## 🚀 MVP (Minimum Viable Product) Scope

**For rapid deployment, focus on Phases 0-5:**

- Phase 0: Foundation
- Phase 1: Authentication
- Phase 2: Products
- Phase 3: Basic Inventory
- Phase 4: Basic Sales
- Phase 5: Payments

**MVP Features:**
- ✅ User login
- ✅ Product management
- ✅ Quantity-based inventory
- ✅ POS sales
- ✅ Cash payments
- ✅ Basic reporting

**MVP Duration:** ~15-20 days

---

## 📋 Development Best Practices Per Phase

### For Each Phase:

1. **Planning:**
   - Review architecture design
   - Identify dependencies
   - Break tasks into smaller units

2. **Development:**
   - Follow module structure (service → controller → routes)
   - Write validation rules
   - Handle errors properly
   - Add logging

3. **Testing:**
   - Test each function/service
   - Test API endpoints
   - Test edge cases
   - Test error scenarios

4. **Documentation:**
   - Update API documentation
   - Add code comments
   - Document business rules

5. **Review:**
   - Code review
   - Architecture compliance check
   - Performance check

---

## 🔄 Iterative Approach

**Recommended Development Flow:**

1. **Week 1-2:** Phases 0-1 (Foundation + Auth)
2. **Week 3-4:** Phases 2-3 (Products + Inventory)
3. **Week 5-7:** Phases 4-5 (Sales + Payments) → **MVP Ready**
4. **Week 8-9:** Phase 6 (Inventory UID)
5. **Week 10-12:** Phase 7 (Enterprise Features)
6. **Week 13:** Phase 8 (Discounts)
7. **Week 14-15:** Phases 9-10 (Procurement + Production)
8. **Week 16:** Phases 11-12 (Returns + Shifts)
9. **Week 17-18:** Phase 13 (KRA Integration)
10. **Week 19:** Phase 14 (Customers)
11. **Week 20-21:** Phase 15 (Reports)
12. **Week 22-23:** Phase 16 (Testing & Optimization)

---

## ✅ Phase Completion Criteria

Each phase is complete when:

1. ✅ All tasks in phase completed
2. ✅ All acceptance criteria met
3. ✅ Code reviewed
4. ✅ Tests written and passing
5. ✅ Documentation updated
6. ✅ No critical bugs
7. ✅ Integration with previous phases verified

---

This phased approach ensures:
- ✅ Stable foundation before adding complexity
- ✅ Testable increments
- ✅ Early MVP delivery
- ✅ Manageable development cycles
- ✅ Clear milestones and deliverables

