# WooInsight - Development Brief

## What It Is

A WooCommerce plugin that adds a modern React-powered analytics dashboard to the WordPress admin, with an integrated AI chat assistant that lets store owners query their data in plain English.

---

## Pages and Features

### Overview Dashboard

The default landing page when the plugin is opened from the WP admin sidebar.

**KPI Row (4 cards across the top):**
- Total Revenue with percentage change vs previous period
- Total Orders with percentage change and average order value
- Total Customers with percentage change and new customers this month
- Conversion Rate with percentage change and total visitor count

All KPIs respect the date range selector (7D, 1M, 3M, 6M, 1Y) in the header. Percentage changes compare to the equivalent previous period.

**Charts:**
- Revenue Overview: area chart, current period vs same period last year, monthly granularity. Y-axis formatted as currency.
- Sales by Category: donut chart showing percentage of revenue per product category. Category names are clickable and navigate to the Products page filtered by that category.
- This Week Revenue: bar chart with daily breakdown (Mon-Sun). Highest revenue day visually highlighted.
- Customer Growth: stacked area chart showing new customers vs returning customers per month.

**Tables:**
- Recent Orders: last 6 orders showing order ID, customer name, total, status badge, time ago. Order IDs link to Order Detail. Customer names link to Customer Detail. View All button navigates to the Orders page.
- Top Products: top 5 products by revenue showing rank, product name, units sold, revenue, trend percentage. Product names link to Product Detail. View All button navigates to the Products page.

### Orders Page

Full paginated order list. Accessible from the nav tab and from View All on the overview.

**Filters:**
- Status tabs across the top: All, Completed, Processing, On Hold, Refunded
- Each tab shows a count of orders in that status

**Table columns:**
- Order ID (clickable, links to Order Detail)
- Customer name (clickable, links to Customer Detail)
- Email
- Item count
- Total (currency formatted)
- Status (colour-coded badge)
- Date

Data source: WooCommerce orders via REST API or direct DB query, paginated.

### Order Detail Page

Accessed by clicking any order ID anywhere in the dashboard.

**Back button** returns to the Orders page.

**Three-column layout:**

Column 1 - Order Details: Date, Time (relative), Payment method, Shipping method, Order total (highlighted).

Column 2 - Customer: Avatar (initials-based), Customer name (clickable, links to Customer Detail), Email, Customer ID.

Column 3 - Items: List of products in the order. Each product shows its icon/thumbnail, name (clickable, links to Product Detail), and unit price.

**Order Timeline:**
Below the three columns. A vertical timeline showing order progression: Order placed, Payment confirmed, Shipped, Delivered. Each step shows a timestamp. Incomplete steps show Pending. Active/completed steps are visually distinct from pending ones.

### Products Page

Product grid layout. Accessible from the nav tab and View All on the overview.

**Product cards (4 per row) showing:**
- Product icon/thumbnail
- Product name
- Category and SKU
- Price (large, highlighted)
- Trend percentage (green up / red down)
- Footer row: Units Sold, Stock Level, Customer Rating
- Stock level shown in red if below a configurable low-stock threshold

Each card is fully clickable and navigates to Product Detail.

### Product Detail Page

Accessed by clicking any product name or card anywhere in the dashboard.

**Back button** returns to the Products page.

**Header:** Product icon, name, category, SKU.

**KPI Row (4 cards):** Price, Units Sold, Total Revenue, In Stock count.

**Two-column layout below KPIs:**

Left column - Sales Trend: Area chart showing units sold per week over the last 8 weeks.

Right column - Product Details: Category, SKU, Rating (star rating and review count), Trend direction and percentage, Stock status (In Stock / Low Stock, colour coded).

**Related Orders Table:**
Below the two columns. Shows all recent orders that contain this product. Columns: Order ID (clickable), Customer (clickable), Total, Status badge, Date.

### Customers Page

Sortable customer directory. Accessible from the nav tab.

