# POS System - Implementation Plan

## Overview
This document outlines the step-by-step implementation plan for the enhanced POS system features.

## Implementation Phases

### Phase 1: Foundation & Database Schema ✅
**Goal**: Set up database structure and basic product configuration

#### Backend Tasks:
1. ✅ Add `sell_on_pos` column to products table
2. ✅ Add fulfillment type to sales table
3. ✅ Add quantity tracking columns to sale_items
4. ✅ Add payment tender columns (tender_number, mpesa fields, card_reference)
5. ✅ Create settings table for configurable policies (deposit %, M-Pesa timeout, etc.)
6. ✅ Add indexes for performance

#### Frontend Tasks:
1. ✅ Update Product model/types to include `sell_on_pos`
2. ✅ Update Sale/Payment types to support new fields

**Estimated Time**: 2-3 hours

---

### Phase 2: Stock Checking & Cart Warnings ✅
**Goal**: Real-time stock validation and user notifications

#### Backend Tasks:
1. ✅ Create endpoint: `GET /api/products/:id/availability`
   - Returns: `available_qty`, `reserved_qty`, `total_qty`
2. ✅ Create endpoint: `POST /api/sales/check-stock` (bulk check)
   - Input: `[{product_id, variant_id, quantity}, ...]`
   - Output: `[{product_id, requested, available, shortfall, status}, ...]`
3. ✅ Update product listing to include real-time stock
4. ✅ Add stock checking middleware/utility function

#### Frontend Tasks:
1. ✅ Add stock check API client functions
2. ✅ Update ProductGrid to show stock badges
3. ✅ Add warning modal when adding items with insufficient stock
4. ✅ Update Cart component to show stock warnings
5. ✅ Add visual indicators (✅ In Stock, ⚠️ Low Stock, 🔴 Out of Stock, 📋 Preorder)

**Estimated Time**: 4-5 hours

---

### Phase 3: Auto-Split Fulfillment ✅
**Goal**: Automatically split sales into immediate sale + preorder

#### Backend Tasks:
1. ✅ Update `createSale` service to:
   - Check stock for each item
   - Split items: available → sale, shortfall → preorder
   - Create sale_items with `quantity_fulfilled` and `quantity_preordered`
   - Create separate ORDER records for preordered items
2. ✅ Add fulfillment type logic:
   - `POS_SALE`: All items available
   - `SPLIT_FULFILLMENT`: Mix of available + preordered
   - `ORDER`: All items preordered
3. ✅ Apply deposit policy to preorders
4. ✅ Update inventory deduction logic (only deduct available qty)
5. ✅ Add preorder fulfillment endpoint: `POST /api/sales/preorders/:id/fulfill`

#### Frontend Tasks:
1. ✅ Update cart to show split items visually
2. ✅ Separate "Sold" vs "Preordered" line items in cart
3. ✅ Show preorder summary in checkout
4. ✅ Display deposit requirement
5. ✅ Update sale creation to handle split responses

**Estimated Time**: 6-8 hours

---

### Phase 4: Split Payments (Max 2 Tenders) ✅
**Goal**: Support multiple payment methods per sale

#### Backend Tasks:
1. ✅ Update payment validation:
   - Allow multiple payments per sale (max 2)
   - Validate total tenders ≥ sale total (or deposit)
   - Track tender_number (1 or 2)
2. ✅ Update payment creation:
   - Accept array of payments or single payment
   - Calculate change only from cash tenders
   - Validate change amount
3. ✅ Add payment status tracking:
   - `PENDING`, `CONFIRMED`, `FAILED`, `RETRYING`
4. ✅ Update sale completion logic:
   - Only mark sale as PAID when all payments confirmed
   - Handle partial payments for preorders

