> ## Documentation Index
> Fetch the complete documentation index at: https://help.kuverbooks.com/llms.txt
> Use this file to discover all available pages before exploring further.

# POS API Exposure & Integration Strategy Report

# POS API Exposure & Integration Strategy Report

This report presents a comprehensive API exposure and integration strategy for the POS-Backend platform. It outlines the architectural design, API catalogs, segregation logic, logistics framework, commercial models, and technical standards needed to connect the platform with third-party ERPs, accounting tools, marketplaces, and logistics providers.

***

## Executive Summary: What Has Been Implemented vs. What is Planned

### 1. Currently Implemented (Proof of Concept & Foundation)

* **Database Schema**: Master database table `api_integrations` to map machine-to-machine (M2M) API keys to specific tenants, branches, roles, and fiscal years.
* **Tenant Context Switching**: Dynamic resolution of database connection scopes on a per-request basis using `TenantContextService`.
* **API Key Guard**: Custom `ExternalIntegrationGuard` that validates hashed incoming API keys and projects a virtual `IAuthUser` context.
* **Controller Exposure**: Sandbox controllers for Products (`/api/v1/external/products`) and Billing (`/api/v1/external/billing/invoices`) validating standard operations.

### 2. Research & Future Phase Roadmap (Covered in this Report)

* **Expanded API Catalogs**: Complete endpoints for Purchase Orders, Reservations, Webhooks, Debit/Credit Notes, and Logistics.
* **Segregation & Synchronization**: Logic to manage hybrid ownership between Inventory and Billing.
* **Logistics Integration**: Full Order-to-Shipment lifecycle.
* **Commercialization**: Tiered integration pricing strategies.
* **Observability**: Metrics, API usage quotas, and audit trails.

***

## 1. API Exposure Strategy (Inventory Module)

The Inventory Module is the core repository of product data, stock status, and replenishment flows. Exposing these APIs allows external e-commerce sites (like Shopify, WooCommerce) or ERPs (like SAP, Oracle) to keep their catalogs in sync.

### A. Inventory API Catalog

```mermaid theme={null}
graph TD
    subgraph Products
        A[Product CRUD] --> B[GET /products]
        A --> C[POST /products]
        A --> D[PUT /products/:id]
    end
    subgraph Stock Management
        E[Stock Queries] --> F[GET /products/stock]
        E --> G[POST /products/adjust]
        E --> H[POST /products/reserve]
    end
    subgraph Procurement
        I[Procurement] --> J[GET /purchase-orders]
        I --> K[POST /goods-receipt]
    end
```

#### 1. Product CRUD APIs

* `GET /api/v1/external/products`: Lists products with filtering by categories, status, and search keywords.
* `GET /api/v1/external/products/:id`: Retrieves detailed metadata for a single product, including units, prices, and tax rates.
* `POST /api/v1/external/products`: Creates a new product catalog item.
* `PUT /api/v1/external/products/:id`: Updates product descriptions, pricing, and category mappings.

#### 2. Stock Inquiry, Adjustments, Transfers, & Reservations

* `GET /api/v1/external/products/stock`: Queries real-time stock levels across different branches.
* `POST /api/v1/external/products/adjust`: Modifies stock levels directly for audits or shrinkage write-offs.
* `POST /api/v1/external/products/transfer`: Records warehouse-to-branch or branch-to-branch inventory movements.
* `POST /api/v1/external/products/reserve`: Temporarily locks inventory for a specific shopping cart or sales order to prevent overselling.

#### 3. Purchase Orders & Goods Receipt APIs

* `GET /api/v1/external/purchase-orders`: Lists pending and historical procurement orders.
* `POST /api/v1/external/goods-receipt`: Records incoming deliveries from suppliers, updating stock and writing to ledger.

### B. API Contracts & Standard Payload Structure

All API responses follow a uniform wrapper to ensure predictable client consumption:

#### Standard Success Response

```json theme={null}
{
  "success": true,
  "data": {
    "id": "e30cf827-cb57-4148-9c59-bf88667a421b",
    "sku": "PROD-COFFEE-01",
    "name": "Himalayan Arabica Coffee Beans",
    "price": 1200.00,
    "currentStock": 45
  },
  "metadata": {
    "timestamp": "2026-07-01T06:00:00Z"
  }
}
```

#### Standard Paginated Response

```json theme={null}
{
  "success": true,
  "data": [
    { "id": "e30cf827...", "name": "Coffee" }
  ],
  "pagination": {
    "totalCount": 140,
    "limit": 10,
    "page": 1,
    "totalPages": 14
  }
}
```

#### Standard Error Format

```json theme={null}
{
  "success": false,
  "error": {
    "code": "INSUFFICIENT_STOCK",
    "message": "The requested reservation of 10 items exceeds the available stock of 5.",
    "details": [
      {
        "field": "quantity",
        "issue": "Requested: 10, Available: 5"
      }
    ]
  }
}
```

