# Punkit Creative — Overdue Invoice Chaser
## Finance Department | Developer Handover & Implementation Guide

This document outlines the architecture, data flow, and deployment steps for **Finance Automation 1: The Overdue Invoice Chaser**.

---

## 1. System Architecture Overview

*   **Frontend (The Dashboard):** A premium dark-mode HTML/CSS/JS dashboard (`invoice_chaser_dashboard.html`). Displays overdue invoices grouped into aging buckets (7, 14, and 30+ days), provides per-invoice and bulk "Chase Now" triggers, and shows an AI-generated daily summary. 
    **V2/V3 Features Included:**
    - Slide-over CRM panel with Account Health Scoring.
    - Editable contact details (syncs via `/update-contact` webhook).
    - Gamified Weekly Collection Target progress bar.
    - Built-in Late Fee Interest Calculator & Settlement Discount Simulator.
    - One-Click Communication Templates for WhatsApp/Email.
    - Dispute Flagging (stops the AI from chasing and visually highlights the row).

*   **Backend (n8n Workflow):** The workflow (`overdue_invoice_workflow.json`) runs on two triggers:
    1. **Automatic:** Every weekday morning at 07:00 via a CRON schedule.
    2. **Manual:** A webhook endpoint (`/invoice-chaser-manual`) triggered by the "Chase All Now" button on the dashboard.

### The Data Flow
1. Trigger fires (automatic or manual from dashboard).
2. n8n pulls overdue invoices from Xero. *(Mock data in this handover).*
3. A Code node categorises each invoice into 7-day, 14-day, or 30+ day aging buckets and assigns a tone (friendly / firm / urgent).
4. For each invoice, the Groq API (LLaMA 3.3) generates a personalised, tone-appropriate email.
5. Gmail sends the email directly to each debtor's contact.
6. A final Code node builds the daily summary metrics and returns them to the webhook caller (the dashboard).

---

## 2. Webhook API Schema

### Request (Dashboard → n8n)
```json
POST /webhook/invoice-chaser-manual
Content-Type: application/json

{
  "invoiceId": "INV-001",
  "debtor": "TechFlow Solutions",
  "contact": "sarah@techflow.io",
  "amount": "R 45,000",
  "daysOverdue": 32
}
```

### Response (n8n → Dashboard)
```json
{
  "summary": "Daily Invoice Chase Summary: 5 reminder(s) sent...",
  "total": 5,
  "totalAmount": 171450,
  "bucket7": 1,
  "bucket14": 2,
  "bucket30": 2
}
### Request (Update Contact → n8n)
```json
POST /webhook/update-contact
Content-Type: application/json

{
  "debtor": "TechFlow Solutions",
  "newEmail": "sarah.new@techflow.io",
  "newPhone": "+27 21 555 0192"
}
```

### Request (Flag Dispute → n8n) *(Optional)*
If you want the dispute status to sync back to Xero or stop the CRON trigger:
```json
POST /webhook/update-dispute
Content-Type: application/json

{
  "invoiceId": "INV-001",
  "disputed": true
}
```

---

## 3. Implementation Steps

### Phase 1: n8n Backend

1. Import `overdue_invoice_workflow.json` into your n8n instance.

2. **Update Contact Webhook:** Add a secondary webhook node to your workflow listening on `/update-contact` and route it to a Xero "Update Contact" node to handle any details changed in the UI panel.

3. **Groq API Key:** Open the "Groq - Write Reminder Email" node. Create a `httpHeaderAuth` credential with:
   - Header Name: `Authorization`
   - Value: `Bearer YOUR_GROQ_API_KEY`

3. **Connect Xero (CRITICAL FOR PRODUCTION):**
   > The workflow uses a "Set" node injecting mock invoice data. For production you MUST replace this with a live Xero node.
   - Add the n8n **Xero** node (available in n8n's node library).
   - Authenticate via **OAuth2** using your Xero account credentials.
   - Configure it to query `GET /Invoices` with filter: `Status=="AUTHORISED" AND DueDate<="${today}"`.
   - Ensure the output fields map to: `id`, `contact.emailAddress`, `amountDue`, and `dueDate` (calculate `daysOverdue` from today's date).

4. **Connect Gmail:**
   - Authenticate the "Gmail - Send Reminder" node via OAuth2 with your agency's or client's Google Workspace account.

5. Activate the workflow and copy the **Production Webhook URL** for the manual trigger.

### Phase 2: Frontend Dashboard

1. Host `invoice_chaser_dashboard.html` on your preferred static hosting (Netlify, Vercel, GitHub Pages).
2. Open the dashboard, click **⚙️ n8n Integration** in the sidebar, and paste the Production Webhook URL. It saves to `localStorage`.

---

## 4. Email Tone Logic (Escalation Rules)
| Bucket | Days Overdue | Tone | Action |
|---|---|---|---|
| 🟡 7-Day | 7–13 days | Friendly / gentle | First soft reminder |
| 🟠 14-Day | 14–29 days | Politely firm | Acknowledge possible oversight, request immediate payment |
| 🔴 30+ Day | 30+ days | Urgent / final notice | Clear escalation warning, reference potential collections |

---

## 5. Required Dependencies
*   **n8n instance**
*   **Groq API Key** (LLaMA 3.3)
*   **Xero Account** with OAuth2 credentials (Mandatory for production)
*   **Gmail / Google Workspace Credentials** (OAuth2)