**Sort options:** Top Spenders (default), Most Orders, Alphabetical.

**Table rows showing:**
- Avatar (initials-based, colour varies by tier)
- Customer name and subtitle showing city and join date
- Email
- Order count
- Total lifetime spend (currency formatted)
- Tier badge: Platinum, Gold, Silver, Bronze (thresholds configurable in settings)
- Last order (relative time)

Each row is fully clickable and navigates to Customer Detail.

### Customer Detail Page

Accessed by clicking any customer name or row anywhere in the dashboard.

**Back button** returns to the Customers page.

**Header:** Avatar, name, tier badge, email, city.

**KPI Row (4 cards):** Total Spent, Order Count, Average Order Value, Member Since.

**Two-column layout:**

Left column - Spending History: Bar chart showing monthly spend over the last 6 months.

Right column - Customer Profile: Customer ID, Email, Location, Tier (colour coded), Last order (relative time).

**Order History Table:**
All orders from this customer. Columns: Order ID (clickable), Item count, Products list, Total, Status badge.

### AI Store Assistant

A floating chat panel, toggled by a button fixed to the bottom-right corner of every page.

**Trigger button:** Fixed position, bottom-right. Shows a distinctive icon when closed, close icon when open. Visually prominent using the main accent colour.

**Chat panel (slides up from the button):**
- Header with assistant name and description
- Message area with scrollable history
- User messages styled differently from assistant messages
- Assistant messages prefixed with a small AI indicator
- Typing indicator (animated dots) while waiting for a response
- Suggested question chips shown when the chat is empty (6 pre-set questions). Chips disappear after the first message is sent.

**Input area:**
- Auto-expanding textarea
- Send button (visually active only when there is input)
- Enter key sends, Shift+Enter for new line
- Subtle Powered by AI label below input

**Backend behaviour:**
- User messages are sent to a server-side PHP endpoint (not directly to the AI API from the browser)
- The PHP endpoint builds a system prompt containing a cached summary of the store data (revenue, orders, products, customers, trends)
- The store summary is rebuilt and cached as a WordPress transient every 30 minutes
- Only the last 10 messages of conversation history are sent to keep token usage low
- The AI API key is stored encrypted in wp_options and never exposed to the frontend
- Rate limiting: configurable max queries per user per day (default 50)

---

## Navigation

**Header bar (persistent across all pages):**
- Logo/brand (clickable, returns to Overview)
- Nav tabs: Overview, Orders, Products, Customers. Active tab highlighted. When viewing a detail page, the parent tab stays highlighted (e.g. Order Detail highlights the Orders tab).
- Date range selector (7D, 1M, 3M, 6M, 1Y) - shown on Overview page only
- Store status indicator (Store Live with a pulsing dot)

**Cross-linking rules:**
- Every order ID anywhere in the app links to its Order Detail page
- Every customer name anywhere in the app links to their Customer Detail page
- Every product name anywhere in the app links to its Product Detail page
- Detail pages always have a back button to their parent list page
- The logo always returns to Overview

---

## Data Layer

### Sources

All data is pulled from the WooCommerce database via either the WooCommerce REST API v3 or direct custom queries for aggregations that the API does not support natively.

### Custom REST Endpoints

Register under the namespace wooinsight/v1:

| Endpoint | Method | Purpose |
|---|---|---|
| /overview | GET | KPIs, revenue summary, category breakdown for the selected date range |
| /revenue | GET | Revenue time series data, accepts date_from, date_to, granularity params |
| /orders | GET | Paginated order list, accepts status filter, page, per_page |
| /orders/{id} | GET | Single order with line items and timeline events |
| /products | GET | Product list with calculated sales metrics (units sold, revenue, trend) |
| /products/{id} | GET | Single product with weekly sales history |
| /customers | GET | Customer list with lifetime value, order count, tier. Accepts sort param |
| /customers/{id} | GET | Single customer with monthly spending history |
| /ai-query | POST | Accepts message and conversation history, returns AI response |