### C. Authentication & Authorization Model

* **Mechanism**: Hashed API Keys (SHA-256) passed via the `x-api-key` header for server-to-server (M2M) communications.
* **Tenant Context Propagation**: The request context resolves the tenant domain name and points Kysely database queries directly to the correct database (e.g. `tenant_company_1_development`) ensuring complete tenant isolation.
* **Access Rule Permissions**: API keys are mapped to roles (e.g., `INTEGRATION_ROLE` or `SUPER_ADMIN`) controlling which endpoints can be invoked.

***

## 2. Billing API Exposure Strategy

Exposing Billing APIs enables external sales channels (e.g. website carts, self-service kiosks, external billing software) to submit transactions directly to the POS for taxation, receipt generation, and accounting.

### A. Billing API Catalog

1. **Invoice Lifecycle APIs**:
   * `POST /api/v1/external/billing/invoices`: Submits sales transactions, generates invoice numbers, and files tax records.
   * `GET /api/v1/external/billing/invoices/:id`: Retrieves invoice status and billing items.
   * `PATCH /api/v1/external/billing/invoices/:id/void`: Voids an invoice (with reason logs) in compliance with IRD guidelines.
2. **Payment APIs**:
   * `POST /api/v1/external/billing/invoices/:id/payments`: Logs payments (Cash, Card, QR, Credit) against open invoices.
3. **Customer APIs**:
   * `POST /api/v1/external/billing/customers`: Creates or registers customer profiles for loyalty points and VAT tracking.
4. **Debit/Credit Note APIs**:
   * `POST /api/v1/external/billing/notes`: Issues credit/debit notes for returned items or price corrections.

### B. Webhook Events (Billing Domain)

Webhooks notify external applications immediately when events occur inside the POS, reducing the need for polling:

| Event Name                 | Trigger Condition                                   | Payload Includes                        |
| :------------------------- | :-------------------------------------------------- | :-------------------------------------- |
| `billing.invoice.created`  | Generated when a new invoice is created             | Invoice ID, Client, Amount, Tax, Branch |
| `billing.invoice.voided`   | Fired when an invoice is successfully voided        | Invoice ID, Void reason, Timestamp      |
| `billing.payment.received` | Triggered when payment is logged                    | Invoice ID, Payment mode, Reference No  |
| `billing.refund.processed` | Triggered when a credit note or refund is finalized | Refund ID, Amount, Original Invoice ID  |

***

## 3. Inventory & Billing Segregation Architecture

When integrating external ERPs and e-commerce platforms, maintaining data consistency is a major challenge. We define clear system boundaries to prevent synchronization loops and double-counting.

### A. System Ownership Models

```mermaid theme={null}
graph TD
    subgraph Model A: Inventory Source of Truth
        A[POS Inventory] -->|Syncs Stock Levels| B[External Billing / Shopify]
        B -->|Submits Orders| A
    end
    subgraph Model B: Billing Source of Truth
        C[External ERP] -->|Manages Stock / Catalog| D[POS Billing / Register]
        D -->|Logs Invoices| C
    end
```

1. **Inventory as Source of Truth**:
   * The POS platform owns stock levels, product metadata, and pricing.
   * External systems (e.g. Shopify) poll stock or receive updates via webhooks and submit invoices to the POS when sales happen.
2. **Billing as Source of Truth**:
   * An external ERP (e.g. SAP) owns procurement, product registry, and accounts receivable.
   * The POS functions purely as a transaction register, pushing invoice logs to the ERP and relying on the ERP for catalog definitions.
3. **Hybrid Mode**:
   * Product master data is managed in the ERP.
   * Live stock counts and daily sales transaction entries are maintained in the POS.
   * The systems sync hourly via message queues.

### B. Integration Architecture & Data Sync Rules

To decouple systems and prevent latency bottlenecks, the platform uses an **Event-Driven Architecture**:

```text theme={null}
+------------------+         +-----------------+         +---------------------+
|   POS Backend    | ------> |  RabbitMQ/Bull  | ------> |  Integration Worker |
| (Kysely + Nest)  |         |  Message Queue  |         | (Webhook Dispatch)  |
+------------------+         +-----------------+         +---------------------+
                                                                    |
                                                                    v
                                                         +---------------------+
                                                         |  Third-Party App    |
                                                         +---------------------+
```

* **Message Broker (RabbitMQ/BullMQ)**: Every transaction or stock adjustment pushes an event to a queue. Background workers process the queues and post webhooks asynchronously.
* **Webhook Retry Flow (Backoff & DLQ)**:
  * If a webhook call fails, it retries using **exponential backoff** (e.g., retry after 1 min, 5 mins, 30 mins, 2 hours).
  * If the target system is down after 5 retries, the message goes to the **Dead-Letter Queue (DLQ)**, triggering admin notifications and pausing further updates to prevent system loops.
