# Punkit Creative — AI Invoice Processor
## Finance Department | Developer Handover & Implementation Guide

This document outlines the architecture, data flow, and deployment steps for **Finance Automation 2: AI Accounts Payable Processor**.

---

## 1. System Architecture Overview

*   **Frontend (The Dashboard):** A specialized "Tabbed Verification" dashboard (`ap_invoice_dashboard.html`). Features a distinct Neon Cyan/Purple UI.
    *   **V2 Features:** Line-item level extraction, AI confidence highlighting (yellow warnings if OCR fails), Fraud Alert banners for bank details, Duplicate Detection warnings, AI Auto-Assigned GL Categories, a "Chat with Document" AI assistant, and a "One-Click Approve" button to push to Xero.
*   **Backend (n8n Workflow V2):** The workflow (`ap_processor_workflow.json`) acts as an inbox watcher and router.
    1. **Trigger:** `IMAP Read Email` node listens to `accounts@punkit.co.za` for emails with attachments.
    2. **Extraction:** An `OpenAI` node uses `gpt-4o` to read the PDF and extract JSON data (Supplier, Total, VAT, Line Items, Bank Details).
    3. **Verification (Fraud & Duplicates):** n8n uses `Xero` nodes to pull the vendor's saved bank details and recent invoices to check for mismatches (fraud) and exact duplicates.
    4. **Routing:** n8n sends the structured JSON (with `fraudAlert` and `duplicate` boolean flags) to the dashboard.
    5. **Approval Sync:** When the clerk clicks "Approve", the dashboard hits an n8n webhook, which then pushes the data to Xero via the `Xero` node to create a Draft Bill.

---

## 2. Webhook API Schema

### Request (Dashboard → n8n Xero Sync)
This is triggered when the user clicks "✅ Approve & Sync to Xero".
```json
POST /webhook/ap-approve-to-xero
Content-Type: application/json

{
  "invoiceId": "inv_101",
  "supplier": "CloudHost Web Services",
  "date": "2026-06-12",
  "dueDate": "2026-06-26",
  "invNum": "CH-2026-889",
  "subtotal": 12500.00,
  "vat": 1875.00,
  "total": 14375.00,
  "lineItems": [
    { "desc": "Dedicated Server Hosting (June)", "qty": 1, "unit": 8500.00, "sum": 8500.00 },
    { "desc": "CDN Overage Fees", "qty": 1, "unit": 4000.00, "sum": 4000.00 }
  ]
}
```

---

## 3. Implementation Steps

### Phase 1: n8n Backend
1. Import `ap_processor_workflow.json` into your n8n instance.
2. **Email Setup:** Configure the `IMAP Email Read` node with the credentials for `accounts@punkit.co.za`. Set it to download attachments.
3. **OpenAI Credentials:** Configure the `OpenAI` node with an API key. Ensure the account has access to Vision models (e.g., `gpt-4o` or `gpt-4-vision-preview`).
4. **Xero Credentials:** Configure the `Xero` node using OAuth2. Ensure it is set to create an `ACCPAY` (Accounts Payable / Bill) invoice type.

### Phase 2: Dashboard Frontend
1. Host `ap_invoice_dashboard.html`.
2. Update the AJAX/Fetch calls inside `approveInvoice()` to point to your live `ap-approve-to-xero` webhook URL.
3. The dashboard currently uses Mock Data (`INBOX`) for UI demonstration. You will need to build an endpoint or database (e.g., Supabase/Firebase) to store the incoming n8n extractions so the dashboard can render them.

---

## 4. Required Dependencies
*   **n8n instance**
*   **OpenAI API Key** (Vision capabilities required)
*   **Xero Account** with OAuth2 credentials
*   **Email Account** (IMAP access enabled)