#### Frontend Tasks:
1. ✅ Update PaymentModal to support multiple tenders
2. ✅ Add "Add Tender" button (max 2)
3. ✅ Implement tender entry form (method, amount, phone for M-Pesa)
4. ✅ Show tender summary table
5. ✅ Calculate and display change (cash only)
6. ✅ Show remaining amount to be paid
7. ✅ Disable "Complete Payment" until all tenders confirmed

**Estimated Time**: 6-7 hours

---

### Phase 5: M-Pesa STK Push Integration ✅
**Goal**: Real-time M-Pesa payments via Daraja API

#### Backend Tasks:
1. ✅ Set up Daraja API client:
   - Install/configure `daraja-node` or similar
   - Add credentials to environment variables
   - Create service: `services/payments/mpesa.js`
2. ✅ Implement STK Push:
   - `POST /api/payments/mpesa/stk-push`
   - Generate transaction reference
   - Send STK Push request to Daraja
   - Store request metadata (CheckoutRequestID, etc.)
   - Return status to frontend
3. ✅ Implement callback handler:
   - `POST /api/payments/mpesa/callback`
   - Parse Safaricom callback
   - Update payment status based on ResultCode
   - Notify frontend (via WebSocket or polling)
4. ✅ Add retry logic:
   - Timeout handling (60 seconds default)
   - Retry mechanism (max 1 retry)
   - Fallback to C2B after retry fails
5. ✅ Add payment status polling endpoint:
   - `GET /api/payments/:id/status`
   - For frontend to check payment status

#### Frontend Tasks:
1. ✅ Add M-Pesa STK Push UI:
   - Phone number input
   - "Request Payment" button
   - Loading spinner with countdown timer
   - Status display (waiting, confirmed, timeout)
2. ✅ Implement payment status polling:
   - Poll every 2-3 seconds while pending
   - Update UI when confirmed
   - Handle timeout/retry
3. ✅ Add retry button if timeout
4. ✅ Show success/error messages

**Estimated Time**: 8-10 hours

---

### Phase 6: M-Pesa C2B Fallback ✅
**Goal**: Manual M-Pesa payment when STK Push fails

#### Backend Tasks:
1. ✅ Implement C2B payment generation:
   - `POST /api/payments/mpesa/c2b`
   - Generate Paybill number + Account Number
   - Store reference for matching
2. ✅ Implement C2B callback handler:
   - Match incoming payment to pending payment
   - Update payment status
3. ✅ Add C2B polling option:
   - `GET /api/payments/:id/c2b-status`
   - Check if payment received

#### Frontend Tasks:
1. ✅ Add "Use C2B" button when STK fails
2. ✅ Display Paybill details:
   - Paybill number
   - Account number (invoice/sale reference)
   - Amount
   - QR code (optional)
3. ✅ Add "Check Payment" button for manual verification
4. ✅ Show payment confirmation when matched

**Estimated Time**: 4-5 hours

---

### Phase 7: Manual Confirmation & RM Sales ✅
**Goal**: Manager overrides and RM sales support

#### Backend Tasks:
1. ✅ Add manual M-Pesa confirmation:
   - `POST /api/payments/mpesa/manual-confirm`
   - Requires manager/admin role
   - Validates transaction code
   - Updates payment status
   - Logs manager action
2. ✅ Add RM sales validation:
   - Check `sell_on_pos` flag
   - Require manager approval if flag is false
   - Log approval action
3. ✅ Add stock override:
   - `POST /api/sales/override-stock`
   - Requires manager/admin role
   - Allows negative stock sale
   - Logs reason for override

#### Frontend Tasks:
1. ✅ Add manager approval UI for RM sales
2. ✅ Add manual M-Pesa confirmation modal
3. ✅ Add stock override option (manager only)
4. ✅ Show approval badges/indicators

**Estimated Time**: 4-5 hours

---

### Phase 8: Category Filter Fix ✅
**Goal**: Fix category filtering in POS

#### Backend Tasks:
1. ✅ Verify categories API response format
2. ✅ Ensure category_id filtering works in products list
3. ✅ Add category_id validation