* **Audit Trails**: All integration requests, payload logs, and HTTP statuses are written to `api_logs` for troubleshooting.

***

## 4. External Logistics Integration Framework

For e-commerce and retail tenants, integration with logistics providers (e.g. Pathao, Upaya, e-desh) is vital to automate order fulfillment.

### A. Logistics API Catalog & Events

* `POST /api/v1/external/logistics/shipments`: Books a delivery request with details on weight, cash-on-delivery (COD) values, and customer addresses.
* `GET /api/v1/external/logistics/shipments/:id/track`: Polls delivery status and tracking histories.
* `POST /api/v1/external/logistics/shipments/cancel`: Cancels an active booking request.

#### Webhook Events:

* `logistics.shipment.pickup`: Fired when the courier collects the package.
* `logistics.shipment.transit`: Fired when the package reaches dispatch hubs.
* `logistics.shipment.delivered`: Fired upon successful delivery.
* `logistics.shipment.failed`: Fired if delivery fails (customer unavailable, wrong address).

### B. Integration Flow

```text theme={null}
[ Customer Orders ] 
       │
       ▼
[ POS Invoice Created ] ────► [ Trigger Logistics Booking ] ────► [ Print Shipping Label ]
                                           │
                                           ▼
[ Customer Delivery ] ◄───── [ Track Courier Transit ] ◄───── [ Package Picked Up ]
```

***

## 5. Integration Pricing & Commercial Model

To monetize the API ecosystem and offset server infrastructure costs, we recommend a tiered pricing model:

| Model Tier       | Access Limits           | Pricing Structure                          | Use Case                                         |
| :--------------- | :---------------------- | :----------------------------------------- | :----------------------------------------------- |
| **Free / Basic** | 1,000 requests/month    | Included in SaaS base fee                  | Small retailers with basic accounting sync       |
| **Growth**       | 10,000 requests/month   | \$29 / month                               | Medium retailers syncing WooCommerce/Shopify     |
| **Enterprise**   | 100,000+ requests/month | \$149 / month + \$0.01 per additional call | High-volume retail stores and external ERPs      |
| **Custom Setup** | Unlimited               | One-time setup fee (\$500)                 | Enterprise clients requiring custom integrations |

### Recommendation

Implement the **API Usage-Based Billing** model with monthly tiers. This aligns billing with customer size and ensures that system resources are charged in proportion to their utilization.

***

## 6. Technical Standards & Security Framework

### A. Technical Conventions

* **API Style**: Standard RESTful APIs using JSON.
* **Versioning**: Path-based versioning (e.g., `/api/v1/external/...`). Version changes (v2) are introduced only when breaking changes occur (e.g. field removals).
* **Documentation**: Automatic interactive documentation using OpenAPI (Swagger) to let developer clients test routes.

### B. Security Outline

* **IP Whitelisting**: Optional restriction of API key calls to registered static client server IPs.
* **Rate Limiting**: Enforced rate limiting using Redis (e.g., max 60 calls per minute per API key) to protect database pools from denial-of-service (DoS) scenarios.
* **Audit Trail Schema**: A dedicated log table to store request details:
  ```typescript theme={null}
  interface ApiLogs {
    id: string;
    integration_id: string;
    endpoint: string;
    method: string;
    request_payload: string;
    response_status: number;
    executed_at: Date;
  }
  ```

***

## Explaining the Integration Flow to a Normal User (Layman's Terms)

Imagine your POS system as a busy, secure **warehouse**:

1. **The Gatekeeper (API Key & Guard)**: When an external system (like your Shopify website) wants to check what's in the warehouse, it must show a special **Access Pass (API Key)**. The security guard at the gate checks this pass. If it's valid, the guard writes down who entered, which branch of the business they represent, and lets them in.
2. **Context Switching (Database Isolation)**: The warehouse has separate, locked rooms for each business (Tenant isolation). The guard escorts the guest directly to their business's room, ensuring they can never see or touch another company's products or money.
3. **Inventory Syncing (Stock Inquiry)**: The guest (Shopify) asks: *"Do we have Arabica Coffee Beans in stock?"* The warehouse team checks the shelf and says, *"Yes, we have 45 bags left."* Shopify immediately updates its website display so online shoppers see the correct count.
4. **Billing Syncing (Sales Order)**: When an online shopper buys 2 bags of coffee, Shopify registers the sale and tells the warehouse: *"We just sold 2 bags of coffee. Please pack them and update the books!"* The POS system deducts the 2 bags from the stock level, records the cash payment, and logs the invoice details.
5. **Couriers & Delivery (Logistics Integration)**: The POS system then automatically alerts the courier service: *"We have a package ready. Here is the address, please come pick it up."* As the courier transports the coffee, they send updates back to the POS system, so the business owner can see if the delivery is transit, completed, or failed.
