> For the complete documentation index, see [llms.txt](https://wally-3.gitbook.io/wally-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wally-3.gitbook.io/wally-docs/product/insights.md).

# AI Insights & Analytics

> Intelligent spending analysis and contextual nudges powered by rule-based heuristics.

***

## Overview

The Insights module provides **contextual nudges** (alerts/suggestions in the existing UI) and a **full analytics dashboard** using statistical rules and heuristics over the user's transaction history. No external LLM — pure statistical computation over Prisma data, precomputed with a nightly cron job.

***

## Nudges (Contextual Alerts)

Nudges are non-blocking, dismissible banners that appear at key moments in the transaction flow.

### Pre-Transaction (Send Page)

Shown after selecting a beneficiary and amount, before confirming.

| Rule                     | Logic                                   | Example                                                            |
| ------------------------ | --------------------------------------- | ------------------------------------------------------------------ |
| **Amount Anomaly**       | `amount > avg + 2 * stddev`             | "This amount is significantly higher than your usual ($X average)" |
| **Best Day**             | Day pattern from history vs current day | "You usually send on Fridays — prefer to wait?"                    |
| **Frequent Beneficiary** | Top beneficiary doesn't match selection | "You send more often to \[María] — did you mean her?"              |
| **Recurring Pattern**    | Recurring pattern due within ±3 days    | "You seem to send \~$200 to \[María] around the 15th each month"   |

### During Transaction (Before Confirm)

Shown as alerts before the final confirmation step.

| Rule                              | Logic                                       | Example                                                             |
| --------------------------------- | ------------------------------------------- | ------------------------------------------------------------------- |
| **Duplicate 24h**                 | Same beneficiary + same amount in last 24h  | "You already sent $100 to \[María] today — are you sure?"           |
| **New Destination + High Amount** | No previous sends + amount > average        | "First time sending to this recipient with a high amount"           |
| **Category Inconsistency**        | Historical category for beneficiary differs | "You usually send for 'Food' to \[María], but selected 'Emergency'" |

***

## Analytics Dashboard (`/analytics`)

A dedicated page with charts and recommendations.

### Stats Cards (Top Row)

* **Total sent this month** — animated CountUp
* **Trend vs previous month** — percentage with up/down arrow
* **Top category** — highest spending category
* **Yield earned** — if user has a SavingsVault

### Charts

* **Category Bar Chart** — spending by category (FOOD, HEALTH, EMERGENCY, etc.) with color-coded bars
* **Monthly Line Chart** — area chart showing spending trend over last 6-12 months
* **Spending Pie Chart** — donut chart with percentage breakdown; categories >40% highlighted in red as warning

### Smart Recommendations

Rule-based suggestions ordered by priority:

| Rule                      | Logic                                        | Example                                                                                                   |
| ------------------------- | -------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| **Excessive Category**    | Non-essential category >40% of total         | "You spend 52% on 'Party' — consider reducing"                                                            |
| **Goal vs Reality**       | Active Project + non-essential >30%          | "You have a $2,000 goal for \[Construction]. Reducing Party by $50/month gets you there 3 months earlier" |
| **Auto Savings**          | Stable spending ±10% for 3+ months, no vault | "Your spending is stable (\~$X/month). The surplus could earn yield on Blend"                             |
| **Beneficiary Spike**     | Sends to a beneficiary up >50% this month    | "You sent 65% more to \[María] this month — everything OK?"                                               |
| **Spending Distribution** | Compare distribution vs recommended          | "Your distribution: Food 35%, Party 30%, Health 20%. We recommend Party <15%"                             |

### Goal Progress

For users with active Projects:

* Progress bar: contributed vs goalAmount
* Estimated completion date at current pace
* Suggestion to accelerate by reducing non-essential categories

***

## Dashboard Integration

The main Dashboard (`/dashboard`) includes an **InsightsCard** widget showing:

* Total sent this month
* Trend vs previous month
* Top category
* Yield earned (if applicable)
* Savings suggestion (if no vault and avg >$200/month)
* Link to full Analytics page

***

## Technical Architecture

### Backend Module: `apps/api/src/insights/`

```
insights/
├── insights.module.ts           # NestJS module (imports PrismaModule)
├── insights.service.ts          # Orchestrator: reads cache + real-time checks
├── insights-compute.service.ts  # Heavy computation (called by cron)
├── insights-cron.service.ts     # @Cron('0 3 * * *') nightly job
├── insights.resolver.ts         # GraphQL queries (GqlAuthGuard protected)
├── entities/
│   ├── nudge.entity.ts          # @ObjectType: type, message, severity
│   ├── spending-report.entity.ts # @ObjectType: monthly aggregates
│   ├── analytics.entity.ts      # @ObjectType: full analytics data
│   └── recommendation.entity.ts # @ObjectType: type, priority, impact
└── rules/
    ├── pre-transaction.rules.ts     # Pure functions for pre-send nudges
    ├── during-transaction.rules.ts  # Pure functions for confirmation alerts
    ├── post-transaction.rules.ts    # Trend and savings computations
    └── recommendation.rules.ts      # Smart recommendation generation
```

### Prisma Model: `UserInsightsCache`

Precomputed data per user, updated nightly:

| Field               | Type    | Description                             |
| ------------------- | ------- | --------------------------------------- |
| `monthlyAvgSend`    | Float   | Average send amount                     |
| `stddevAmount`      | Float   | Standard deviation of amounts           |
| `topBeneficiaryId`  | String? | Most frequent beneficiary               |
| `topCategory`       | String? | Most used category                      |
| `sendDayPattern`    | Json    | Day-of-week frequency map               |
| `recurringPatterns` | Json    | Detected recurring transfers            |
| `categoryBreakdown` | Json    | Current month spending by category      |
| `monthlyHistory`    | Json    | Last 12 months with category breakdown  |
| `recommendations`   | Json    | Generated recommendations with priority |
| `totalSentMonth`    | Float   | Current month total                     |
| `totalSentAllTime`  | Float   | Lifetime total                          |

### GraphQL Queries

```graphql
# Pre-transaction nudges (Send page)
query preTransactionCheck($amount: Float, $beneficiaryId: String): [Nudge]

# During-transaction alerts (before confirm)
query transactionAlerts($amount: Float!, $beneficiaryId: String!, $category: String): [Nudge]

# Monthly spending report (Dashboard widget)
query myInsights: SpendingReport

# Full analytics data (Analytics page)
query myAnalytics($months: Int): Analytics
```

### Frontend Components

| Component            | Location                | Purpose                                       |
| -------------------- | ----------------------- | --------------------------------------------- |
| `NudgeBanner`        | `components/insights/`  | Dismissible alert banner (info/warning/alert) |
| `InsightsCard`       | `components/insights/`  | Dashboard widget with monthly summary         |
| `StatsRow`           | `components/analytics/` | 4-column stats cards with CountUp             |
| `CategoryBarChart`   | `components/analytics/` | Recharts bar chart by category                |
| `MonthlyLineChart`   | `components/analytics/` | Recharts area chart with gradient             |
| `SpendingPieChart`   | `components/analytics/` | Donut chart with >40% warning                 |
| `RecommendationCard` | `components/analytics/` | Dismissible recommendation with impact        |
| `GoalProgressCard`   | `components/analytics/` | Project progress bars                         |

### Cron Job

Runs at **3:00 AM daily** (`@Cron('0 3 * * *')`):

1. Finds all users with QuickSend history
2. Computes aggregates: mean, stddev, patterns, categories
3. Detects recurring transfers (same beneficiary ±20% amount, ±5 days, 3+ months)
4. Generates recommendations based on spending patterns
5. Upserts `UserInsightsCache` for each user

***

## Testing

```bash
# Run insights unit tests
cd apps/api && npx jest --no-coverage --testPathPatterns=insights
```

23 unit tests covering all pure rule functions:

* Pre-transaction rules (amount anomaly, best day, frequent beneficiary, recurring patterns)
* During-transaction rules (duplicate detection, new destination, category inconsistency)
* Recommendation rules (excessive category, auto savings, beneficiary spikes)
