# Punkit Creative — Management Auto 2: KPI Watchdog
## Developer Handover & Implementation Guide

This document outlines the architecture and deployment steps for the **KPI Watchdog System**. By bypassing third-party subscription platforms like Windmill, we have built a fully custom, high-margin solution using our standard Punkit dashboard and n8n stack.

### 1. System Architecture
This automation acts as an early warning system. It monitors business health metrics and fires high-priority WhatsApp messages to relevant managers if metrics drop below acceptable levels.

*   **Frontend (KPI Configuration Dashboard):** A custom settings portal (`kpi_alert_dashboard.html`) built with the Punkit dark-mode theme. It allows directors to set threshold rules (e.g., Cash < R100,000) and assign specific phone numbers to specific alerts.
*   **Backend (n8n Watchdog):** The orchestration engine (`kpi_alert_workflow.json`).
    1. **Trigger:** A CRON node set to run every 2 hours.
    2. **Config Fetch:** An HTTP node pulls the latest threshold rules saved by the Dashboard.
    3. **Data Fetch:** n8n pulls live bank balances from Xero and pipeline values from HubSpot.
    4. **Evaluation:** IF nodes evaluate whether the live data breaches the configured thresholds.
    5. **Alerting:** If a threshold is breached (and the rule is toggled 'ON'), the WhatsApp Cloud API node fires the alert directly to the manager's phone.

### 2. Deployment Steps

#### Step 1: Deploy the Dashboard
1. Host `kpi_alert_dashboard.html` on a secure admin route (e.g., `https://punkit.co.za/admin/kpi-config`).
2. Wire the "Save Configuration" button to POST the threshold variables to your backend database (this DB is what the n8n HTTP node will read from).

#### Step 2: Import & Configure n8n Workflow
1. Import `kpi_alert_workflow.json` into the production n8n instance.
2. Authenticate the following nodes:
   *   **HTTP Node (Config Fetch):** Point this URL to your database endpoint where the dashboard saves its configuration JSON.
   *   **Xero Node:** Requires an active OAuth2 connection with `accounting.reports.read` scopes.
   *   **HubSpot Node:** Requires a Private App Access Token with `crm.objects.deals.read` scope.
   *   **WhatsApp Nodes:** Requires a Meta Developer account with the WhatsApp Cloud API configured. Ensure the `phoneNumberId` and System User Access Token are valid.

#### Step 3: Testing
1. In the Dashboard, set a threshold you know will fail (e.g., Alert if Cash < R10,000,000).
2. Enter your personal phone number.
3. Manually execute the n8n workflow.
4. Verify that you receive the WhatsApp alert instantly.

### 3. Adding New Rules
To add a new rule (e.g., "Alert if Staff Turnover > 5%"):
1. Duplicate a `.rule-card` block in the HTML dashboard and add the new metric inputs.
2. Add an HTTP node in n8n to fetch the HR data.
3. Add a new IF node and connect it to a new WhatsApp node.
