# Phase 13: KRA eTIMS Integration - COMPLETE ✅

## Overview
Phase 13 implements KRA eTIMS (Kenya Revenue Authority Electronic Tax Invoice Management System) integration for fiscal receipt generation. The system supports creating fiscal receipts, fiscalising sales and returns (credit notes), storing KRA receipt numbers and QR codes, and handling fiscalisation failures gracefully.

## Implementation Details

### 1. KRA API Client Service
**File:** `server/modules/kra-etims/services/kraClient.js`

Created a KRA eTIMS API client class:
- **getAuthToken**: Authenticates with KRA API and returns access token
  - Placeholder implementation (to be replaced with actual KRA authentication)
  - Handles authentication errors gracefully
- **fiscaliseSaleReceipt**: Sends sale receipt to KRA for fiscalisation
  - Prepares receipt data in format expected by KRA
  - Calls KRA API endpoint (placeholder - to be replaced with actual endpoint)
  - Returns receipt number, QR code, and fiscalised timestamp
  - Supports enable/disable flag via configuration
- **fiscaliseCreditNote**: Sends credit note to KRA for fiscalisation
  - Prepares credit note data
  - Calls KRA API endpoint for credit notes (placeholder)
  - Returns receipt number, QR code, and fiscalised timestamp

**Note**: The KRA client is a placeholder implementation. Replace the TODO sections with actual KRA eTIMS API calls based on official KRA eTIMS API documentation.

### 2. Fiscal Receipt Service
**File:** `server/modules/kra-etims/services/fiscalReceipts.js`

Implemented the following functions:

#### createFiscalReceipt
Creates a fiscal receipt record (before fiscalisation):
- Validates receipt category (SALE or CREDIT_NOTE)
- Validates receipt type (B2C or B2B)
- Validates sale_id or return_id based on category
- Ensures no duplicate fiscal receipts
- Creates FiscalReceipt with status PENDING
- Returns created receipt with associations

#### getFiscalReceipt
Retrieves a fiscal receipt by ID with complete associations:
- Includes sale with items (for SALE receipts)
- Includes return with items (for CREDIT_NOTE receipts)
- Returns receipt with all related data

#### listFiscalReceipts
Lists fiscal receipts with optional filters and pagination:
- Supports filtering by sale_id, return_id, receipt_category, receipt_type, fiscal_status
- Paginated results with metadata
- Ordered by creation date descending

#### fiscaliseSale
Fiscalises a sale by sending it to KRA eTIMS:
- Gets sale with items and products
- Determines receipt type (B2C if no customer, B2B if customer exists)
- Finds or creates fiscal receipt for the sale
- Prepares receipt data for KRA:
  - Formats items with product codes, names, quantities, prices, VAT rates
  - Calculates totals, taxes, discounts
  - Includes invoice number
- Calls KRA API to fiscalise
- Updates fiscal receipt with KRA response:
  - Stores receipt number (kra_receipt_no)
  - Stores QR code (qr_code)
  - Updates status to FISCALISED
  - Records fiscalised_at timestamp
- Handles failures: Updates status to FAILED if fiscalisation fails
- Supports async processing flag (for future queue implementation)
- All operations in a transaction for data consistency

#### fiscaliseReturn
Fiscalises a return by sending credit note to KRA eTIMS:
- Gets return with items and original sale
- Validates return is COMPLETED
- Ensures original sale is fiscalised
- Determines receipt type from original sale
- Finds or creates fiscal receipt for credit note
- Prepares credit note data for KRA:
  - Formats items with original sale item data
  - Calculates totals and taxes accurately
  - Includes original receipt number
  - Includes return reason
- Calls KRA API to fiscalise credit note
- Updates fiscal receipt with KRA response
- Handles failures gracefully
- Supports async processing flag

### 3. Receipt Data Preparation
**Function:** `prepareReceiptItems`

Formats sale/return items for KRA API:
- Maps items to KRA format with product codes, names, quantities, prices
- Calculates line totals and VAT amounts
- Includes all required fields for KRA eTIMS

### 4. Controllers
**File:** `server/modules/kra-etims/controllers/index.js`

Implemented controllers for:
- createFiscalReceipt: Creates fiscal receipt
- getFiscalReceipt: Retrieves fiscal receipt by ID
- listFiscalReceipts: Lists fiscal receipts with filters
- fiscaliseSale: Fiscalises a sale
- fiscaliseReturn: Fiscalises a return

All controllers:
- Use asyncHandler for error handling
- Extract data from request (body, params, query)
- Call appropriate service functions
- Return standardized responses
- Log operations

### 5. Validations
**File:** `server/modules/kra-etims/validations/index.js`

Implemented comprehensive validation rules for:
- createFiscalReceipt:
  - receipt_category (required, SALE or CREDIT_NOTE)
  - receipt_type (required, B2C or B2B)
  - sale_id (required if SALE category)
  - return_id (required if CREDIT_NOTE category)
  - customer_pin (optional, max 20 chars)
- getFiscalReceipt: receipt ID (required, positive integer)
- listFiscalReceipts: Optional filters (sale_id, return_id, receipt_category, receipt_type, fiscal_status, page, limit)
- fiscaliseSale: sale ID (required), customer_pin (optional), async (optional boolean)
- fiscaliseReturn: return ID (required), customer_pin (optional), async (optional boolean)

### 6. Routes
**File:** `server/modules/kra-etims/routes/index.js`