#### Frontend Tasks:
1. ✅ Debug category API call
2. ✅ Fix CategorySidebar category selection
3. ✅ Ensure ProductGrid updates when category changes
4. ✅ Test category filtering end-to-end

**Estimated Time**: 1-2 hours

---

### Phase 9: UI Polish & Settings ✅
**Goal**: Final UI improvements and configurable settings

#### Backend Tasks:
1. ✅ Create settings endpoints:
   - `GET /api/settings` - Get all settings
   - `PUT /api/settings/:key` - Update setting
2. ✅ Add default settings on startup
3. ✅ Add deposit calculation service

#### Frontend Tasks:
1. ✅ Create Settings UI for managers:
   - Deposit % configuration
   - M-Pesa timeout settings
   - RM sales policy
2. ✅ Add preorder summary component
3. ✅ Add fulfillment queue page (manager view)
4. ✅ Final UI polish (animations, transitions)
5. ✅ Mobile responsiveness improvements

**Estimated Time**: 5-6 hours

---

### Phase 10: Testing & Bug Fixes ✅
**Goal**: Comprehensive testing and bug fixes

#### Testing Tasks:
1. ✅ Unit tests for stock checking logic
2. ✅ Unit tests for split fulfillment
3. ✅ Unit tests for payment calculations
4. ✅ Integration tests for M-Pesa flow
5. ✅ E2E tests for checkout flow
6. ✅ Manual testing checklist:
   - Stock scenarios
   - Payment scenarios
   - M-Pesa scenarios
   - Role permissions

#### Bug Fixes:
- Fix any discovered issues
- Performance optimization
- Error handling improvements

**Estimated Time**: 6-8 hours

---

## Dependencies & Prerequisites

### External Services:
- ✅ Safaricom Daraja API credentials (sandbox for dev)
- ✅ Daraja API callback URL configured
- ✅ Environment variables set up

### Database:
- ✅ Migration scripts ready
- ✅ Backup strategy in place

### Frontend:
- ✅ React Query set up (already done)
- ✅ WebSocket or polling mechanism for payment status

---

## Implementation Order (Critical Path)

1. **Phase 1** → Foundation (must do first)
2. **Phase 8** → Category Fix (quick win, unblock testing)
3. **Phase 2** → Stock Checking (needed for Phase 3)
4. **Phase 3** → Auto-Split (needed for Phase 4)
5. **Phase 4** → Split Payments (needed for Phase 5)
6. **Phase 5** → M-Pesa STK Push
7. **Phase 6** → M-Pesa C2B Fallback
8. **Phase 7** → Manual Confirmations
9. **Phase 9** → Settings & Polish
10. **Phase 10** → Testing

---

## Estimated Total Time
- **Development**: ~50-60 hours
- **Testing**: ~8-10 hours
- **Total**: ~60-70 hours (1.5-2 weeks for a single developer)

---

## Quick Wins (Do First)
1. ✅ Category filter fix (1-2 hours) - Immediate user feedback
2. ✅ Product sell_on_pos flag (1 hour) - Simple, high impact
3. ✅ Stock checking in cart (2-3 hours) - Core feature

---

## Risk Mitigation
- **M-Pesa Integration**: Use sandbox first, test thoroughly before production
- **Stock Deduction**: Double-check logic to prevent inventory errors
- **Payment Handling**: Ensure idempotency to prevent double-charging
- **Data Integrity**: Transactions for all critical operations

---

## Success Criteria
- ✅ Cashier can see stock warnings when adding items
- ✅ System auto-splits available vs preordered items
- ✅ Split payments (max 2 tenders) works correctly
- ✅ M-Pesa STK Push works with retry
- ✅ C2B fallback works when STK fails
- ✅ Category filtering works reliably
- ✅ RM sales work with proper approval
- ✅ Manager can override stock when needed

