# HomeQuips POS - KRA eTIMS / Comstore FC4 Integration

## Scope of this build

This build adds Comstore FC4 fiscalisation to completed POS sales, eTIMS credit notes for sales returns, device/API connection testing, manual upload of pending fiscal-device invoices, and a dedicated professional 80 mm fiscal receipt.

The implementation follows the supplied **Comstore API Documentation 3.4.3**:

- `POST /api/complete-workflow` for original invoices and credit notes.
- `POST /api/upload-plu-data` for new/missing fiscal items.
- `GET /api/health` for API-service health.
- `POST /api/init` for fiscal-device initialization/connection testing.
- Invoice-status endpoint for checking invoices on the device, uploaded invoices and pending invoices.
- `POST /api/invoices/manually-upload/{serialNumber}` for queuing unsent device invoices to eTIMS.
- Protected calls send `X-API-KEY`.
- If fiscalisation reports **E337 / NO FIND PLU DATA**, POS automatically uploads the sale items to the fiscal device and retries once.
- If the device reports **E090/E351 insufficient stock**, POS refreshes those sale items from current POS stock and retries once.
- Successful fiscal response fields are stored on the transaction and printed on the receipt/credit note.

## Deploy / database upgrade

1. Back up the application files and database.
2. Replace the application files with this build.
3. Ensure Laravel writable cache directories exist (important on fresh ZIP deployments):

   ```bash
   mkdir -p storage/framework/views storage/framework/cache/data storage/framework/sessions bootstrap/cache
   chmod -R 775 storage bootstrap/cache
   ```

4. From the Laravel project directory run:

   ```bash
   php artisan optimize:clear
   php artisan migrate --force
   ```

This build also uses `storage_path('framework/views')` directly instead of `realpath(...)`, preventing Laravel's **Please provide a valid cache path** error when the compiled-view directory has not yet been created.

4. Confirm the Comstore API service is running and reachable from the POS server/PC (normally port `4000`).

## Configure each Business Location

Open **Business Settings -> Business Locations -> Edit** and complete **KRA eTIMS (Comstore FC4)**:

- Enable eTIMS for the location.
- Comstore API URL, for example `http://127.0.0.1:4000` when the service runs on the same machine.
- X-API-KEY generated by the Comstore service.
- Fiscal Device Serial No.
- Device IP when device initialization/testing is required.
- Business KRA PIN.
- Keep **Auto-upload missing PLU items** enabled.
- Keep **Use professional 80mm fiscal receipt** enabled.
- Use **Test mode** during commissioning; switch it off only when live submission is approved.

The location screen now also has:

- **Test API / Device Connection** - tests the API service and, when serial number + device IP are entered, tests device initialization as well.
- **Check Pending Invoices** - reads the device invoice counts.
- **Upload Pending eTIMS Invoices** - queues unsent invoices already held by the fiscal device for manual transmission to eTIMS.

For faster item onboarding, set sensible location defaults for Item Class Code, Package Unit Code, Quantity Unit Code, Country of Origin, eTIMS Tax Type and Product Type. Do not invent an Item Class Code; it must match KRA/eTIMS master classification.

## Product-specific eTIMS setup

Product create/edit includes **KRA eTIMS Product Details**. Product values override location defaults. For a zero-tax POS item, explicitly select the correct eTIMS category **A (Exempt), C (0% Zero Rated), or D (Non-VAT)**. The POS intentionally does not guess among them.

## Fast sales workflow

1. Cashier completes a final POS sale.
2. POS sends `complete-workflow` immediately, without downloading the fiscal inventory first.
3. If the item exists, the fiscal signature is stored and the receipt prints.
4. If Comstore returns E337, POS uploads the required PLU data and retries once.
5. If Comstore reports E090/E351, POS refreshes the fiscal stock for the sale items and retries once.
6. Successful receipts print with fixed Description / Qty / Price / Amount columns, totals, payment details, tax summary, KRA QR, CU identifiers and barcode.
7. If eTIMS fails, the local sale remains saved and the receipt is clearly marked failed/pending; it never fabricates a KRA QR.

## eTIMS credit note / sales return workflow

When the original sale has a successful eTIMS fiscal signature:

1. Open **Sales Return** from the original sale.
2. Enter the return quantities.
3. Select the required KRA refund reason:
   - 01 - Missing Quantity
   - 02 - Missing Data
   - 03 - Damaged / Wasted
   - 04 - Raw Material
   - 05 - Shortage
   - 06 - Refund
4. Select the refund payment method: Cash, Cheque, or Card/M-Pesa/Other non-cash.
5. Save the return.
6. The local return commits first, then POS submits an eTIMS credit note using `InvoiceType = credit`, the original CU invoice number as `relevantInvoiceNumber`, and the selected refund reason.
7. A successful credit note prints using the same aligned professional 80 mm layout with **CREDIT NOTE**, original invoice reference, original CU number, refund reason, tax summary, QR and new CU credit-note details.

A successfully fiscalised credit note is protected from normal editing/deletion so the same KRA credit is not accidentally changed or sent twice. In the current local-return data model, treat a fiscalised return as final; do not edit its returned quantities after successful eTIMS submission.

## Manual re-upload of pending/unsigned device invoices

From **Business Location -> eTIMS settings**:

1. Click **Check Pending Invoices** to see device totals and pending count.
2. Click **Upload Pending eTIMS Invoices**.
3. Confirm the action.
4. Comstore queues invoices already held on the fiscal device for transmission to eTIMS.

This function is for invoices already present on the Comstore/fiscal device but not transmitted successfully to eTIMS. A local POS transaction that never reached Comstore still needs its original fiscalisation request corrected/retried rather than relying on the device manual-upload command.

## Receipt rules

- Live successful sale: **TAX INVOICE**.
- Live successful return: **CREDIT NOTE**.
- Test sale: **TEST TAX INVOICE**.
- Test return: **TEST CREDIT NOTE**.
- Failed/pending fiscalisation: clearly marked eTIMS failed/pending; QR and CU data are shown only when a successful fiscal response exists.

## Validation / troubleshooting

- E337: item missing in fiscal inventory -> automatic PLU upload + controlled retry.
- E090/E351: insufficient fiscal stock -> stock refresh + controlled retry.
- E321: item tax rate differs from fiscal inventory -> correct the product eTIMS tax category.
- E341: PLU totals/tax summary do not reconcile -> POS blocks inconsistent fiscal data.
- E313: original/relevant invoice number is invalid -> verify the original eTIMS CU invoice reference.
- E218/E331, E219/E332, E220/E333, E335: credit value/price/quantity exceeds the original -> correct the return quantities/amounts.
- E034 / PLU data errors: verify item fields and remove unsupported/non-ASCII data.
- Authentication errors: verify X-API-KEY.
- Device unavailable: verify API service, device IP, serial number, firewall, device power and connectivity.

For commissioning, test at least one item from each tax category used by the business, discounts, cash/non-cash payments, a missing PLU, a partial sales return/credit note, an intentional device/network interruption, pending-invoice status and manual upload before switching to live production.
