# Punkit Creative — Month-End Director's Briefing
## Finance Department | Developer Handover & Implementation Guide

This document outlines the architecture, data flow, and deployment steps for **Finance Automation 3: Automated Month-End Report**.

---

## 1. System Architecture Overview

*   **Frontend (The Executive Dashboard):** A premium, non-interactive "Briefing" dashboard (`month_end_report_dashboard.html`). It features the Punkit Creative Brand Theme.
    *   **V2 Features:** Budget vs. Actuals tracking, Top 5 Client Concentration table, and an interactive "Executive Actions" panel that allows the Director to approve CFO recommendations with a single click.
*   **Backend (n8n Workflow V2):** The workflow (`month_end_workflow.json`) acts as the data aggregator and AI orchestrator.
    1. **Trigger:** `CRON` node fires on the 28th of every month (or last weekday) at 16:00.
    2. **Data Pull:** `Xero` nodes pull the trailing 30-day Profit & Loss, Balance Sheet, and **Budget Summary** reports.
    3. **AI Analysis:** `OpenAI` node (`gpt-4o`) reads the raw JSON. It generates the narrative summary, anomalies, and proposes an **Executive Action**.
    4. **Dashboard Publish:** `HTTP` webhook pushes the structured payload to the static HTML dashboard.
    5. **Email Delivery:** `Gmail` node emails the company directors.
    6. **Action Listener:** A `Webhook` node listens for `POST` requests from the dashboard's "Approve" button to execute bank transfers or other actions in Xero.

---

## 2. Webhook API Schema

### Request (n8n → Dashboard)
This payload is pushed by n8n to populate the static HTML file.
```json
POST /api/reports/month-end-webhook
Content-Type: application/json

{
  "month": "June 2026",
  "metrics": {
    "revenue": 284500,
    "expenses": 221900,
    "margin": "22.0%",
    "debtors": 145000,
    "creditors": 32000,
    "cash": 412500
  },
  "aiSummary": "June was a strong month for Punkit Creative, closing with <strong>R284,500 in total revenue</strong>...",
  "chartData": [
    { "month": "Jan", "rev": 210000, "exp": 180000 },
    { "month": "Jun", "rev": 284500, "exp": 221900 }
  ],
  "budgets": [
    { "dept": "Marketing & Ads", "budget": 30000, "actual": 28500 }
  ],
  "topClients": [
    { "name": "Apex Holdings", "billed": 95000 }
  ],
  "anomalies": [
    {
      "icon": "⚠️",
      "title": "Debtors Swell (Aging Risk)",
      "text": "Accounts Receivable increased by 15% this month..."
    }
  ]
}
```

### Action Request (Dashboard → n8n)
When the Director clicks "Approve" on the Executive Actions panel, the dashboard will POST to this webhook to execute the action.
```json
POST https://n8n.punkit.co.za/webhook/exec-action-webhook
Content-Type: application/json

{
  "status": "approved",
  "actionType": "bank_transfer",
  "amount": 45000,
  "fromBankId": "acc-123",
  "toBankId": "acc-456"
}
```

---

## 3. Implementation Steps

### Phase 1: n8n Backend
1. Import `month_end_workflow.json` into your n8n instance.
2. **Xero Setup:** Configure the Xero nodes to use your OAuth2 credentials. Ensure the nodes are querying the exact date ranges needed (e.g., `FromDate` and `ToDate` dynamically set to the current month).
3. **OpenAI Prompting:** Review the prompt inside the OpenAI node. You may need to inject specific Xero account codes into the prompt so the AI knows exactly which lines correspond to "Revenue" vs "Cost of Goods Sold" for your specific Chart of Accounts.

### Phase 2: Dashboard Frontend
1. Host `month_end_report_dashboard.html`.
2. **Dynamic Data:** The dashboard currently uses a static `DATA` constant for demonstration. You will need to implement a backend (like a small Express/Next.js route) that receives the n8n webhook payload, saves it to a database, and injects it into the HTML before serving it to the directors.

---

## 4. Required Dependencies
*   **n8n instance**
*   **OpenAI API Key** (`gpt-4o` recommended for complex JSON reasoning)
*   **Xero Account** with OAuth2 credentials
*   **Gmail / SMTP Credentials** for the outgoing email alert.