All endpoints require manage_woocommerce capability and are nonce-authenticated.

### Caching

- Overview KPIs: 15-minute transient
- Revenue and chart data: 1-hour transient
- Recent orders: 5-minute transient
- AI store context summary: 30-minute transient
- Cache busted on: woocommerce_new_order, woocommerce_order_status_changed, woocommerce_update_product

### AI Context Builder

A PHP class that generates a structured text summary of the store state, stored as a transient. Includes: total revenue, order count, top products by revenue, top customers by spend, category breakdown percentages, recent order activity, stock alerts, and trend comparisons. Target size: under 2,000 tokens.

---

## Settings Page

Accessible via WooCommerce > WooInsight > Settings in the WP admin.

**AI Configuration:**
- Enable/disable AI assistant toggle
- OpenAI API key input (stored encrypted)
- Daily query limit per user (number input, default 50)

**Dashboard Configuration:**
- Customer tier thresholds: Platinum, Gold, Silver spend amounts (currency inputs)
- Low stock threshold (number input, default 10)
- Cache TTL overrides (optional, advanced)
- Manual Clear Cache button

**Access Control:**
- Minimum WordPress role required to view the dashboard (dropdown: Administrator, Shop Manager)

**White Label:**
- Custom dashboard name (text input, replaces WooInsight in the header)
- Custom logo upload (replaces the default logo mark)

Currency and date format are inherited automatically from the WooCommerce store settings.

---

## Technical Requirements

| Requirement | Detail |
|---|---|
| WordPress | 6.0+ |
| WooCommerce | 8.0+ |
| PHP | 8.0+ |
| HPOS | Must support both legacy (post-based) and HPOS (custom tables) order storage |
| Frontend | React 18, built with @wordpress/scripts |
| Charts | Recharts library |
| AI API | OpenAI API, proxied through PHP, never called from the browser |
| Build | npm run build produces compiled assets in /build directory |

### Plugin File Structure

```
wooinsight/
|-- wooinsight.php              # Plugin header, activation hooks, dependency checks
|-- includes/
|   |-- class-admin.php         # Registers admin menu page, enqueues React bundle
|   |-- class-rest.php          # Registers all custom REST endpoints
|   |-- class-data.php          # Data aggregation queries and transient caching
|   |-- class-ai.php            # AI proxy endpoint, context builder, rate limiter
|   |-- class-settings.php      # Settings page registration and sanitisation
|-- src/
|   |-- index.js                # React entry point, mounts app into admin page div
|   |-- App.jsx                 # Router, nav, layout shell
|   |-- pages/                  # One component per page (Overview, Orders, etc.)
|   |-- components/             # Reusable UI (KPICard, StatusBadge, AIChatPanel, etc.)
|   |-- hooks/                  # useStoreData, useAIChat
|   |-- utils/                  # formatCurrency, api client wrapper
|-- build/                      # Compiled output (generated, not committed)
|-- assets/                     # Static assets (icon, default logo)
|-- readme.txt                  # WordPress plugin readme
```

### Security

- All REST endpoints check manage_woocommerce capability
- All REST endpoints verify the wp_rest nonce
- AI API key encrypted in wp_options, never sent to the browser
- AI input sanitised server-side before forwarding to the API
- System prompt is server-side only, cannot be overridden by user input
- AI endpoint rate-limited per user per day

---

## Functional Notes

- The dashboard renders inside a single WordPress admin page as a full React SPA. No iframes.
- Client-side routing handles navigation between pages without full page reloads.
- The React app receives the REST API base URL and nonce via wp_localize_script.
- Loading states should show skeleton placeholders, not spinners.
- Error states should show a retry option, not a blank screen.
- All currency formatting must use the WooCommerce store currency symbol and decimal settings.
- The AI chat session resets on page refresh. No conversation persistence between sessions.
- The dashboard should load in under 2 seconds on a store with 10,000 orders.