Implemented RESTful routes:
- `POST /api/kra-etims/receipts` - Create fiscal receipt (manager, system_admin)
- `GET /api/kra-etims/receipts` - List fiscal receipts (authenticated)
- `GET /api/kra-etims/receipts/:id` - Get fiscal receipt by ID (authenticated)
- `POST /api/kra-etims/sales/:saleId/fiscalise` - Fiscalise sale (cashier, manager, system_admin)
- `POST /api/kra-etims/returns/:returnId/fiscalise` - Fiscalise return (manager, system_admin)

All routes:
- Use authentication middleware
- Use role-based access control where appropriate
- Include request validation
- Have Swagger documentation

### 7. Routes Integration
**File:** `server/routes/index.js`

Added KRA eTIMS routes to main routes file:
- `router.use('/kra-etims', kraEtimsRoutes)`

### 8. Configuration
**File:** `server/config/app.js`

KRA eTIMS configuration already exists:
- `kra.apiUrl`: KRA API base URL
- `kra.apiKey`: KRA API key
- `kra.apiSecret`: KRA API secret
- `kra.oscuUrl`: OSCU (Offline System Control Unit) URL
- `kra.enableFiscalisation`: Enable/disable fiscalisation flag

## Key Features

### 1. Placeholder KRA Client
- Structure ready for actual KRA eTIMS API implementation
- Clear TODO markers for actual API calls
- Error handling in place
- Supports enable/disable via configuration

### 2. Receipt Number and QR Code Storage
- Stores KRA receipt numbers (kra_receipt_no)
- Stores QR codes (qr_code)
- Unique constraint on receipt numbers
- All stored in FiscalReceipt model

### 3. Failure Handling
- Updates fiscal_status to FAILED on errors
- Logs errors for debugging
- Transaction rollback on failures
- Status remains as PENDING if not yet attempted
- Failed receipts can be retried

### 4. B2C and B2B Support
- Automatically determines receipt type from sale
- B2C: No customer (walk-in sales)
- B2B: Has customer (customer sales)
- Customer PIN stored only in fiscal receipt (not customer table)

### 5. Async Processing Support
- Async flag supported in fiscaliseSale and fiscaliseReturn
- Structure ready for queue implementation
- Currently processes synchronously but logs async intent
- TODO markers for actual queue implementation (e.g., Bull, BullMQ)

### 6. Credit Note Support
- Fiscalises returns as credit notes
- Links to original sale receipt
- Includes return reason
- Calculates taxes accurately from original sale items

### 7. Transaction Safety
- All fiscalisation operations are transactional
- Receipt updates atomic with KRA API calls
- Rollback on errors ensures data consistency

## API Endpoints Summary

### Fiscal Receipt Endpoints
- `POST /api/kra-etims/receipts` - Create fiscal receipt
- `GET /api/kra-etims/receipts` - List fiscal receipts
- `GET /api/kra-etims/receipts/:id` - Get fiscal receipt by ID

### Fiscalisation Endpoints
- `POST /api/kra-etims/sales/:saleId/fiscalise` - Fiscalise sale
- `POST /api/kra-etims/returns/:returnId/fiscalise` - Fiscalise return

## Next Steps for Production

1. **Replace KRA Client Placeholders**:
   - Implement actual KRA eTIMS authentication
   - Implement actual KRA eTIMS API endpoints
   - Follow official KRA eTIMS API documentation
   - Handle KRA-specific error codes and responses

2. **Implement Queue System** (Optional but Recommended):
   - Add Bull or BullMQ for async processing
   - Implement queue workers for fiscalisation
   - Add retry logic for failed fiscalisations
   - Add queue monitoring and management

3. **Add OSCU Support** (If using offline mode):
   - Implement OSCU (Offline System Control Unit) integration
   - Handle offline fiscalisation
   - Sync with KRA when online

4. **Testing**:
   - Test with KRA sandbox environment
   - Test with actual KRA eTIMS API
   - Test failure scenarios
   - Test async processing (when implemented)

## Testing Checklist

- [x] Create fiscal receipt for sale
- [x] Create fiscal receipt for return
- [x] Get fiscal receipt by ID
- [x] List fiscal receipts with filters
- [x] Fiscalise sale (placeholder API)
- [x] Fiscalise return (placeholder API)
- [x] Store receipt numbers and QR codes
- [x] Handle fiscalisation failures
- [x] Support B2C receipts
- [x] Support B2B receipts
- [x] Verify transaction rollback on error
- [ ] Test with actual KRA eTIMS API (pending KRA credentials)

## Dependencies

- Phase 4: Sales (Sale, SaleItem models)
- Phase 11: Returns (Return, ReturnItem models)
- FiscalReceipt model (already exists)
- axios (for HTTP requests - should be installed)

## Notes

1. **Placeholder Implementation**: KRA client uses placeholder API calls. Replace with actual KRA eTIMS API implementation.
2. **Async Processing**: Structure supports async processing but currently processes synchronously. Implement queue system for production.
3. **Error Handling**: Failures update status to FAILED and can be retried.
4. **Customer PIN**: Stored only in fiscal receipt, not in customer table (as per requirements).
5. **Receipt Numbers**: Unique constraint ensures no duplicate KRA receipt numbers.
6. **Configuration**: Enable/disable fiscalisation via `ENABLE_FISCALISATION` environment variable.

## Next Steps

Phase 13 is complete with placeholder implementation. The structure is ready for actual KRA eTIMS API integration. Replace placeholder implementations in `kraClient.js` with actual KRA eTIMS API calls based on official documentation.

