feat: lead dashboard with status history (conversion = WON) #29

Merged
ngqile merged 14 commits from add-lead-dashboard into main 2026-12-01 02:51:22 +00:00
49 changed files with 3023 additions and 12 deletions

No files matched your search

+9
View File
@@ -97,6 +97,14 @@ After running `04`, `SELECT LENGTH(password) FROM \`service-system\`.\`user\` WH
Run the three in order, with a user that may alter tables. File `03` ends every admin session: everyone signs in again, staff with company `ins`. `99-rollback.sql` in the same folder undoes the three. It fails on the username unique key once two companies have a user with the same username; rename one of them first.
| File | What it does |
|---|---|
| `openspec/changes/archive/2026-12-01-add-lead-dashboard/sql/01-status-change.sql` | Creates `service-counter`.`event_lead_status_change` (every event-lead status change with its time and user) and an index on `event_lead` for the dashboard. DDL. |
| `openspec/changes/archive/2026-12-01-add-lead-dashboard/sql/02-status-change-backfill.sql` | Gives event leads captured before this release a history: OPEN at capture, and the current status at the last update. These times are approximate. Safe to run twice. |
| `openspec/changes/archive/2026-12-01-add-lead-dashboard/sql/03-dashboard-module.sql` | Adds the Dashboard back-office module (`BO_DASHBOARD`). No role gets it; super admins grant it under Roles. |
Run the three in order before the new images go live: the new services-counter writes to the table from `01` on every capture and status edit, and fails without it. `01` needs a user that may create tables. `99-rollback.sql` in the same folder undoes them and deletes the status history.
**Database user:**
- Create one user with `SELECT, INSERT, UPDATE, DELETE, EXECUTE` on the five schemas. EXECUTE is needed: service-member calls a stored function.
- Every Java service reads the same variables (section 6): `MYSQLHOST`, `MYSQLPORT`, `MYSQLUSER`, `MYSQLPWD`.
@@ -293,6 +301,7 @@ data:
- **No email provider yet.** Staff onboarding does not need one: the admin types each new user's first password, and "Set temporary password" on a user's page unlocks a user who forgot theirs. Both force a password change at the next sign-in. Forgot-password and "Send password reset" still create an email with a temporary password. Nobody receives it, but `service-email` saves every email first, so a super admin (or a role granted Emails) can read it under **Emails** and pass the password on in person. The user must change it at the next sign-in. Grant Emails narrowly: it shows every saved email, including other users' temporary passwords, member email-verification codes, and contact or distributor form submissions with the sender's personal data.
- **Sign-in lockout.** 5 failed sign-ins within 15 minutes lock a username, even with the right password, until 15 minutes after the first of those failures, and unknown usernames are counted too. Anyone who knows a username can therefore lock it on purpose. An admin with **Login security** can unlock it at once (Locked tab), and can change the limits there. If every super admin is locked, wait out the period. The lock check fails open: if `service-system` is down, sign-in still works without the lockout.
- **Companies and super admins.** INS and CV each see only their own leads, events, event leads, users, emails, login history and audit log. Staff sign in with their company code, username and password. A super admin leaves Company blank, sees every company (with a company picker in the header), and is the only one who can manage companies, roles, interests, lockout settings and password rules. Changing a company's code renames its staff's sign-in names and signs them out; deactivating a company blocks its staff from signing in. Emails sent from public forms and other system emails have no company, so only super admins see them. Do not give a company's old code to another company while sessions opened under the old code may still be valid: such a session token would resolve to the new company's user of the same name. When in doubt, never reuse a code.
- **Lead dashboard.** Users whose role has the Dashboard module see lead captures, wins, conversion and overdue follow-ups on the home page, for this month, last month or a custom range of up to two years in Malaysian time. A lead counts as converted when its status at an event is WON. Wins and days to win come from the status history, which starts with this release; for older leads it is approximate (see section 3).
- **Reference data from Tastefully.** It still holds some Tastefully business text (message templates with a phone number, bank account and form links; a public image bucket URL; Tastefully usernames in audit columns). Review it before go-live.
- **Other Tastefully defaults.** The sender addresses in `service-email` and the `CUSTOMER_PORTAL_BASE_URL` fallback point at Tastefully. Override them as described in section 6.
- **Leaked SMS key.** An SMS360 API key from Tastefully was in `service-email`'s config and is in git history. It has been removed from the config, but it must be rotated with SMS360 before go-live, by whoever owns that Tastefully account.
@@ -0,0 +1,103 @@
# Lead Dashboard — Design
Date: 2026-12-01. Status: draft for approval.
## Why
Co-Lite exists to generate leads for INS and CV marketing. Managers need to see which events, salespeople and interests produce leads and which of those leads convert. Today the portal home page is a welcome line, and the system keeps only each event lead's current status, so it cannot say when a lead was won or how long it took.
## Goals
- A dashboard on the portal home page showing lead capture and conversion for a chosen period.
- Record every event-lead status change with its time, so the dashboard can count wins in a period and time to win.
- Gate the dashboard with a new ACL module, `BO_DASHBOARD`, assigned to roles like every other module.
- Company scoping as everywhere else: staff see their company, super admins see all or the one picked.
## Non-goals
- New lead statuses or a pipeline editor. The existing statuses stay: OPEN, CONTACTED, QUALIFIED, WON, LOST.
- Member-app conversion (option 2). It comes later as its own change.
- Showing the status timeline on the lead or event-lead screens. The data will exist; a later change can show it.
- Excel export of the dashboard.
- Demographics (age, gender, state) as in the legacy event statistics: Co-Lite leads carry none of those fields.
## Anti-goals
- Numbers that disagree with the Leads and Event Leads listings for the same filter.
- SQL built by string replacement (the legacy report service does this; it is an injection risk).
- A slow home page: every user lands there after sign-in.
## Definitions
- **Capture:** one event lead (a person captured at one event). A person captured at two events is two captures. Conversion is per capture, because the question is which events convert.
- **Won:** an event lead whose current status is WON.
- **Won in period:** a won event lead whose latest change into WON falls in the period.
- **Conversion rate:** of the captures made in the period, the share that are now WON.
- **Days to win:** from capture to the latest change into WON, in whole days. Reported as the median.
- **Overdue follow-up:** an event lead that is not WON or LOST and whose next follow-up date is before today. This is a current count, not tied to the period.
- **Clock:** Asia/Kuala_Lumpur, as in the legacy dashboard.
## What the dashboard shows
- **Period:** This month (the default), Last month, or a custom range. A range of up to 62 days is charted by day; a longer one by month (legacy rule).
- **Company picker:** the existing picker, for super admins only.
- **Tiles:**
- Captures.
- New leads (lead type NEW).
- Won in period.
- Conversion rate.
- Median days to win.
- Overdue follow-ups.
- **Funnel:** the period's captures by current status (OPEN, CONTACTED, QUALIFIED, WON, LOST).
- **Trend chart:** captures and wins per day or month.
- **By event:** each event with captures in the period.
- Columns: event, captures, new, won, conversion rate.
- A super admin viewing all companies also gets a Company column.
- Each row links to that event's leads.
- **By salesperson:** for the period's captures, per salesperson.
- Columns: assigned, worked (status beyond OPEN), won, lost, conversion rate, overdue follow-ups.
- Captures with no salesperson appear as an "Unassigned" row.
- **By interest:** per interest, the captures and wins. A capture with two interests counts under both.
- **Phone width:** tiles stack, and the tables become cards, as on the other listings.
## Status timing
- **New table** `event_lead_status_change` in services-counter, append-only. Columns:
- `id`, `company_id`, `event_lead_id`;
- `from_status` (null for the first row), `to_status`;
- `changed_at`, `changed_by`.
- **Capture** writes the first row: null → initial status, at `captured_at`.
- **An edit that changes status** writes one row in the same transaction. An edit that keeps the status writes nothing.
- **Backfill** for existing event leads, in the change's SQL:
- one row null → OPEN at `captured_at`;
- when the current status is not OPEN, a second row OPEN → status at `updated_at`, or at `captured_at` when `updated_at` is null.
These times are approximate, and the deployment notes say so.
## Access
- **New module** `BO_DASHBOARD`, type M, URL `/`, id `40050000`. The sidebar shows a "Dashboard" link.
- **The home page** shows the dashboard to users with `BO_DASHBOARD`. Everyone else sees today's welcome, not a not-authorised page, because every user lands at home after sign-in.
- **The endpoint** answers 403 without the module.
- **Super admins** pass as they do for every module.
## Approach
Aggregate in services-counter SQL:
- services-counter gets one endpoint, `/counter/dashboard/leads`. It takes `companyId` (null = all), `from`, `to` and the bucket, and runs grouped native queries with bind parameters over `event_lead`, `event_lead_status_change`, `event_lead_interest` and `event`.
- mobile-api adds `GET /api/admin/dashboard/leads` under `@AdminModule("BO_DASHBOARD")`. It applies the company scope, resolves salesperson names in one batch call to services-system, and returns one JSON payload.
Rejected:
- **Aggregating in mobile-api from paged listings:** too many calls, and it gets slower as leads grow.
- **A separate report service like legacy:** a new deployable for one screen.
## Portal
- **Charts:** add `recharts` and copy babyboo's `chart.tsx` wrapper. babyboo already uses both, and the look then matches.
- **The funnel and tables** use existing components (Card, Table, data-table).
## Left to the builder
- Indexes for the dashboard queries, chosen from EXPLAIN on realistic local data: likely `event_lead(company_id, captured_at)` and `event_lead_status_change(event_lead_id, changed_at)`.
- Exact tile layout and copy.
- Message keys for every label (English, as for other screens).
+25
View File
@@ -228,3 +228,28 @@ WHERE u.`type` = 'A' AND EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id`
UPDATE `user` u SET u.`company_id` = 1, u.`username` = CONCAT(u.`username`, '@ins')
WHERE u.`type` = 'A' AND NOT EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id` = u.`id` AND r.`role_id` = 1);
-- add-lead-dashboard/sql/01-status-change.sql (02 backfill has nothing to do on an empty volume)
USE `service-counter`;
CREATE TABLE IF NOT EXISTS `event_lead_status_change` (
`id` bigint NOT NULL AUTO_INCREMENT,
`company_id` bigint NOT NULL,
`event_lead_id` bigint NOT NULL,
`from_status` varchar(10) NULL,
`to_status` varchar(10) NOT NULL,
`changed_at` datetime NOT NULL,
`changed_by` varchar(255) NULL,
PRIMARY KEY (`id`),
KEY `idx_elsc_event_lead` (`event_lead_id`, `changed_at`),
KEY `idx_elsc_company_to_changed` (`company_id`, `to_status`, `changed_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Dashboard capture query: captures by company and capture time.
ALTER TABLE `event_lead` ADD KEY `idx_event_lead_company_captured` (`company_id`, `captured_at`);
-- add-lead-dashboard/sql/03-dashboard-module.sql
USE `service-system`;
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
(40050000, 'BO_DASHBOARD', 'Dashboard', 'BO', 'M', 40000000, '/', 'LayoutDashboard');
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-01
@@ -0,0 +1,95 @@
## Context
Approved product design: `docs/superpowers/specs/2026-12-01-lead-dashboard-design.md` (definitions, figures, access). This file fixes the technical contract so the services-counter, mobile-api and portal tasks can be built in parallel.
Facts the design relies on:
- `event_lead.status` already holds OPEN / CONTACTED / QUALIFIED / WON / LOST (event-lead-capture). Only the current value is stored.
- `event_lead.captured_at` and `updated_at` are `LocalDateTime.now()` in the services-counter JVM, i.e. wall time in the JVM's default zone (UTC in the containers). There is no zone column.
- services-counter has no database tests; every existing test is a Mockito unit test.
- Salesperson names live in services-system; mobile-api already resolves them per user id with a per-request map (`AdminLeadService.salesperson`).
## Decisions
### 1. Status history table
`service-counter.event_lead_status_change`:
- columns `id` bigint PK auto, `company_id` bigint NOT NULL, `event_lead_id` bigint NOT NULL, `from_status` varchar(10) NULL, `to_status` varchar(10) NOT NULL, `changed_at` datetime NOT NULL, `changed_by` varchar(255) NULL;
- key `idx_elsc_event_lead (event_lead_id, changed_at)` and key `idx_elsc_company_to_changed (company_id, to_status, changed_at)`.
`EventLeadService.capture` saves one row (null → initial status, `changed_at` = the event lead's `captured_at`, `changed_by` = doneBy) in the capture transaction. `update` saves one row when the requested status differs from the stored one (`changed_at` = the new `updated_at`). Entity `EventLeadStatusChange`, repository `EventLeadStatusChangeRepository`. Nothing deletes or updates these rows.
Backfill (`sql/02-status-change-backfill.sql`, idempotent: only event leads with no history rows):
- one row null → OPEN at `captured_at`, `changed_by` = `captured_by`;
- where `status <> 'OPEN'`, one row OPEN → status at `COALESCE(updated_at, captured_at)`, `changed_by` = `COALESCE(updated_by, captured_by)`.
### 2. Aggregate in Java over lean rows, not in SQL
services-counter runs three plain native queries with bind parameters and aggregates the rows in a pure Java class (`LeadDashboardCalculator`), which is unit-tested without a database:
1. **Captures:** event leads with `captured_at` in [fromUtc, toUtc) and the company filter, joined to `event` for name and company: `event_lead.id, event_uuid, event name, company_id, salesperson_user_id, lead_type, status, captured_at`.
2. **Wins:** event leads with `status = 'WON'` whose latest history row with `to_status = 'WON'` has `changed_at` in [fromUtc, toUtc): `event_lead.id, captured_at, won_at`.
3. **Overdue:** `salesperson_user_id, COUNT(*)` for status not in (WON, LOST) and `next_follow_up_date < today`, grouped by salesperson.
Interests for the captures come from the existing `EventLeadInterestRepository.findByIdEventLeadIdIn`, in chunks of 1000 ids, and interest names from `InterestRepository`.
Rejected: one grouped SQL query per figure. Its correctness could only be checked against a live database (no DB tests here), and adding Testcontainers is a new build dependency for one screen.
`ponytail:` row volume is one row per capture in the period. Fine for thousands per period; move the sums into SQL when one company captures hundreds of thousands of leads a year.
### 3. Time zone
mobile-api turns the period into dates; services-counter turns `[from 00:00, to+1 00:00)` in Asia/Kuala_Lumpur into the JVM default zone's wall time for the queries, and turns each stored time back to a Malaysian date for bucketing. "Today" for overdue is today in Asia/Kuala_Lumpur.
### 4. services-counter contract
`POST /counter/dashboard/leads` (route already under `/counter/**`), body:
```json
{ "companyId": 2, "from": "2026-11-01", "to": "2026-11-30", "bucket": "DAY" }
```
`companyId` null = all companies. `bucket` is `DAY` or `MONTH`. `from` after `to` → 400 `INVALID_PERIOD`. Response:
```json
{
"captures": 10, "newLeads": 6, "wonInPeriod": 3, "medianDaysToWin": 5, "overdueFollowUps": 4,
"funnel": { "OPEN": 3, "CONTACTED": 1, "QUALIFIED": 1, "WON": 3, "LOST": 2 },
"trend": [ { "bucket": "2026-11-01", "captures": 2, "wins": 0 } ],
"events": [ { "eventUuid": "123", "name": "KL Expo", "companyId": 2, "captures": 10, "newLeads": 6, "won": 3 } ],
"salespeople": [ { "userId": 7, "assigned": 4, "worked": 3, "won": 1, "lost": 1, "overdue": 2 } ],
"interests": [ { "interestId": 5, "name": "Cookware", "captures": 4, "won": 1 } ]
}
```
- `medianDaysToWin` is null when there are no wins; with an even count it is the lower middle value (whole days).
- `trend` lists every bucket in the period, zero-filled; a month bucket is the month's first day.
- `events` is ordered by captures descending, then name; `salespeople` by assigned descending, with `userId` null for Unassigned; `salespeople` also includes a salesperson with overdue follow-ups but no captures in the period (assigned 0). `interests` by captures descending, then name.
- `eventUuid` is a string (JavaScript loses precision on snowflake ids).
Rates are not sent; the portal divides.
### 5. mobile-api contract
`GET /api/admin/dashboard/leads?from=2026-11-01&to=2026-11-30&companyId=2` under `@AdminModule("BO_DASHBOARD")`:
- `from`/`to` optional; when absent, from = first day of the current Malaysian month, to = today (Malaysia).
- Bad date format, from after to, or a range of more than 731 days (two years) → 400 `INVALID_PERIOD` (ProblemDetail: `code`, `detail`). The cap keeps one request from building an unbounded bucket list in services-counter, which also refuses a range over 731 days.
- bucket = `DAY` when `to - from + 1 <= 62` days, else `MONTH`.
- company from `AdminCompanyScope.scope(caller, companyId)`.
- Response: the counter response plus `from`, `to`, `bucket`, and each salesperson row gains `name` (the user's name, or null for Unassigned and for a user that no longer exists). Salesperson names are resolved with the existing per-request map pattern.
### 6. Module
`service-system.module` row `(40050000, 'BO_DASHBOARD', 'Dashboard', 'BO', 'M', 40000000, '/', 'LayoutDashboard')`. No role grant: super admins grant it under Roles. Id 40050000 sorts it first in the sidebar, which orders by module id. The portal's route gate (`ROUTE_MODULES`) does not list `/`: the home page itself decides between the dashboard and the welcome, using `hasModule("BO_DASHBOARD")`.
### 7. Portal
- `recharts` added to `package.json`; `app/components/ui/chart.tsx` copied from babyboo's portal.
- `app/lib/services/adminDashboard.ts`: types for decision 5 and `getLeadDashboard({from, to, companyId})`.
- `app/page.tsx`: welcome for users without the module; otherwise the dashboard with a period control (This month / Last month / Custom with the existing date picker), the company picker for super admins (via `useCompanyScope`), tiles, funnel bars, a recharts line or bar chart of captures and wins, and three tables (cards below `md`). Event rows link to `/event-leads/{eventUuid}`. The Company column on the event table shows only when `showCompanyColumn`.
- Rates show as whole percent; a null median or zero captures shows "–".
- All labels are message keys with English defaults, as on other screens.
## Risks
- Backfilled history times are approximate (deployment notes say so).
- A lead whose status was set by a direct DB edit has no history row for that change; the dashboard then misses that win. Nothing in the app does this.
- `captured_at` stored in the JVM zone: if production pods ever run in a different zone from when rows were written, older rows shift. Same risk already exists for every listing.
@@ -0,0 +1,33 @@
## Why
Co-Lite exists to generate leads for INS and CV marketing. Managers need to see which events, salespeople and interests produce leads and which of those leads convert (status WON). Today the portal home page is a welcome line, and the system keeps only each event lead's current status, so it cannot say when a lead was won or how long it took. Approved design: `docs/superpowers/specs/2026-12-01-lead-dashboard-design.md`.
## What Changes
- Every event-lead status change is recorded with its time and who made it. Capture records the first status. Existing event leads are backfilled with approximate times.
- A lead dashboard on the portal home page for a chosen period (this month, last month, or a custom range):
- tiles: captures, new leads, won in period, conversion rate, median days to win, overdue follow-ups;
- a status funnel;
- a trend of captures and wins;
- tables by event, by salesperson and by interest.
- A new back-office module `BO_DASHBOARD` gates the dashboard. Users without it keep the welcome page.
- Company scoping as on every other admin screen.
- The admin portal gains the `recharts` dependency (already used by babyboo's portal) for the trend chart.
## Capabilities
### New Capabilities
- `lead-dashboard`: the dashboard, its definitions, period rules, access and company scope.
### Modified Capabilities
- `event-lead-capture`: adds the status change history requirement.
## Impact
- Database `service-counter`: new table `event_lead_status_change`, a backfill, and an index on `event_lead`. `service-system`: one `module` row. SQL in `sql/`, mirrored in `local/seed/03-colite.sql`.
- `solvway-services-counter`: history writes on capture and edit; a new dashboard endpoint.
- `solvway-mobile-api`: `GET /api/admin/dashboard/leads`.
- `solvway-admin-portal`: home page, sidebar link, `recharts`.
- `docs/deployment.md`: the new SQL files.
@@ -0,0 +1,22 @@
## ADDED Requirements
### Requirement: Event lead status history
The system SHALL record every change of an event lead's status with the previous status, the new status, the time and the user who made it. Capturing an event lead SHALL record its first status with no previous status, at the capture time. An edit that leaves the status unchanged SHALL record nothing. The history SHALL never be edited or deleted through the application.
#### Scenario: Capture records the first status
- **WHEN** staff capture a lead at an event with no status chosen
- **THEN** the history holds one entry from no status to OPEN at the capture time, by that user
#### Scenario: Status change recorded
- **GIVEN** an OPEN event lead
- **WHEN** staff change its status to CONTACTED and later to WON
- **THEN** the history holds OPEN to CONTACTED and CONTACTED to WON, each with its time and user
#### Scenario: Edit without a status change
- **GIVEN** a CONTACTED event lead
- **WHEN** staff change only its temperature and notes
- **THEN** no history entry is added
@@ -0,0 +1,152 @@
## ADDED Requirements
### Requirement: Dashboard access
The system SHALL show the lead dashboard on the back-office home page to users granted the `BO_DASHBOARD` module, and SHALL show users without it the welcome message instead of a not-authorised page. The dashboard endpoint SHALL answer 403 to a user without `BO_DASHBOARD`. The sidebar SHALL show a Dashboard link to users with the module.
#### Scenario: Granted user
- **GIVEN** a role holding `BO_DASHBOARD` is assigned to `sales1`
- **WHEN** `sales1` signs in
- **THEN** the home page shows the lead dashboard and the sidebar shows Dashboard
#### Scenario: User without the module
- **WHEN** a user without `BO_DASHBOARD` opens the home page or calls the dashboard endpoint
- **THEN** the page shows the welcome message and the endpoint responds 403
### Requirement: Dashboard period
The dashboard SHALL cover a period of whole days in Malaysia time (Asia/Kuala_Lumpur): this month up to today (the default), last month, or a custom range from one date to another, both included. A range whose start is after its end, or that spans more than 731 days, SHALL be refused with a message. The trend SHALL be counted by day for a period of up to 62 days and by month for a longer one, and SHALL list every day or month in the period, with zero where nothing happened.
#### Scenario: Default period
- **WHEN** a user opens the dashboard on 2026-12-10
- **THEN** it covers 2026-12-01 to 2026-12-10, with one trend point per day
#### Scenario: Long range counted by month
- **WHEN** the user picks 2026-01-01 to 2026-12-31
- **THEN** the trend has one point per month, January to December
#### Scenario: Day boundary in Malaysia time
- **GIVEN** a lead captured at 2026-11-30 23:30 Malaysia time
- **WHEN** the user views 2026-11-01 to 2026-11-30
- **THEN** the capture is counted on 30 November
#### Scenario: Reversed range
- **WHEN** the user picks a start date after the end date
- **THEN** the dashboard shows a message and no figures, and the endpoint responds 400
#### Scenario: Range too long
- **WHEN** the user picks 2024-01-01 to 2026-12-31
- **THEN** the dashboard shows a message and no figures, and the endpoint responds 400
### Requirement: Capture figures
For the chosen period the dashboard SHALL show the captures (event leads captured in the period, so a person captured at two events counts twice), the new leads (captures whose lead type is NEW), the conversion rate (the share of the period's captures whose current status is WON, shown as a dash when there are no captures), a funnel of the period's captures by current status (OPEN, CONTACTED, QUALIFIED, WON, LOST) and the captures in the trend.
#### Scenario: Conversion of the period's captures
- **GIVEN** 10 leads captured in November, 3 of them now WON and 2 LOST
- **WHEN** the user views November
- **THEN** captures show 10, conversion rate 30%, and the funnel shows WON 3 and LOST 2
#### Scenario: No captures
- **WHEN** the user views a period with no captures
- **THEN** captures show 0 and the conversion rate shows a dash
### Requirement: Win figures
The dashboard SHALL count as won in the period every event lead whose current status is WON and whose latest change to WON falls in the period, whenever it was captured. It SHALL show that count, the wins in the trend, and the median of whole days from capture to the latest change to WON over those event leads, shown as a dash when there are none.
#### Scenario: Win of an older capture
- **GIVEN** a lead captured in October and changed to WON on 5 November
- **WHEN** the user views November
- **THEN** won in period counts it and the November captures do not
#### Scenario: Reopened lead
- **GIVEN** a lead changed to WON on 3 November, back to QUALIFIED on 4 November, and to WON again on 20 November
- **WHEN** the user views 1 to 10 November
- **THEN** won in period does not count it, because its latest change to WON is 20 November
#### Scenario: Median days to win
- **GIVEN** three leads won in November, 2, 5 and 30 days after capture
- **WHEN** the user views November
- **THEN** median days to win shows 5
### Requirement: Overdue follow-ups
The dashboard SHALL show the event leads that are not WON or LOST and whose next follow-up date is before today in Malaysia time, whatever the chosen period.
#### Scenario: Overdue counted regardless of period
- **GIVEN** an OPEN lead captured in August with next follow-up 2026-12-01
- **WHEN** the user views November on 2026-12-05
- **THEN** overdue follow-ups count it
### Requirement: Breakdown by event
The dashboard SHALL list each event with captures in the period, most captures first, with its captures, new leads, won and conversion rate, and each row SHALL open that event's leads listing.
#### Scenario: Event drill-down
- **WHEN** the user selects an event row
- **THEN** that event's leads listing opens
### Requirement: Breakdown by salesperson
The dashboard SHALL list, for the period's captures, each salesperson's assigned, worked (status other than OPEN), won, lost and conversion rate, with their current overdue follow-ups, and SHALL show captures with no salesperson as Unassigned.
#### Scenario: Salesperson row
- **GIVEN** in November `sales1` was assigned 4 captures: 1 OPEN, 1 CONTACTED, 1 WON and 1 LOST
- **WHEN** the user views November
- **THEN** sales1's row shows assigned 4, worked 3, won 1, lost 1 and conversion rate 25%
#### Scenario: Unassigned captures
- **GIVEN** 2 November captures have no salesperson
- **WHEN** the user views November
- **THEN** an Unassigned row shows assigned 2
### Requirement: Breakdown by interest
The dashboard SHALL list each interest with the period's captures tagged with it and how many of them are now WON. A capture with two interests SHALL count under both.
#### Scenario: Two interests
- **GIVEN** a November capture tagged `Cookware` and `Kitchen appliances`, now WON
- **WHEN** the user views November
- **THEN** both interests count 1 capture and 1 won
### Requirement: Phone width
The dashboard SHALL be usable on a 360 px wide screen without sideways scrolling.
#### Scenario: Phone
- **WHEN** a user opens the dashboard at 360 px
- **THEN** the tiles stack and the breakdowns show as cards
### Requirement: Dashboard company scope
The dashboard SHALL count only the records of the caller's company for company staff. A super admin SHALL see every company's records by default and SHALL be able to narrow the dashboard to one company with the company picker; while all companies are shown, the by-event list SHALL show each event's company.
#### Scenario: Staff see their company
- **GIVEN** leads captured at INS and at CV events in November
- **WHEN** an INS user with `BO_DASHBOARD` views November
- **THEN** every figure counts INS records only
#### Scenario: Super admin picks a company
- **WHEN** a super admin picks CV in the company picker
- **THEN** every figure counts CV records only
@@ -0,0 +1,19 @@
-- Co-Lite change add-lead-dashboard: event lead status history (design decision 1).
-- Target: `service-counter`. Additive only. Run before the new images go live (services-counter writes this table), then 02.
USE `service-counter`;
CREATE TABLE IF NOT EXISTS `event_lead_status_change` (
`id` bigint NOT NULL AUTO_INCREMENT,
`company_id` bigint NOT NULL,
`event_lead_id` bigint NOT NULL,
`from_status` varchar(10) NULL,
`to_status` varchar(10) NOT NULL,
`changed_at` datetime NOT NULL,
`changed_by` varchar(255) NULL,
PRIMARY KEY (`id`),
KEY `idx_elsc_event_lead` (`event_lead_id`, `changed_at`),
KEY `idx_elsc_company_to_changed` (`company_id`, `to_status`, `changed_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Dashboard capture query: captures by company and capture time.
ALTER TABLE `event_lead` ADD KEY `idx_event_lead_company_captured` (`company_id`, `captured_at`);
@@ -0,0 +1,15 @@
-- Co-Lite change add-lead-dashboard: history for event leads captured before the history existed.
-- Target: `service-counter`. Idempotent: touches only event leads with no history row. Times are approximate:
-- the first status at capture, the current status (if not OPEN) at the last update.
USE `service-counter`;
INSERT INTO `event_lead_status_change` (`company_id`, `event_lead_id`, `from_status`, `to_status`, `changed_at`, `changed_by`)
SELECT el.company_id, el.id, NULL, 'OPEN', el.captured_at, el.captured_by
FROM `event_lead` el
WHERE NOT EXISTS (SELECT 1 FROM `event_lead_status_change` s WHERE s.event_lead_id = el.id);
INSERT INTO `event_lead_status_change` (`company_id`, `event_lead_id`, `from_status`, `to_status`, `changed_at`, `changed_by`)
SELECT el.company_id, el.id, 'OPEN', el.status, COALESCE(el.updated_at, el.captured_at), COALESCE(el.updated_by, el.captured_by)
FROM `event_lead` el
WHERE el.status <> 'OPEN'
AND NOT EXISTS (SELECT 1 FROM `event_lead_status_change` s WHERE s.event_lead_id = el.id AND s.to_status = el.status);
@@ -0,0 +1,7 @@
-- Co-Lite change add-lead-dashboard: the Dashboard back-office module (area BO).
-- Target: `service-system`.`module`. Additive only. Run once, after the release package.
-- No role grant: super admins see every module; they grant BO_DASHBOARD to other roles under Roles.
USE `service-system`;
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
(40050000, 'BO_DASHBOARD', 'Dashboard', 'BO', 'M', 40000000, '/', 'LayoutDashboard');
@@ -0,0 +1,8 @@
-- Co-Lite change add-lead-dashboard: rollback. Drops the status history (its data is lost).
USE `service-system`;
DELETE FROM `modules_roles` WHERE `module_id` = 40050000;
DELETE FROM `module` WHERE `id` = 40050000;
USE `service-counter`;
ALTER TABLE `event_lead` DROP KEY `idx_event_lead_company_captured`;
DROP TABLE IF EXISTS `event_lead_status_change`;
@@ -0,0 +1,63 @@
# Tasks
Design: `design.md` (technical contract) and `docs/superpowers/specs/2026-12-01-lead-dashboard-design.md` (product).
Waves:
- Wave 0 (serial, controller): 1.1 and 1.2 touch hotspots (SQL, seed, `package.json`).
- Wave 1 (parallel, 3 implementers): 2.1, 3.1 and 4.1 build against the fixed contracts in design decisions 4 and 5. Scopes do not overlap: each touches one module.
- Wave 2 (serial, controller): 5.1.
## 1. Data, module and chart dependency
- [x] 1.1 SQL `sql/01..03` and `99-rollback.sql`; mirror 01 and 03 in `local/seed/03-colite.sql` (02 has nothing to backfill on an empty volume); apply 01, 02 and 03 to the local database.
- Depends on: none
- Scope: `local/seed/**`, `openspec/changes/add-lead-dashboard/sql/**`
- Verify: `SELECT` shows the table, the index, the backfilled rows and the module row.
- [x] 1.2 Portal: add `recharts` (same major as babyboo's portal) with `npm install`, and copy babyboo's `app/components/ui/chart.tsx`.
- Depends on: none
- Scope: `solvway-admin-portal/package.json`, `solvway-admin-portal/package-lock.json`, `solvway-admin-portal/app/components/ui/chart.tsx`
- Verify: `cd solvway-admin-portal && npm run lint && npx tsc --noEmit && npx vitest run`
## 2. services-counter
- [x] 2.1 Status history writes (decision 1) and the dashboard endpoint (decisions 2 to 4).
- Tests first:
- capture saves one history row null → initial status at the capture time, by doneBy;
- update saves one row when the status changes and none when it stays;
- the calculator, from in-memory rows: captures, new leads, funnel, won in period (latest WON only), median days (odd, even, none), overdue per salesperson, Unassigned, salesperson with overdue only, interest double-count, event ordering, zero-filled day and month trend, Malaysia day boundary from JVM-zone times;
- the endpoint rejects from after to with 400 `INVALID_PERIOD` and passes a null company as all companies.
- Scope: `solvway-services-counter/src/**`
- Verify: `mvn -T 1C -q -pl solvway-services-counter verify`
## 3. mobile-api
- [x] 3.1 `GET /api/admin/dashboard/leads` (decision 5).
- Tests first:
- default period is this Malaysian month to today; DAY bucket up to 62 days, MONTH above;
- bad date and from after to → 400 `INVALID_PERIOD`;
- staff are scoped to their company, a super admin's `companyId` is passed through, null for all;
- salesperson names resolved, null for Unassigned and for a missing user;
- the endpoint is gated by `BO_DASHBOARD` (aspect test with the annotation).
- Scope: `solvway-mobile-api/src/**`
- Verify: `mvn -T 1C -q -pl solvway-mobile-api verify`
## 4. Portal
- [x] 4.1 Home page dashboard (decision 7).
- Tests first:
- without `BO_DASHBOARD` the welcome shows and the dashboard API is not called;
- with it: tiles, funnel, chart container, the three tables with Unassigned, whole-percent rates and "–" for null median and zero captures;
- period presets send the right `from`/`to`; a reversed custom range shows the error message;
- a super admin's picker sends `companyId` and shows the Company column only for all companies;
- an event row links to `/event-leads/{eventUuid}`;
- the hard-coded copy sweep stays green (labels as message keys).
- Includes the Next proxy route `app/api/dashboard/leads/route.ts` (added after review: the first plan left it out).
- Scope: `solvway-admin-portal/app/api/dashboard/**`, `solvway-admin-portal/app/page.tsx`, `solvway-admin-portal/app/page*.test.tsx`, `solvway-admin-portal/app/components/dashboard/**`, `solvway-admin-portal/app/lib/services/adminDashboard*.ts`, `solvway-admin-portal/app/lib/i18n/defaultMessages.ts`
- Verify: `cd solvway-admin-portal && npm run lint && npx tsc --noEmit && npx vitest run`
## 5. Release
- [x] 5.1 `docs/deployment.md` lists the SQL; live check against the local stack (seeded INS and CV event leads with status changes), and Playwright at 1280 and 360 px for a granted user, a user without the module, and a super admin switching company.
- Depends on: 1.1 to 4.1
- Scope: `docs/deployment.md`, `openspec/changes/add-lead-dashboard/tasks.md`
- Verify: full `mvn -T 1C -q verify` of the three touched Maven modules and the portal verify.
@@ -0,0 +1,38 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
type Req = Parameters<typeof GET>[0];
const req = (url: string) => new Request(`http://localhost${url}`) as unknown as Req;
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { captures: 1 } });
mocks.getToken.mockReset().mockResolvedValue("jwt-abc");
});
describe("/api/dashboard/leads", () => {
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await GET(req("/api/dashboard/leads"));
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards the query string to mobile-api", async () => {
const res = await GET(req("/api/dashboard/leads?from=2026-11-01&to=2026-11-30&companyId=2"));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ captures: 1 });
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/dashboard/leads?from=2026-11-01&to=2026-11-30&companyId=2", { token: "jwt-abc" });
});
it("passes an upstream INVALID_PERIOD with its code", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Start date must be on or before end date.", status: 400, code: "INVALID_PERIOD" });
const res = await GET(req("/api/dashboard/leads?from=2026-11-30&to=2026-11-01"));
expect(res.status).toBe(400);
expect(((await res.json()) as Record<string, unknown>).code).toBe("INVALID_PERIOD");
});
});
@@ -0,0 +1,13 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
// Proxy for /api/admin/dashboard/leads; mobile-api owns period validation and the BO_DASHBOARD guard.
export async function GET(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
const result = await callMobileApi<unknown>(`/api/admin/dashboard/leads${new URL(req.url).search}`, { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,60 @@
import type { ReactNode } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
import { EmptyState } from "@/app/components/ui/states";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table";
import { cn } from "@/app/lib/utils";
export interface DashColumn<R> {
label: string;
numeric?: boolean;
cell: (row: R) => ReactNode;
}
/** A titled table that stacks into label/value cards below md (one DOM, CSS only). */
export function DashTable<R>({ title, empty, columns, rows, rowKey }: {
title: string;
empty: string;
columns: DashColumn<R>[];
rows: R[];
rowKey: (row: R) => string;
}) {
return (
<Card>
<CardHeader><CardTitle className="text-base">{title}</CardTitle></CardHeader>
<CardContent>
{rows.length === 0 ? (
<EmptyState title={empty} className="py-6" />
) : (
<Table aria-label={title} className="max-md:block">
<TableHeader className="max-md:hidden">
<TableRow>
{columns.map((c) => (
<TableHead key={c.label} className={cn(c.numeric && "text-right")}>{c.label}</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody className="max-md:block max-md:[&_tr:last-child]:border">
{rows.map((row) => (
<TableRow key={rowKey(row)} className="max-md:mb-3 max-md:block max-md:rounded-lg max-md:border max-md:p-2">
{columns.map((c) => (
<TableCell
key={c.label}
data-label={c.label}
className={cn(
"max-md:flex max-md:justify-between max-md:gap-4 max-md:whitespace-normal max-md:px-1 max-md:py-1",
"max-md:before:font-medium max-md:before:text-muted-foreground max-md:before:content-[attr(data-label)]",
c.numeric && "text-right tabular max-md:text-left",
)}
>
{c.cell(row)}
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,189 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from "recharts";
import { Button } from "@/app/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from "@/app/components/ui/chart";
import { DatePicker } from "@/app/components/ui/date-picker";
import { ErrorState } from "@/app/components/ui/states";
import { Skeleton } from "@/app/components/ui/skeleton";
import { ApiError } from "@/app/lib/clientApi";
import { useCompanyScope } from "@/app/lib/CompanyScope";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { getLeadDashboard, type LeadDashboard } from "@/app/lib/services/adminDashboard";
import { DashTable, type DashColumn } from "./DashTable";
type Preset = "this" | "last" | "custom";
type Range = { from?: string; to?: string };
const DASH = "–";
const pct = (num: number, den: number) => (den > 0 ? `${Math.round((num / den) * 100)}%` : DASH);
/** First and last day of the previous calendar month, as seen in Kuala Lumpur right now. */
function lastMonthRange(): Range {
const today = new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Kuala_Lumpur" }).format(new Date());
const [y, m] = today.split("-").map(Number);
const py = m === 1 ? y - 1 : y;
const pm = m === 1 ? 12 : m - 1;
const mm = String(pm).padStart(2, "0");
const lastDay = new Date(Date.UTC(y, m - 1, 0)).getUTCDate();
return { from: `${py}-${mm}-01`, to: `${py}-${mm}-${lastDay}` };
}
function bucketLabel(bucket: string, kind: "DAY" | "MONTH"): string {
const [y, m, d] = bucket.split("-");
if (kind === "DAY") return `${d}/${m}`;
return new Date(Date.UTC(Number(y), Number(m) - 1, 1)).toLocaleString("en-GB", { month: "short", year: "numeric", timeZone: "UTC" });
}
function Tile({ label, value }: { label: string; value: string }) {
return (
<div role="group" aria-label={label} className="rounded-xl border bg-card p-4">
<div className="text-sm text-muted-foreground">{label}</div>
<div className="mt-1 text-2xl font-semibold tabular">{value}</div>
</div>
);
}
export function LeadDashboard() {
const t = useT();
const { companyId, showCompanyColumn, codeOf } = useCompanyScope();
const [preset, setPreset] = useState<Preset>("this");
const [customFrom, setCustomFrom] = useState("");
const [customTo, setCustomTo] = useState("");
const [data, setData] = useState<LeadDashboard | null>(null);
const [error, setError] = useState<string | null>(null);
const [refusedPeriod, setRefusedPeriod] = useState(false);
const [reloadKey, setReloadKey] = useState(0);
const range = useMemo<Range | null>(() => {
if (preset === "this") return {};
if (preset === "last") return lastMonthRange();
return customFrom && customTo && customFrom <= customTo ? { from: customFrom, to: customTo } : null;
}, [preset, customFrom, customTo]);
const reversed = preset === "custom" && !!customFrom && !!customTo && customFrom > customTo;
const from = range?.from;
const to = range?.to;
useEffect(() => {
if (!range) return;
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets data/error before the period/company/reloadKey-triggered fetch below, which is the actual synchronization.
setData(null);
setError(null);
getLeadDashboard({ from, to, companyId })
.then((d) => { if (!cancelled) setData(d); })
.catch((err: unknown) => {
if (cancelled) return;
const refused = err instanceof ApiError && (err.data as { code?: string } | undefined)?.code === "INVALID_PERIOD";
setError(refused ? err.message : t("DashLoadFailed"));
setRefusedPeriod(refused);
});
return () => { cancelled = true; };
// eslint-disable-next-line react-hooks/exhaustive-deps -- `range` is derived from from/to.
}, [from, to, companyId, reloadKey, !!range, t]);
const presets: [Preset, string][] = [["this", t("DashThisMonth")], ["last", t("DashLastMonth")], ["custom", t("DashCustom")]];
const chartConfig = { captures: { label: t("DashCaptures"), color: "var(--chart-1)" }, wins: { label: t("DashWins"), color: "var(--chart-2)" } } satisfies ChartConfig;
const eventCols: DashColumn<LeadDashboard["events"][number]>[] = [
{ label: t("DashEvent"), cell: (r) => <Link href={`/event-leads/${r.eventUuid}`} className="font-medium text-primary underline-offset-4 hover:underline">{r.name}</Link> },
...(showCompanyColumn ? [{ label: t("Company"), cell: (r: { companyId: number }) => codeOf(r.companyId) }] : []),
{ label: t("DashCaptures"), numeric: true, cell: (r) => r.captures },
{ label: t("LeadNew"), numeric: true, cell: (r) => r.newLeads },
{ label: t("LeadWon"), numeric: true, cell: (r) => r.won },
{ label: t("DashConversion"), numeric: true, cell: (r) => pct(r.won, r.captures) },
];
const salesCols: DashColumn<LeadDashboard["salespeople"][number]>[] = [
{ label: t("DashSalesperson"), cell: (r) => (r.userId == null ? t("DashUnassigned") : r.name ?? t("DashUnknownUser")) },
{ label: t("DashAssigned"), numeric: true, cell: (r) => r.assigned },
{ label: t("DashWorked"), numeric: true, cell: (r) => r.worked },
{ label: t("LeadWon"), numeric: true, cell: (r) => r.won },
{ label: t("LeadLost"), numeric: true, cell: (r) => r.lost },
{ label: t("DashConversion"), numeric: true, cell: (r) => pct(r.won, r.assigned) },
{ label: t("DashOverdueShort"), numeric: true, cell: (r) => r.overdue },
];
const interestCols: DashColumn<LeadDashboard["interests"][number]>[] = [
{ label: t("DashInterest"), cell: (r) => r.name },
{ label: t("DashCaptures"), numeric: true, cell: (r) => r.captures },
{ label: t("LeadWon"), numeric: true, cell: (r) => r.won },
];
const funnelRows: [keyof LeadDashboard["funnel"], string][] = [
["OPEN", t("LeadOpen")], ["CONTACTED", t("LeadContacted")], ["QUALIFIED", t("LeadQualified")], ["WON", t("LeadWon")], ["LOST", t("LeadLost")],
];
return (
<div className="space-y-4">
<div className="flex flex-wrap items-end gap-2">
{presets.map(([key, label]) => (
<Button key={key} variant={preset === key ? "default" : "outline"} aria-pressed={preset === key} onClick={() => setPreset(key)}>{label}</Button>
))}
{preset === "custom" && (
<>
<DatePicker aria-label={t("DashFrom")} value={customFrom} onChange={setCustomFrom} className="w-40" />
<DatePicker aria-label={t("DashTo")} value={customTo} onChange={setCustomTo} className="w-40" />
</>
)}
</div>
{reversed && <p role="alert" className="text-sm text-destructive">{t("DashRangeReversed")}</p>}
{range && error && <ErrorState message={error} onRetry={refusedPeriod ? undefined : () => setReloadKey((k) => k + 1)} />}
{range && !error && !data && <Skeleton className="h-40 w-full" />}
{range && data && (
<>
<div className="grid grid-cols-2 gap-3 lg:grid-cols-6">
<Tile label={t("DashCaptures")} value={String(data.captures)} />
<Tile label={t("DashNewLeads")} value={String(data.newLeads)} />
<Tile label={t("DashWonInPeriod")} value={String(data.wonInPeriod)} />
<Tile label={t("DashConversionRate")} value={pct(data.funnel.WON, data.captures)} />
<Tile label={t("DashMedianDays")} value={data.medianDaysToWin == null ? DASH : String(data.medianDaysToWin)} />
<Tile label={t("DashOverdue")} value={String(data.overdueFollowUps)} />
</div>
<div className="grid gap-4 lg:grid-cols-2">
<Card>
<CardHeader><CardTitle className="text-base">{t("DashFunnel")}</CardTitle></CardHeader>
<CardContent>
<ul aria-label={t("DashLeadFunnelLabel")} className="space-y-2">
{funnelRows.map(([key, label]) => {
const max = Math.max(1, ...Object.values(data.funnel));
return (
<li key={key} className="flex items-center gap-2 text-sm">
<span className="w-24 shrink-0">{label}</span>
<span className="h-4 min-w-0 flex-1"><span className="block h-full rounded bg-primary" style={{ width: `${(data.funnel[key] / max) * 100}%` }} /></span>
<span className="w-10 shrink-0 text-right tabular">{data.funnel[key]}</span>
</li>
);
})}
</ul>
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle className="text-base">{t("DashTrend")}</CardTitle></CardHeader>
<CardContent>
<ChartContainer config={chartConfig} role="img" aria-label={t("DashTrend")} className="aspect-auto h-56 w-full">
<BarChart data={data.trend.map((p) => ({ ...p, label: bucketLabel(p.bucket, data.bucket) }))}>
<CartesianGrid vertical={false} />
<XAxis dataKey="label" tickLine={false} axisLine={false} />
<YAxis allowDecimals={false} width={32} tickLine={false} axisLine={false} />
<ChartTooltip content={<ChartTooltipContent />} />
<Bar dataKey="captures" fill="var(--color-captures)" radius={2} />
<Bar dataKey="wins" fill="var(--color-wins)" radius={2} />
</BarChart>
</ChartContainer>
</CardContent>
</Card>
</div>
<DashTable title={t("DashByEvent")} empty={t("DashEmpty")} columns={eventCols} rows={data.events} rowKey={(r) => r.eventUuid} />
<DashTable title={t("DashBySalesperson")} empty={t("DashEmpty")} columns={salesCols} rows={data.salespeople} rowKey={(r) => String(r.userId)} />
<DashTable title={t("DashByInterest")} empty={t("DashEmpty")} columns={interestCols} rows={data.interests} rowKey={(r) => String(r.interestId)} />
</>
)}
</div>
);
}
@@ -0,0 +1,372 @@
import * as React from "react"
import * as RechartsPrimitive from "recharts"
import type { TooltipValueType } from "recharts"
import { cn } from "@/app/lib/utils"
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: "", dark: ".dark" } as const
const INITIAL_DIMENSION = { width: 320, height: 200 } as const
type TooltipNameType = number | string
export type ChartConfig = Record<
string,
{
label?: React.ReactNode
icon?: React.ComponentType
} & (
| { color?: string; theme?: never }
| { color?: never; theme: Record<keyof typeof THEMES, string> }
)
>
type ChartContextProps = {
config: ChartConfig
}
const ChartContext = React.createContext<ChartContextProps | null>(null)
function useChart() {
const context = React.useContext(ChartContext)
if (!context) {
throw new Error("useChart must be used within a <ChartContainer />")
}
return context
}
function ChartContainer({
id,
className,
children,
config,
initialDimension = INITIAL_DIMENSION,
...props
}: React.ComponentProps<"div"> & {
config: ChartConfig
children: React.ComponentProps<
typeof RechartsPrimitive.ResponsiveContainer
>["children"]
initialDimension?: {
width: number
height: number
}
}) {
const uniqueId = React.useId()
const chartId = `chart-${id ?? uniqueId.replace(/:/g, "")}`
return (
<ChartContext.Provider value={{ config }}>
<div
data-slot="chart"
data-chart={chartId}
className={cn(
"flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector]:outline-none [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-none",
className
)}
{...props}
>
<ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer
initialDimension={initialDimension}
>
{children}
</RechartsPrimitive.ResponsiveContainer>
</div>
</ChartContext.Provider>
)
}
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
const colorConfig = Object.entries(config).filter(
([, config]) => config.theme ?? config.color
)
if (!colorConfig.length) {
return null
}
return (
<style
dangerouslySetInnerHTML={{
__html: Object.entries(THEMES)
.map(
([theme, prefix]) => `
${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
const color =
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ??
itemConfig.color
return color ? ` --color-${key}: ${color};` : null
})
.join("\n")}
}
`
)
.join("\n"),
}}
/>
)
}
const ChartTooltip = RechartsPrimitive.Tooltip
function ChartTooltipContent({
active,
payload,
className,
indicator = "dot",
hideLabel = false,
hideIndicator = false,
label,
labelFormatter,
labelClassName,
formatter,
color,
nameKey,
labelKey,
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
React.ComponentProps<"div"> & {
hideLabel?: boolean
hideIndicator?: boolean
indicator?: "line" | "dot" | "dashed"
nameKey?: string
labelKey?: string
} & Omit<
RechartsPrimitive.DefaultTooltipContentProps<
TooltipValueType,
TooltipNameType
>,
"accessibilityLayer"
>) {
const { config } = useChart()
const tooltipLabel = React.useMemo(() => {
if (hideLabel || !payload?.length) {
return null
}
const [item] = payload
const key = `${labelKey ?? item?.dataKey ?? item?.name ?? "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const value =
!labelKey && typeof label === "string"
? (config[label]?.label ?? label)
: itemConfig?.label
if (labelFormatter) {
return (
<div className={cn("font-medium", labelClassName)}>
{labelFormatter(value, payload)}
</div>
)
}
if (!value) {
return null
}
return <div className={cn("font-medium", labelClassName)}>{value}</div>
}, [
label,
labelFormatter,
payload,
hideLabel,
labelClassName,
config,
labelKey,
])
if (!active || !payload?.length) {
return null
}
const nestLabel = payload.length === 1 && indicator !== "dot"
return (
<div
className={cn(
"grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",
className
)}
>
{!nestLabel ? tooltipLabel : null}
<div className="grid gap-1.5">
{payload
.filter((item) => item.type !== "none")
.map((item, index) => {
const key = `${nameKey ?? item.name ?? item.dataKey ?? "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const indicatorColor = color ?? item.payload?.fill ?? item.color
return (
<div
key={index}
className={cn(
"flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",
indicator === "dot" && "items-center"
)}
>
{formatter && item?.value !== undefined && item.name ? (
formatter(item.value, item.name, item, index, item.payload)
) : (
<>
{itemConfig?.icon ? (
<itemConfig.icon />
) : (
!hideIndicator && (
<div
className={cn(
"shrink-0 rounded-[2px] border-[color:var(--color-border)] bg-[var(--color-bg)]",
{
"h-2.5 w-2.5": indicator === "dot",
"w-1": indicator === "line",
"w-0 border-[1.5px] border-dashed bg-transparent":
indicator === "dashed",
"my-0.5": nestLabel && indicator === "dashed",
}
)}
style={
{
"--color-bg": indicatorColor,
"--color-border": indicatorColor,
} as React.CSSProperties
}
/>
)
)}
<div
className={cn(
"flex flex-1 justify-between leading-none",
nestLabel ? "items-end" : "items-center"
)}
>
<div className="grid gap-1.5">
{nestLabel ? tooltipLabel : null}
<span className="text-muted-foreground">
{itemConfig?.label ?? item.name}
</span>
</div>
{item.value != null && (
<span className="font-mono font-medium text-foreground tabular-nums">
{typeof item.value === "number"
? item.value.toLocaleString()
: String(item.value)}
</span>
)}
</div>
</>
)}
</div>
)
})}
</div>
</div>
)
}
const ChartLegend = RechartsPrimitive.Legend
function ChartLegendContent({
className,
hideIcon = false,
payload,
verticalAlign = "bottom",
nameKey,
}: React.ComponentProps<"div"> & {
hideIcon?: boolean
nameKey?: string
} & RechartsPrimitive.DefaultLegendContentProps) {
const { config } = useChart()
if (!payload?.length) {
return null
}
return (
<div
className={cn(
"flex items-center justify-center gap-4",
verticalAlign === "top" ? "pb-3" : "pt-3",
className
)}
>
{payload
.filter((item) => item.type !== "none")
.map((item, index) => {
const key = `${nameKey ?? item.dataKey ?? "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
return (
<div
key={index}
className={cn(
"flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"
)}
>
{itemConfig?.icon && !hideIcon ? (
<itemConfig.icon />
) : (
<div
className="h-2 w-2 shrink-0 rounded-[2px]"
style={{
backgroundColor: item.color,
}}
/>
)}
{itemConfig?.label}
</div>
)
})}
</div>
)
}
// Helper to extract item config from a payload.
function getPayloadConfigFromPayload(
config: ChartConfig,
payload: unknown,
key: string
) {
if (typeof payload !== "object" || payload === null) {
return undefined
}
const payloadPayload =
"payload" in payload &&
typeof payload.payload === "object" &&
payload.payload !== null
? payload.payload
: undefined
let configLabelKey: string = key
if (
key in payload &&
typeof payload[key as keyof typeof payload] === "string"
) {
configLabelKey = payload[key as keyof typeof payload] as string
} else if (
payloadPayload &&
key in payloadPayload &&
typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
) {
configLabelKey = payloadPayload[
key as keyof typeof payloadPayload
] as string
}
return configLabelKey in config ? config[configLabelKey] : config[key]
}
export {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
ChartLegend,
ChartLegendContent,
ChartStyle,
}
@@ -0,0 +1,9 @@
import { describe, it, expect } from "vitest";
import { resolveMessage } from "./t";
// The sidebar labels the BO_DASHBOARD module by its name as a message key; without a default it shows the raw code.
describe("BO_DASHBOARD label", () => {
it("resolves to Dashboard with an empty catalog", () => {
expect(resolveMessage({}, "BO_DASHBOARD")).toBe("Dashboard");
});
});
@@ -117,6 +117,36 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
ModulesParent: "Parent",
DashWelcome: "Welcome, {name}",
DashWelcomeFallbackName: "admin",
DashLeadFunnelLabel: "Lead funnel",
DashThisMonth: "This month",
DashLastMonth: "Last month",
DashCustom: "Custom",
DashFrom: "From",
DashTo: "To",
DashRangeReversed: "The start date must not be after the end date.",
DashLoadFailed: "Could not load the dashboard.",
DashCaptures: "Captures",
DashNewLeads: "New leads",
DashWonInPeriod: "Won in period",
DashConversionRate: "Conversion rate",
DashMedianDays: "Median days to win",
DashOverdue: "Overdue follow-ups",
DashFunnel: "Funnel",
DashTrend: "Captures and wins over time",
DashWins: "Wins",
DashByEvent: "By event",
DashBySalesperson: "By salesperson",
DashByInterest: "By interest",
DashEvent: "Event",
DashSalesperson: "Salesperson",
DashInterest: "Interest",
DashAssigned: "Assigned",
DashWorked: "Worked",
DashConversion: "Conversion",
DashOverdueShort: "Overdue",
DashUnassigned: "Unassigned",
DashUnknownUser: "Unknown user",
DashEmpty: "No data for this period",
Close: "Close",
Enabled: "Enabled",
Admin: "Admin",
@@ -395,6 +425,7 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
LsSettingsLoadFailed: "Failed to load the settings",
LsSaveFailed: "Failed to save",
BO_AUDIT_LOG: "Audit log",
BO_DASHBOARD: "Dashboard",
BO_LEADS_EDIT: "Lead editing",
BO_LEADS_EXPORT: "Lead export",
AuditWho: "Who",
@@ -18,7 +18,10 @@ const HTML_SINKS = [
] as const;
type Sink = (typeof HTML_SINKS)[number];
const SINK_ALLOWED: Record<string, Sink[]> = {};
const SINK_ALLOWED: Record<string, Sink[]> = {
// shadcn chart: a <style> built from the chart's own colour config (code constants), never from data.
"components/ui/chart.tsx": ["dangerouslySetInnerHTML"],
};
function sourceFiles(dir: string, out: string[] = []): string[] {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
@@ -0,0 +1,22 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ apiGet: vi.fn() }));
vi.mock("@/app/lib/clientApi", () => mocks);
import { getLeadDashboard } from "./adminDashboard";
beforeEach(() => mocks.apiGet.mockReset().mockResolvedValue({}));
describe("adminDashboard", () => {
it("sends no query string when no params are given", async () => {
await getLeadDashboard({});
expect(mocks.apiGet).toHaveBeenCalledWith("/api/dashboard/leads");
});
it("sends only the given params", async () => {
await getLeadDashboard({ from: "2026-11-01", to: "2026-11-30", companyId: 2 });
expect(mocks.apiGet).toHaveBeenCalledWith("/api/dashboard/leads?from=2026-11-01&to=2026-11-30&companyId=2");
await getLeadDashboard({ companyId: 3 });
expect(mocks.apiGet).toHaveBeenLastCalledWith("/api/dashboard/leads?companyId=3");
});
});
@@ -0,0 +1,32 @@
import { apiGet } from "@/app/lib/clientApi";
export interface LeadDashboard {
from: string;
to: string;
bucket: "DAY" | "MONTH";
captures: number;
newLeads: number;
wonInPeriod: number;
medianDaysToWin: number | null;
overdueFollowUps: number;
funnel: { OPEN: number; CONTACTED: number; QUALIFIED: number; WON: number; LOST: number };
trend: { bucket: string; captures: number; wins: number }[];
events: { eventUuid: string; name: string; companyId: number; captures: number; newLeads: number; won: number }[];
salespeople: { userId: number | null; name: string | null; assigned: number; worked: number; won: number; lost: number; overdue: number }[];
interests: { interestId: number; name: string; captures: number; won: number }[];
}
export interface LeadDashboardParams {
from?: string;
to?: string;
companyId?: number;
}
export function getLeadDashboard({ from, to, companyId }: LeadDashboardParams): Promise<LeadDashboard> {
const qs = new URLSearchParams();
if (from) qs.set("from", from);
if (to) qs.set("to", to);
if (companyId) qs.set("companyId", String(companyId));
const s = qs.toString();
return apiGet<LeadDashboard>(`/api/dashboard/leads${s ? `?${s}` : ""}`);
}
@@ -0,0 +1,173 @@
import { render, screen, waitFor, within, fireEvent } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { pickDate } from "@/test/pickDate";
const mocks = vi.hoisted(() => ({
getLeadDashboard: vi.fn(),
useAdminAuth: vi.fn(),
useCompanyScope: vi.fn(),
}));
vi.mock("@/app/lib/services/adminDashboard", () => ({ getLeadDashboard: mocks.getLeadDashboard }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
import { ApiError } from "@/app/lib/clientApi";
import HomePage from "./page";
const DATA = {
from: "2026-12-01", to: "2026-12-01", bucket: "DAY",
captures: 40, newLeads: 25, wonInPeriod: 8, medianDaysToWin: 4.5, overdueFollowUps: 3,
funnel: { OPEN: 11, CONTACTED: 12, QUALIFIED: 13, WON: 8, LOST: 6 },
trend: [{ bucket: "2026-12-01", captures: 5, wins: 1 }],
events: [{ eventUuid: "ev-1", name: "Expo KL", companyId: 2, captures: 20, newLeads: 10, won: 5 }],
salespeople: [
{ userId: null, name: null, assigned: 7, worked: 2, won: 1, lost: 0, overdue: 4 },
{ userId: 9, name: null, assigned: 0, worked: 0, won: 0, lost: 0, overdue: 0 },
{ userId: 5, name: "Sam", assigned: 10, worked: 6, won: 3, lost: 1, overdue: 2 },
],
interests: [{ interestId: 1, name: "Catering", captures: 15, won: 4 }],
};
const scope = (companyId?: number, showCompanyColumn = false) => ({
companyId, companies: [], showCompanyColumn, codeOf: (id?: number | null) => (id === 2 ? "CV" : ""), setCompanyId: vi.fn(),
});
const tile = (name: string) => within(screen.getByRole("group", { name }));
beforeEach(() => {
mocks.getLeadDashboard.mockReset().mockResolvedValue(DATA);
mocks.useAdminAuth.mockReset().mockReturnValue({ name: "Alice", loading: false, isSuper: false, hasModule: (m: string) => m === "BO_DASHBOARD" });
mocks.useCompanyScope.mockReset().mockReturnValue(scope());
});
afterEach(() => vi.useRealTimers());
describe("home page lead dashboard", () => {
it("shows only the welcome and never calls the API without the module", () => {
mocks.useAdminAuth.mockReturnValue({ name: "Alice", loading: false, hasModule: () => false });
render(<HomePage />);
expect(screen.getByText("Welcome, Alice")).toBeInTheDocument();
expect(screen.queryByRole("group", { name: "Captures" })).not.toBeInTheDocument();
expect(mocks.getLeadDashboard).not.toHaveBeenCalled();
});
it("shows the welcome plus tiles with the This month default (no from/to)", async () => {
render(<HomePage />);
expect(screen.getByText("Welcome, Alice")).toBeInTheDocument();
await screen.findByRole("group", { name: "Captures" });
expect(tile("Captures").getByText("40")).toBeInTheDocument();
expect(tile("New leads").getByText("25")).toBeInTheDocument();
expect(tile("Won in period").getByText("8")).toBeInTheDocument();
expect(tile("Conversion rate").getByText("20%")).toBeInTheDocument();
expect(tile("Median days to win").getByText("4.5")).toBeInTheDocument();
expect(tile("Overdue follow-ups").getByText("3")).toBeInTheDocument();
expect(mocks.getLeadDashboard).toHaveBeenCalledWith({ from: undefined, to: undefined, companyId: undefined });
});
it("shows a dash for a null median and for zero captures", async () => {
mocks.getLeadDashboard.mockResolvedValue({ ...DATA, captures: 0, medianDaysToWin: null });
render(<HomePage />);
await waitFor(() => expect(tile("Conversion rate").getByText("–")).toBeInTheDocument());
expect(tile("Median days to win").getByText("–")).toBeInTheDocument();
});
it("shows the funnel counts and the trend chart", async () => {
const { container } = render(<HomePage />);
const funnel = await screen.findByRole("list", { name: "Lead funnel" });
const items = within(funnel).getAllByRole("listitem").map((li) => li.textContent);
expect(items).toEqual(["Open11", "Contacted12", "Qualified13", "Won8", "Lost6"]);
expect(container.querySelector('[data-slot="chart"]')).toBeInTheDocument();
});
it("shows the by-event, by-salesperson and by-interest tables", async () => {
render(<HomePage />);
const ev = within(await screen.findByRole("table", { name: "By event" }));
expect(ev.getByRole("link", { name: "Expo KL" })).toHaveAttribute("href", "/event-leads/ev-1");
expect(ev.getByText("25%")).toBeInTheDocument();
expect(ev.queryByText("Company")).not.toBeInTheDocument();
const sp = within(screen.getByRole("table", { name: "By salesperson" }));
expect(sp.getByText("Unassigned")).toBeInTheDocument();
expect(sp.getByText("Unknown user")).toBeInTheDocument();
expect(sp.getByText("Sam")).toBeInTheDocument();
expect(sp.getByText("30%")).toBeInTheDocument();
expect(sp.getAllByText("–").length).toBe(1);
const rowText = (name: string) => Array.from(sp.getByText(name).closest("tr")!.querySelectorAll("td")).map((td) => td.textContent);
expect(rowText("Unassigned")).toEqual(["Unassigned", "7", "2", "1", "0", "14%", "4"]);
expect(rowText("Sam")).toEqual(["Sam", "10", "6", "3", "1", "30%", "2"]);
const it = within(screen.getByRole("table", { name: "By interest" }));
expect(it.getByText("Catering")).toBeInTheDocument();
});
it("shows empty-state lines for empty lists", async () => {
mocks.getLeadDashboard.mockResolvedValue({ ...DATA, events: [], salespeople: [], interests: [] });
render(<HomePage />);
await waitFor(() => expect(screen.getAllByText("No data for this period")).toHaveLength(3));
});
it("sends the previous Malaysian month for Last month", async () => {
vi.useFakeTimers({ toFake: ["Date"], now: new Date("2026-12-01T10:00:00+08:00") });
render(<HomePage />);
fireEvent.click(screen.getByRole("button", { name: "Last month" }));
await waitFor(() => expect(mocks.getLeadDashboard).toHaveBeenLastCalledWith({ from: "2026-11-01", to: "2026-11-30", companyId: undefined }));
});
it("uses Malaysian time near midnight UTC and across a year boundary", async () => {
vi.useFakeTimers({ toFake: ["Date"], now: new Date("2026-12-31T20:00:00Z") }); // 2027-01-01 04:00 in KL
render(<HomePage />);
fireEvent.click(screen.getByRole("button", { name: "Last month" }));
await waitFor(() => expect(mocks.getLeadDashboard).toHaveBeenLastCalledWith({ from: "2026-12-01", to: "2026-12-31", companyId: undefined }));
});
it("rejects a reversed custom range without calling the API", async () => {
render(<HomePage />);
await screen.findByRole("group", { name: "Captures" });
fireEvent.click(screen.getByRole("button", { name: "Custom" }));
expect(screen.queryByRole("group", { name: "Captures" })).not.toBeInTheDocument();
mocks.getLeadDashboard.mockClear();
pickDate("From", "2026-11-20");
pickDate("To", "2026-11-10");
expect(await screen.findByText("The start date must not be after the end date.")).toBeInTheDocument();
expect(screen.queryByRole("group", { name: "Captures" })).not.toBeInTheDocument();
expect(mocks.getLeadDashboard).not.toHaveBeenCalled();
});
it("sends a valid custom range", async () => {
render(<HomePage />);
await screen.findByRole("group", { name: "Captures" });
fireEvent.click(screen.getByRole("button", { name: "Custom" }));
pickDate("From", "2026-11-10");
pickDate("To", "2026-11-20");
await waitFor(() => expect(mocks.getLeadDashboard).toHaveBeenLastCalledWith({ from: "2026-11-10", to: "2026-11-20", companyId: undefined }));
});
it("sends the picked company and shows no Company column", async () => {
mocks.useCompanyScope.mockReturnValue(scope(2, false));
render(<HomePage />);
const ev = within(await screen.findByRole("table", { name: "By event" }));
expect(mocks.getLeadDashboard).toHaveBeenCalledWith({ from: undefined, to: undefined, companyId: 2 });
expect(ev.queryByText("Company")).not.toBeInTheDocument();
});
it("on All companies sends no companyId and shows the Company column with the code", async () => {
mocks.useCompanyScope.mockReturnValue(scope(undefined, true));
render(<HomePage />);
const ev = within(await screen.findByRole("table", { name: "By event" }));
expect(mocks.getLeadDashboard).toHaveBeenCalledWith({ from: undefined, to: undefined, companyId: undefined });
expect(ev.getByText("Company")).toBeInTheDocument();
expect(ev.getByText("CV")).toBeInTheDocument();
});
it("shows the API message for INVALID_PERIOD", async () => {
mocks.getLeadDashboard.mockRejectedValue(new ApiError("Start date must be on or before end date.", 400, { error: "Start date must be on or before end date.", code: "INVALID_PERIOD" }));
render(<HomePage />);
expect(await screen.findByText("Start date must be on or before end date.")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Retry" })).not.toBeInTheDocument();
});
it("shows a retryable error for other failures", async () => {
mocks.getLeadDashboard.mockRejectedValueOnce(new Error("boom"));
render(<HomePage />);
expect(await screen.findByText("Could not load the dashboard.")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
await screen.findByRole("group", { name: "Captures" });
expect(tile("Captures").getByText("40")).toBeInTheDocument();
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
import { render, screen } from "@testing-library/react";
import { describe, it, expect, vi } from "vitest";
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ name: "Alice" }) }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ name: "Alice", hasModule: () => false }) }));
import HomePage from "./page";
+10 -6
View File
@@ -2,16 +2,20 @@
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { LeadDashboard } from "@/app/components/dashboard/LeadDashboard";
export default function HomePage() {
const t = useT();
const { name } = useAdminAuth();
const { name, hasModule } = useAdminAuth();
return (
<div className="space-y-2">
<h1 className="text-xl">{t("BackOfficeTitle")}</h1>
<p className="text-sm text-muted-foreground">
{t("DashWelcome", { name: name ?? t("DashWelcomeFallbackName") })}
</p>
<div className="space-y-6">
<div className="space-y-2">
<h1 className="text-xl">{t("BackOfficeTitle")}</h1>
<p className="text-sm text-muted-foreground">
{t("DashWelcome", { name: name ?? t("DashWelcomeFallbackName") })}
</p>
</div>
{hasModule("BO_DASHBOARD") && <LeadDashboard />}
</div>
);
}
+388 -1
View File
@@ -17,6 +17,7 @@
"react": "^19.2.8",
"react-day-picker": "10.0.1",
"react-dom": "^19.2.8",
"recharts": "3.10.1",
"tailwind-merge": "^3.6.0"
},
"devDependencies": {
@@ -3183,6 +3184,36 @@
"integrity": "sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw==",
"license": "MIT"
},
"node_modules/@reduxjs/toolkit": {
"version": "2.16.0",
"resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.16.0.tgz",
"integrity": "sha512-MZAZNNvsNJrMttw/+rfBhay3+/zxPZNmuK/lFmahE+SAJTemxW643i+USptYg69guUohrtUu/4/XXbocOxVFIA==",
"license": "MIT",
"dependencies": {
"@standard-schema/spec": "^1.0.0",
"@standard-schema/utils": "^0.3.0",
"immer": "^11.2.14",
"redux": "^5.0.1",
"redux-thunk": "^3.1.0",
"reselect": "^5.1.0"
},
"peerDependencies": {
"@types/react": "*",
"react": "^16.9.0 || ^17.0.0 || ^18 || ^19",
"react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"react": {
"optional": true
},
"react-redux": {
"optional": true
}
}
},
"node_modules/@rolldown/binding-android-arm-eabi": {
"version": "1.2.19",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz",
@@ -3527,7 +3558,12 @@
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
"dev": true,
"license": "MIT"
},
"node_modules/@standard-schema/utils": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
"license": "MIT"
},
"node_modules/@swc/helpers": {
@@ -3701,6 +3737,69 @@
"assertion-error": "^2.0.1"
}
},
"node_modules/@types/d3-array": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",
"integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",
"license": "MIT"
},
"node_modules/@types/d3-color": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",
"integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
"license": "MIT"
},
"node_modules/@types/d3-ease": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",
"integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",
"license": "MIT"
},
"node_modules/@types/d3-interpolate": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
"integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",
"license": "MIT",
"dependencies": {
"@types/d3-color": "*"
}
},
"node_modules/@types/d3-path": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",
"integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",
"license": "MIT"
},
"node_modules/@types/d3-scale": {
"version": "4.0.9",
"resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",
"integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",
"license": "MIT",
"dependencies": {
"@types/d3-time": "*"
}
},
"node_modules/@types/d3-shape": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.2.0.tgz",
"integrity": "sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw==",
"license": "MIT",
"dependencies": {
"@types/d3-path": "*"
}
},
"node_modules/@types/d3-time": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",
"integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",
"license": "MIT"
},
"node_modules/@types/d3-timer": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",
"integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
"license": "MIT"
},
"node_modules/@types/deep-eql": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
@@ -3759,6 +3858,12 @@
"@types/react": "^19.2.0"
}
},
"node_modules/@types/use-sync-external-store": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",
"integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==",
"license": "MIT"
},
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.2.tgz",
@@ -5236,6 +5341,127 @@
"devOptional": true,
"license": "MIT"
},
"node_modules/d3-array": {
"version": "3.2.5",
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.5.tgz",
"integrity": "sha512-Th8qGXoBalmWsstpkuhmBuTsBQIFqYOJtjlBvNVvBfJ8E3uYusBUwUR8HU20U0qKKQkgCvKyR1YjiozWadk5QA==",
"license": "ISC",
"dependencies": {
"internmap": "1 - 2"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-color": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.1.tgz",
"integrity": "sha512-lfab8x0Bj0UO7SNsY8dZSbNIA6ipbkE3X0NG9nqjCu6CfCHZseuDnOSJY7hidKrjpP++i1M2qT+FlAdPKYRilA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-ease": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.2.tgz",
"integrity": "sha512-B5znKqRmKROAN4oHWQ50W/qisVjA9GXh2WMsVKdFVp4DxWmcrOsweqgUOUVsv5th96kwaZlokU6SlV4J3gak1w==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-format": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.3.tgz",
"integrity": "sha512-+F+/49swqmGuQJmSKnVMIDH/QkEFV5li9QRj0xm/KhyAUBv099O5PrvpQFxBp24PYph17Mnvt9mjKQV0ii0nMA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-interpolate": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.2.tgz",
"integrity": "sha512-IRzGU62DtxhvsnSTWMQIdnoZ6gA+BCWwBon1EJI6SjoN595799b6z/QRBzXfFhE8iupUPp3042yBNo0STPqnzQ==",
"license": "ISC",
"dependencies": {
"d3-color": "1 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-path": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.1.tgz",
"integrity": "sha512-jsbgV8zIT38ReB9O7X7gcLndTQRONSqNNd+oGIaTBdUug4r5jFmp0N6RY9R5GWbdUDucn0qoTGyfjapT4tDhcg==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-scale": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.3.tgz",
"integrity": "sha512-66cWobCNzcMvlfoaDHCxuIv9TBUWG1BLOWdv9kHHFuCr1JdqAWPvTmsaEYDD5NRMyWZ5+7u0GqiCDfMXMqh3hg==",
"license": "ISC",
"dependencies": {
"d3-array": "2.10.0 - 3",
"d3-format": "1 - 3",
"d3-interpolate": "1.2.0 - 3",
"d3-time": "2.1.1 - 3",
"d3-time-format": "2 - 4"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-shape": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.1.tgz",
"integrity": "sha512-dm2o+lbKdzg9tY7GEag/dB9hcbodLfwkE/DkvqbELJXaMz0yKzWWhZqhbI7CKubukA7HnRyz0avdtvi7EPxPvw==",
"license": "ISC",
"dependencies": {
"d3-path": "^3.1.1"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-time": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.1.tgz",
"integrity": "sha512-Ze7rjrhMzdeulh0/hjcfFj7XLAHOfowtEMfsoG6DU866HPynQNW7Wfen6hzXcqKTv8XzxvF6Hzr5XD6bMHr2ug==",
"license": "ISC",
"dependencies": {
"d3-array": "2 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-time-format": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.1.tgz",
"integrity": "sha512-22XaqjyCjpqgda20erhsOjGmC3vvYwTNYniKAd45W5UWLDF43moeOuV9qYpRqobIlsnK0UhnKZjUUJm3VgORUA==",
"license": "ISC",
"dependencies": {
"d3-time": "1 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-timer": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.2.tgz",
"integrity": "sha512-1Il1aliroVSErrv5aulRBxAY+7+DnaoLIWGd1C6SsBTWDeobWiP/V69vwb8vT6abR1kKwaNe1196pmaQ1fK90A==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/damerau-levenshtein": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz",
@@ -5346,6 +5572,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/decimal.js-light": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz",
"integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==",
"license": "MIT"
},
"node_modules/deep-is": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
@@ -5698,6 +5930,18 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/es-toolkit": {
"version": "1.53.2",
"resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.53.2.tgz",
"integrity": "sha512-iUqZ+NlwH4jUgRmXZUxFBsV/9762TQEa1O4IXLFBmDEjVHScBytKuseX23I0+v9ShZ5MYxEx6WKNzm6IPnex8g==",
"license": "MIT",
"workspaces": [
"docs",
"benchmarks",
"tests/types",
"tests/browser-compat"
]
},
"node_modules/escalade": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
@@ -6147,6 +6391,12 @@
"node": ">=0.10.0"
}
},
"node_modules/eventemitter3": {
"version": "5.0.4",
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",
"integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
"license": "MIT"
},
"node_modules/expect-type": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
@@ -6660,6 +6910,16 @@
"node": ">= 4"
}
},
"node_modules/immer": {
"version": "11.2.14",
"resolved": "https://registry.npmjs.org/immer/-/immer-11.2.14.tgz",
"integrity": "sha512-Xujh/D+NWN1mM/eJb30ASOOTrI74DA6BV+SdkvfeIvHt8Pk70h0lP5l4LRIvBcEujxbw7LbVTFvcxgGg6pgvKA==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/immer"
}
},
"node_modules/import-fresh": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
@@ -6712,6 +6972,15 @@
"node": ">= 0.4"
}
},
"node_modules/internmap": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",
"integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/is-array-buffer": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz",
@@ -8725,6 +8994,36 @@
"react": "^19.2.8"
}
},
"node_modules/react-is": {
"version": "19.3.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-19.3.1.tgz",
"integrity": "sha512-RRieF6IyxQBkcK6pP8xOHprLTPW6QjRkbGdImtqNme+/hYVwCZkLQLdlZGOhUqXwkS9IEynaGvPJtv6XB/cz0Q==",
"license": "MIT",
"peer": true
},
"node_modules/react-redux": {
"version": "9.3.1",
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.3.1.tgz",
"integrity": "sha512-vxMLT0lalUjbZPkoTepWyKAZbjIIFssNx/CEL9lTfwQBU6XpkGSmCNdcCIrkOBUgB68uftZMnbXVb6DwGnhRKQ==",
"license": "MIT",
"dependencies": {
"@types/use-sync-external-store": "^0.0.6",
"use-sync-external-store": "^1.4.0"
},
"peerDependencies": {
"@types/react": "^18.2.25 || ^19",
"react": "^18.0 || ^19",
"redux": "^5.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"redux": {
"optional": true
}
}
},
"node_modules/react-remove-scroll": {
"version": "2.7.2",
"resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz",
@@ -8801,6 +9100,36 @@
"dev": true,
"license": "MIT"
},
"node_modules/recharts": {
"version": "3.10.1",
"resolved": "https://registry.npmjs.org/recharts/-/recharts-3.10.1.tgz",
"integrity": "sha512-QXFrvt6IVcw7eeZCoyXTwkIJAX3Dv1nyVhMicXJ47GsGDDpcN8z6o644DibE9XjpBTThtsomLKnTV6lc+cVFUA==",
"license": "MIT",
"workspaces": [
"www"
],
"dependencies": {
"@reduxjs/toolkit": "^1.9.0 || 2.x.x",
"clsx": "^2.1.1",
"decimal.js-light": "^2.5.1",
"es-toolkit": "^1.39.3",
"eventemitter3": "^5.0.1",
"immer": "^11.1.8",
"react-redux": "8.x.x || 9.x.x",
"reselect": "5.2.0",
"tiny-invariant": "^1.3.3",
"use-sync-external-store": "^1.2.2",
"victory-vendor": "^37.0.2"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/redent": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz",
@@ -8815,6 +9144,21 @@
"node": ">=8"
}
},
"node_modules/redux": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
"license": "MIT"
},
"node_modules/redux-thunk": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-3.1.0.tgz",
"integrity": "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==",
"license": "MIT",
"peerDependencies": {
"redux": "^5.0.0"
}
},
"node_modules/reflect.getprototypeof": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",
@@ -8869,6 +9213,12 @@
"node": ">=0.10.0"
}
},
"node_modules/reselect": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/reselect/-/reselect-5.2.0.tgz",
"integrity": "sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw==",
"license": "MIT"
},
"node_modules/resolve": {
"version": "2.0.0-next.7",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.7.tgz",
@@ -9732,6 +10082,12 @@
"node": ">=0.8"
}
},
"node_modules/tiny-invariant": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
"integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==",
"license": "MIT"
},
"node_modules/tinybench": {
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
@@ -10205,6 +10561,15 @@
}
}
},
"node_modules/use-sync-external-store": {
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.7.0.tgz",
"integrity": "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==",
"license": "MIT",
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
@@ -10212,6 +10577,28 @@
"dev": true,
"license": "MIT"
},
"node_modules/victory-vendor": {
"version": "37.4.1",
"resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-37.4.1.tgz",
"integrity": "sha512-geV4p2GVfVM9lgm9ZRS3pvsbAPS+BUGhM9W9nPzPHTKi+/+KjNrFXdgP6KkG+XspNZuvcXmchcrtklfuQ4gniw==",
"license": "MIT AND ISC AND BSD-3-Clause",
"dependencies": {
"@types/d3-array": "^3.0.3",
"@types/d3-ease": "^3.0.0",
"@types/d3-interpolate": "^3.0.1",
"@types/d3-scale": "^4.0.2",
"@types/d3-shape": "^3.1.0",
"@types/d3-time": "^3.0.0",
"@types/d3-timer": "^3.0.0",
"d3-array": "^3.1.6",
"d3-ease": "^3.0.1",
"d3-interpolate": "^3.0.1",
"d3-scale": "^4.0.2",
"d3-shape": "^3.1.0",
"d3-time": "^3.0.0",
"d3-timer": "^3.0.1"
}
},
"node_modules/vite": {
"version": "8.3.8",
"resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz",
+1
View File
@@ -23,6 +23,7 @@
"react": "^19.2.8",
"react-day-picker": "10.0.1",
"react-dom": "^19.2.8",
"recharts": "3.10.1",
"tailwind-merge": "^3.6.0"
},
"devDependencies": {
@@ -44,6 +44,7 @@ public class RestApiCounterServiceConstants {
public static final String API_REST_COUNTER_LEAD_SEARCH="/counter/lead/search";
public static final String API_REST_COUNTER_LEAD_DETAIL="/counter/lead/detail/{leadUuid}";
public static final String API_REST_COUNTER_LEAD_UPDATE="/counter/lead/update";
public static final String API_REST_COUNTER_DASHBOARD_LEADS="/counter/dashboard/leads";
public static final String API_REST_COUNTER_EVENT_LEAD_CAPTURE="/counter/eventLead/capture";
public static final String API_REST_COUNTER_EVENT_LEAD_FIND_BY_UUID="/counter/eventLead/findByUuid/{eventLeadUuid}";
public static final String API_REST_COUNTER_EVENT_LEAD_UPDATE="/counter/eventLead/update";
@@ -0,0 +1,30 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.service.AdminDashboardService;
import com.solvway.mobile.api.useraccess.AdminModule;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/** Lead dashboard. Must stay under {@code controller..} for AppAccessAspect. */
@RestController
@RequestMapping("/api/admin/dashboard")
@RequiredArgsConstructor
public class AdminDashboardController {
private final AdminDashboardService adminDashboardService;
@AppAuth
@AdminModule("BO_DASHBOARD")
@GetMapping("/leads")
public ResponseEntity<Map<String, Object>> leads(@RequestParam(required = false) String from,
@RequestParam(required = false) String to,
@RequestParam(required = false) Long companyId) {
return ResponseEntity.ok(adminDashboardService.leads(from, to, companyId));
}
}
@@ -0,0 +1,108 @@
package com.solvway.mobile.api.service;
import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import java.time.Clock;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static com.solvway.mobile.api.service.AdminEventLeadService.error;
/** Lead dashboard for the admin portal: validates the period and company scope here; services-counter aggregates. */
@Service
@SuppressWarnings("unchecked")
public class AdminDashboardService {
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
private static final ZoneId KL = ZoneId.of("Asia/Kuala_Lumpur");
private final RestTemplateCustomUtil restTemplateUtil;
private final AdminAuthenticationService adminAuthenticationService;
private final AdminCompanyScope scope;
private final Clock clock;
@Autowired
public AdminDashboardService(RestTemplateCustomUtil restTemplateUtil, AdminAuthenticationService adminAuthenticationService, AdminCompanyScope scope) {
this(restTemplateUtil, adminAuthenticationService, scope, Clock.systemUTC());
}
AdminDashboardService(RestTemplateCustomUtil restTemplateUtil, AdminAuthenticationService adminAuthenticationService, AdminCompanyScope scope, Clock clock) {
this.restTemplateUtil = restTemplateUtil;
this.adminAuthenticationService = adminAuthenticationService;
this.scope = scope;
this.clock = clock;
}
public Map<String, Object> leads(String fromParam, String toParam, Long companyId) {
Long company = scope.scope(caller(), companyId);
LocalDate today = LocalDate.now(clock.withZone(KL));
LocalDate from = date(fromParam, today.withDayOfMonth(1));
LocalDate to = date(toParam, today);
if (from.isAfter(to)) throw invalid("Start date must be on or before end date.");
long days = ChronoUnit.DAYS.between(from, to) + 1;
if (days > 731) throw invalid("The period can be at most 731 days.");
String bucket = days <= 62 ? "DAY" : "MONTH";
Map<String, Object> body = new LinkedHashMap<>();
body.put("companyId", company);
body.put("from", from.toString());
body.put("to", to.toString());
body.put("bucket", bucket);
Map<String, Object> res = restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(RestApiCounterServiceConstants.API_REST_COUNTER_DASHBOARD_LEADS), MAP, body).getBody();
Map<String, Object> out = new LinkedHashMap<>(res == null ? Map.of() : res);
out.put("from", from.toString());
out.put("to", to.toString());
out.put("bucket", bucket);
Map<Long, Map<String, Object>> users = new HashMap<>();
List<Map<String, Object>> rows = out.get("salespeople") == null ? List.of() : (List<Map<String, Object>>) out.get("salespeople");
out.put("salespeople", rows.stream().map(r -> {
Map<String, Object> m = new LinkedHashMap<>(r);
m.put("name", r.get("userId") instanceof Number n ? name(n.longValue(), users) : null);
return m;
}).toList());
return out;
}
/** User name, or null when the user no longer exists; one lookup per distinct id per request. */
private String name(long id, Map<Long, Map<String, Object>> users) {
if (!users.containsKey(id)) { // computeIfAbsent would not cache a missing user
users.put(id, restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID), MAP, id).getBody());
}
Map<String, Object> u = users.get(id);
return u == null || u.get("name") == null ? null : String.valueOf(u.get("name"));
}
private static LocalDate date(String s, LocalDate dflt) {
if (s == null || s.isBlank()) return dflt;
try {
return LocalDate.parse(s.trim());
} catch (DateTimeParseException e) {
throw invalid("Dates must be yyyy-MM-dd.");
}
}
private static RuntimeException invalid(String message) {
return error(HttpStatus.BAD_REQUEST, message, "INVALID_PERIOD", null);
}
private User caller() {
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED", null);
return caller;
}
}
@@ -0,0 +1,37 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.service.AdminDashboardService;
import com.solvway.mobile.api.useraccess.AdminModule;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.lang.reflect.Method;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class AdminDashboardControllerTest {
@Test
void leadsNeedsBoDashboard() throws Exception {
Method m = AdminDashboardController.class.getDeclaredMethod("leads", String.class, String.class, Long.class);
assertThat(m.isAnnotationPresent(AppAuth.class)).isTrue();
assertThat(m.getAnnotation(AdminModule.class).value()).containsExactly("BO_DASHBOARD");
}
@Test
void passesParams() throws Exception {
AdminDashboardService s = mock(AdminDashboardService.class);
when(s.leads("2026-11-01", "2026-11-30", 2L)).thenReturn(Map.of("bucket", "DAY"));
MockMvc mvc = MockMvcBuilders.standaloneSetup(new AdminDashboardController(s)).build();
mvc.perform(get("/api/admin/dashboard/leads").param("from", "2026-11-01").param("to", "2026-11-30").param("companyId", "2"))
.andExpect(status().isOk()).andExpect(content().json("{\"bucket\":\"DAY\"}"));
}
}
@@ -0,0 +1,181 @@
package com.solvway.mobile.api.service;
import com.solvway.core.model.Role;
import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.MockedStatic;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@SuppressWarnings({"unchecked", "rawtypes"})
class AdminDashboardServiceTest {
private static final String LEADS = "/counter/dashboard/leads";
private static final String USER = "/user/findById/{id}";
private RestTemplateCustomUtil rest;
private AdminAuthenticationService auth;
private AdminDashboardService service;
private MockedStatic<HttpReqRespUtils> http;
private Map<String, Object> answer;
@BeforeEach
void setUp() {
rest = mock(RestTemplateCustomUtil.class);
auth = mock(AdminAuthenticationService.class);
service = new AdminDashboardService(rest, auth, new AdminCompanyScope(), Clock.fixed(Instant.parse("2026-11-30T17:00:00Z"), ZoneOffset.UTC));
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
http = mockStatic(HttpReqRespUtils.class);
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
answer = new HashMap<>();
answer.put("captures", 10);
answer.put("salespeople", List.of());
when(rest.postForEntity(eq(LEADS), any(ParameterizedTypeReference.class), any())).thenAnswer(i -> ResponseEntity.ok(answer));
caller(null, true);
}
@AfterEach
void close() { http.close(); }
private void caller(Long companyId, boolean superAdmin) {
User u = new User();
u.setId(21L);
u.setUsername("boss");
u.setCompanyId(companyId);
if (superAdmin) {
Role r = new Role("Super");
r.setId(1L);
u.setRoles(List.of(r));
}
when(auth.loadUserByToken("tok")).thenReturn(u);
}
private Map<String, Object> sentBody() {
ArgumentCaptor<Object> c = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(LEADS), any(ParameterizedTypeReference.class), c.capture());
return (Map<String, Object>) c.getValue();
}
private void assertInvalidPeriod(String from, String to) {
assertThatThrownBy(() -> service.leads(from, to, null)).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(e.getCode()).isEqualTo("INVALID_PERIOD");
});
verify(rest, never()).postForEntity(eq(LEADS), any(ParameterizedTypeReference.class), any());
}
@Test
void defaultsToMalaysianMonthToToday() {
Map<String, Object> r = service.leads(null, null, null);
assertThat(r).containsEntry("from", "2026-12-01").containsEntry("to", "2026-12-01").containsEntry("bucket", "DAY");
assertThat(sentBody()).containsEntry("from", "2026-12-01").containsEntry("to", "2026-12-01");
}
@Test
void defaultsTheMissingEnd() {
assertThat(service.leads("2026-11-20", null, null)).containsEntry("from", "2026-11-20").containsEntry("to", "2026-12-01");
}
@Test
void bucketIsDayUpTo62DaysThenMonth() {
assertThat(service.leads("2026-01-01", "2026-03-03", null)).containsEntry("bucket", "DAY");
assertThat(service.leads("2026-01-01", "2026-03-04", null)).containsEntry("bucket", "MONTH");
}
@Test
void badDateIsInvalidPeriod() {
assertInvalidPeriod("11/01/2026", "2026-11-30");
}
@Test
void fromAfterToIsInvalidPeriod() {
assertInvalidPeriod("2026-11-30", "2026-11-01");
}
@Test
void staffIsPinnedToOwnCompany() {
caller(5L, false);
service.leads("2026-11-01", "2026-11-30", 9L);
assertThat(sentBody()).containsEntry("companyId", 5L);
}
@Test
void superAdminPassesRequestedCompanyOrNull() {
service.leads("2026-11-01", "2026-11-30", 2L);
assertThat(sentBody()).containsEntry("companyId", 2L);
}
@Test
void superAdminWithoutCompanySendsNull() {
service.leads("2026-11-01", "2026-11-30", null);
assertThat(sentBody()).containsEntry("companyId", null).containsEntry("bucket", "DAY").containsEntry("to", "2026-11-30");
}
@Test
void salespeopleGetNamesOneLookupPerUser() {
answer.put("salespeople", List.of(
Map.of("userId", 7, "assigned", 4), Map.of("userId", 7, "assigned", 1), Map.of("userId", 8, "assigned", 2),
new HashMap<>(Map.of("assigned", 3))));
when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(7L))).thenReturn(ResponseEntity.ok(Map.of("name", "Aisyah")));
when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(8L))).thenReturn(ResponseEntity.ok(null));
List<Map<String, Object>> rows = (List<Map<String, Object>>) service.leads(null, null, null).get("salespeople");
assertThat(rows.get(0)).containsEntry("name", "Aisyah").containsEntry("assigned", 4);
assertThat(rows.get(1)).containsEntry("name", "Aisyah");
assertThat(rows.get(2)).containsEntry("name", null);
assertThat(rows.get(3)).containsEntry("name", null);
verify(rest, times(1)).getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(7L));
verify(rest, times(2)).getForEntity(eq(USER), any(ParameterizedTypeReference.class), any(Long.class));
}
@Test
void periodOf731DaysIsAccepted() {
assertThat(service.leads("2025-01-01", "2027-01-01", null)).containsEntry("bucket", "MONTH");
}
@Test
void periodOf732DaysIsRefused() {
assertInvalidPeriod("2025-01-01", "2027-01-02");
}
@Test
void extendedYearDateIsInvalidPeriod() {
assertInvalidPeriod("2026-11-01", "+999999999-12-31");
assertInvalidPeriod("-999999999-01-01", "2026-11-01");
}
@Test
void missingUserIsLookedUpOnce() {
answer.put("salespeople", List.of(Map.of("userId", 8, "assigned", 2), Map.of("userId", 8, "assigned", 1)));
when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(8L))).thenReturn(ResponseEntity.ok(null));
service.leads(null, null, null);
verify(rest, times(1)).getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(8L));
}
}
@@ -0,0 +1,25 @@
package com.solvway.mobile.api.service;
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/** Two constructors (one for a test clock): Spring must still know which one to use, or mobile-api fails to start. */
class AdminDashboardServiceWiringTest {
@Test
void springCreatesTheService() {
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
ctx.registerBean(RestTemplateCustomUtil.class, () -> mock(RestTemplateCustomUtil.class));
ctx.registerBean(AdminAuthenticationService.class, () -> mock(AdminAuthenticationService.class));
ctx.registerBean(AdminCompanyScope.class);
ctx.register(AdminDashboardService.class);
ctx.refresh();
assertThat(ctx.getBean(AdminDashboardService.class)).isNotNull();
}
}
}
@@ -0,0 +1,22 @@
package com.solvway.services.counter.controller;
import com.solvway.services.counter.dashboard.LeadDashboardService;
import com.solvway.services.counter.dto.LeadDashboardRequest;
import com.solvway.services.counter.dto.LeadDashboardResponse;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/counter")
@AllArgsConstructor
public class LeadDashboardController {
private final LeadDashboardService service;
@PostMapping("/dashboard/leads")
public LeadDashboardResponse leads(@RequestBody LeadDashboardRequest req) {
return service.leads(req);
}
}
@@ -0,0 +1,116 @@
package com.solvway.services.counter.dashboard;
import com.solvway.services.counter.dto.LeadDashboardRequest.Bucket;
import com.solvway.services.counter.dto.LeadDashboardResponse;
import com.solvway.services.counter.dto.LeadDashboardResponse.EventRow;
import com.solvway.services.counter.dto.LeadDashboardResponse.InterestRow;
import com.solvway.services.counter.dto.LeadDashboardResponse.Salesperson;
import com.solvway.services.counter.dto.LeadDashboardResponse.TrendPoint;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
/** Pure aggregation of the dashboard rows; no Spring, no DB. */
public final class LeadDashboardCalculator {
public static final ZoneId KL = ZoneId.of("Asia/Kuala_Lumpur");
private static final List<String> STATUSES = List.of("OPEN", "CONTACTED", "QUALIFIED", "WON", "LOST");
public record Capture(long id, long eventUuid, String eventName, long companyId, Long salespersonUserId,
String leadType, String status, LocalDateTime capturedAt) {}
public record Win(long id, LocalDateTime capturedAt, LocalDateTime wonAt) {}
public record Overdue(Long salespersonUserId, long count) {}
private LeadDashboardCalculator() {}
/**
* ponytail: one row per capture in the period, aggregated in memory; move the sums into SQL when a company
* captures hundreds of thousands of leads a year.
* storedZone is the zone the stored wall times are in (the JVM default zone in production).
*/
public static LeadDashboardResponse calculate(LocalDate from, LocalDate to, Bucket bucket, ZoneId storedZone,
List<Capture> captures, List<Win> wins, List<Overdue> overdue,
Map<Long, List<Long>> interestsByEventLead, Map<Long, String> interestNames) {
Function<LocalDateTime, LocalDate> klDate = t -> t.atZone(storedZone).withZoneSameInstant(KL).toLocalDate();
Map<String, Long> funnel = new LinkedHashMap<>();
STATUSES.forEach(s -> funnel.put(s, 0L));
captures.forEach(c -> funnel.computeIfPresent(c.status(), (k, v) -> v + 1));
List<Long> days = wins.stream()
.map(w -> ChronoUnit.DAYS.between(klDate.apply(w.capturedAt()), klDate.apply(w.wonAt()))).sorted().toList();
Long median = days.isEmpty() ? null : days.get((days.size() - 1) / 2);
TreeMap<LocalDate, long[]> trend = new TreeMap<>();
for (LocalDate d = bucketOf(from, bucket); !d.isAfter(to); d = bucket == Bucket.DAY ? d.plusDays(1) : d.plusMonths(1)) {
trend.put(d, new long[2]);
}
captures.forEach(c -> bump(trend, bucketOf(klDate.apply(c.capturedAt()), bucket), 0));
wins.forEach(w -> bump(trend, bucketOf(klDate.apply(w.wonAt()), bucket), 1));
List<EventRow> events = captures.stream().collect(Collectors.groupingBy(Capture::eventUuid)).values().stream()
.map(l -> new EventRow(String.valueOf(l.get(0).eventUuid()), l.get(0).eventName(), l.get(0).companyId(),
l.size(), count(l, c -> "NEW".equals(c.leadType())), count(l, c -> "WON".equals(c.status()))))
.sorted(Comparator.comparingLong(EventRow::captures).reversed()
.thenComparing(EventRow::name, Comparator.nullsLast(Comparator.naturalOrder())))
.toList();
Map<Long, Long> overdueByUser = new LinkedHashMap<>();
overdue.forEach(o -> overdueByUser.merge(o.salespersonUserId(), o.count(), Long::sum));
Map<Long, List<Capture>> byUser = new LinkedHashMap<>();
captures.forEach(c -> byUser.computeIfAbsent(c.salespersonUserId(), k -> new ArrayList<>()).add(c));
overdueByUser.keySet().forEach(u -> byUser.computeIfAbsent(u, k -> new ArrayList<>()));
List<Salesperson> salespeople = byUser.entrySet().stream()
.map(e -> new Salesperson(e.getKey(), e.getValue().size(), count(e.getValue(), c -> !"OPEN".equals(c.status())),
count(e.getValue(), c -> "WON".equals(c.status())), count(e.getValue(), c -> "LOST".equals(c.status())),
overdueByUser.getOrDefault(e.getKey(), 0L)))
.sorted(Comparator.comparingLong(Salesperson::assigned).reversed()
.thenComparing(Comparator.comparingLong(Salesperson::overdue).reversed())
.thenComparing(Salesperson::userId, Comparator.nullsLast(Comparator.naturalOrder())))
.toList();
Map<Long, long[]> interestTotals = new LinkedHashMap<>();
for (Capture c : captures) {
for (Long interestId : interestsByEventLead.getOrDefault(c.id(), List.of())) {
long[] t = interestTotals.computeIfAbsent(interestId, k -> new long[2]);
t[0]++;
if ("WON".equals(c.status())) t[1]++;
}
}
List<InterestRow> interests = interestTotals.entrySet().stream()
.map(e -> new InterestRow(e.getKey(), interestNames.get(e.getKey()), e.getValue()[0], e.getValue()[1]))
.sorted(Comparator.comparingLong(InterestRow::captures).reversed()
.thenComparing(InterestRow::name, Comparator.nullsLast(Comparator.naturalOrder())))
.toList();
return new LeadDashboardResponse(captures.size(), count(captures, c -> "NEW".equals(c.leadType())), wins.size(),
median, overdueByUser.values().stream().mapToLong(Long::longValue).sum(), funnel,
trend.entrySet().stream().map(e -> new TrendPoint(e.getKey(), e.getValue()[0], e.getValue()[1])).toList(),
events, salespeople, interests);
}
/** Rows outside the period's buckets are ignored. */
private static void bump(Map<LocalDate, long[]> trend, LocalDate bucket, int slot) {
long[] t = trend.get(bucket);
if (t != null) t[slot]++;
}
private static LocalDate bucketOf(LocalDate d, Bucket bucket) {
return bucket == Bucket.MONTH ? d.withDayOfMonth(1) : d;
}
private static <T> long count(List<T> l, java.util.function.Predicate<T> p) {
return l.stream().filter(p).count();
}
}
@@ -0,0 +1,72 @@
package com.solvway.services.counter.dashboard;
import com.solvway.services.counter.dashboard.LeadDashboardCalculator.Capture;
import com.solvway.services.counter.dashboard.LeadDashboardCalculator.Overdue;
import com.solvway.services.counter.dashboard.LeadDashboardCalculator.Win;
import com.solvway.services.counter.dto.LeadDashboardRequest;
import com.solvway.services.counter.dto.LeadDashboardResponse;
import com.solvway.services.counter.model.Interest;
import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.InterestRepository;
import com.solvway.services.counter.repo.LeadDashboardRepository;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
@AllArgsConstructor
public class LeadDashboardService {
private static final int CHUNK = 1000;
private static final int MAX_DAYS = 731;
private final LeadDashboardRepository repo;
private final EventLeadInterestRepository eventLeadInterestRepository;
private final InterestRepository interestRepository;
@Transactional(readOnly = true)
public LeadDashboardResponse leads(LeadDashboardRequest req) {
if (req.from() == null || req.to() == null || req.bucket() == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "PERIOD_AND_BUCKET_REQUIRED");
}
if (req.from().isAfter(req.to()) || ChronoUnit.DAYS.between(req.from(), req.to()) + 1 > MAX_DAYS) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVALID_PERIOD");
}
ZoneId system = ZoneId.systemDefault();
LocalDateTime fromTs = req.from().atStartOfDay(LeadDashboardCalculator.KL).withZoneSameInstant(system).toLocalDateTime();
LocalDateTime toTs = req.to().plusDays(1).atStartOfDay(LeadDashboardCalculator.KL).withZoneSameInstant(system).toLocalDateTime();
List<Capture> captures = repo.captures(req.companyId(), fromTs, toTs).stream()
.map(r -> new Capture(r.getId(), r.getEventUuid(), r.getEventName(), r.getCompanyId(),
r.getSalespersonUserId(), r.getLeadType(), r.getStatus(), r.getCapturedAt())).toList();
List<Win> wins = repo.wins(req.companyId(), fromTs, toTs).stream()
.map(r -> new Win(r.getId(), r.getCapturedAt(), r.getWonAt())).toList();
List<Overdue> overdue = repo.overdue(req.companyId(), LocalDate.now(LeadDashboardCalculator.KL)).stream()
.map(r -> new Overdue(r.getSalespersonUserId(), r.getTotal())).toList();
Map<Long, List<Long>> interestsByLead = new HashMap<>();
List<Long> ids = captures.stream().map(Capture::id).toList();
for (int i = 0; i < ids.size(); i += CHUNK) {
eventLeadInterestRepository.findByIdEventLeadIdIn(ids.subList(i, Math.min(i + CHUNK, ids.size())))
.forEach(r -> interestsByLead.computeIfAbsent(r.getId().getEventLeadId(), k -> new java.util.ArrayList<>())
.add(r.getId().getInterestId()));
}
Map<Long, String> names = interestsByLead.isEmpty() ? Map.of()
: interestRepository.findAllById(interestsByLead.values().stream().flatMap(List::stream).distinct().toList())
.stream().collect(Collectors.toMap(Interest::getId, Interest::getName));
return LeadDashboardCalculator.calculate(req.from(), req.to(), req.bucket(), system, captures, wins, overdue,
interestsByLead, names);
}
}
@@ -0,0 +1,8 @@
package com.solvway.services.counter.dto;
import java.time.LocalDate;
/** companyId null means all companies. The period is whole Asia/Kuala_Lumpur days, both ends included. */
public record LeadDashboardRequest(Long companyId, LocalDate from, LocalDate to, Bucket bucket) {
public enum Bucket { DAY, MONTH }
}
@@ -0,0 +1,17 @@
package com.solvway.services.counter.dto;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
public record LeadDashboardResponse(long captures, long newLeads, long wonInPeriod, Long medianDaysToWin,
long overdueFollowUps, Map<String, Long> funnel, List<TrendPoint> trend,
List<EventRow> events, List<Salesperson> salespeople, List<InterestRow> interests) {
public record TrendPoint(LocalDate bucket, long captures, long wins) {}
public record EventRow(String eventUuid, String name, Long companyId, long captures, long newLeads, long won) {}
public record Salesperson(Long userId, long assigned, long worked, long won, long lost, long overdue) {}
public record InterestRow(long interestId, String name, long captures, long won) {}
}
@@ -0,0 +1,31 @@
package com.solvway.services.counter.model;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
/** Append-only status history of an event lead; rows are never updated or deleted. */
@Getter
@Setter
@Entity
@Table(name = "event_lead_status_change")
public class EventLeadStatusChange {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private long companyId;
private long eventLeadId;
/** Null for the first row written at capture. */
private String fromStatus;
private String toStatus;
private LocalDateTime changedAt;
private String changedBy;
}
@@ -0,0 +1,8 @@
package com.solvway.services.counter.repo;
import com.solvway.services.counter.model.EventLeadStatusChange;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EventLeadStatusChangeRepository extends JpaRepository<EventLeadStatusChange, Long> {}
@@ -0,0 +1,58 @@
package com.solvway.services.counter.repo;
import com.solvway.services.counter.model.EventLead;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
/** Read-only dashboard queries. Times are bound as wall time in the JVM default zone; companyId null means all. */
public interface LeadDashboardRepository extends Repository<EventLead, Long> {
interface CaptureRow {
long getId();
long getEventUuid();
String getEventName();
long getCompanyId();
Long getSalespersonUserId();
String getLeadType();
String getStatus();
LocalDateTime getCapturedAt();
}
interface WinRow {
long getId();
LocalDateTime getCapturedAt();
LocalDateTime getWonAt();
}
interface OverdueRow {
Long getSalespersonUserId();
long getTotal();
}
@Query(nativeQuery = true, value = "SELECT el.id AS id, el.event_uuid AS eventUuid, ev.name AS eventName,"
+ " el.company_id AS companyId, el.salesperson_user_id AS salespersonUserId, el.lead_type AS leadType,"
+ " el.status AS status, el.captured_at AS capturedAt FROM event_lead el"
+ " LEFT JOIN `event` ev ON ev.uuid = el.event_uuid"
+ " WHERE (:companyId IS NULL OR el.company_id = :companyId) AND el.captured_at >= :fromTs AND el.captured_at < :toTs")
List<CaptureRow> captures(@Param("companyId") Long companyId, @Param("fromTs") LocalDateTime fromTs,
@Param("toTs") LocalDateTime toTs);
/** Leads currently WON whose latest transition to WON falls in the period. */
@Query(nativeQuery = true, value = "SELECT el.id AS id, el.captured_at AS capturedAt, w.won_at AS wonAt"
+ " FROM event_lead el JOIN (SELECT event_lead_id, MAX(changed_at) won_at FROM event_lead_status_change"
+ " WHERE to_status = 'WON' AND (:companyId IS NULL OR company_id = :companyId) GROUP BY event_lead_id) w ON w.event_lead_id = el.id"
+ " WHERE el.status = 'WON' AND (:companyId IS NULL OR el.company_id = :companyId)"
+ " AND w.won_at >= :fromTs AND w.won_at < :toTs")
List<WinRow> wins(@Param("companyId") Long companyId, @Param("fromTs") LocalDateTime fromTs,
@Param("toTs") LocalDateTime toTs);
@Query(nativeQuery = true, value = "SELECT salesperson_user_id AS salespersonUserId, COUNT(*) AS total FROM event_lead"
+ " WHERE (:companyId IS NULL OR company_id = :companyId) AND status NOT IN ('WON', 'LOST')"
+ " AND next_follow_up_date < :today GROUP BY salesperson_user_id")
List<OverdueRow> overdue(@Param("companyId") Long companyId, @Param("today") LocalDate today);
}
@@ -9,9 +9,11 @@ import com.solvway.services.counter.dto.LeadMatchRequest;
import com.solvway.services.counter.model.EventLead;
import com.solvway.services.counter.model.EventLeadInterest;
import com.solvway.services.counter.model.EventLeadInterestId;
import com.solvway.services.counter.model.EventLeadStatusChange;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventLeadStatusChangeRepository;
import com.solvway.services.counter.repo.LeadRepository;
import lombok.AllArgsConstructor;
import org.springframework.dao.DataIntegrityViolationException;
@@ -45,6 +47,7 @@ public class EventLeadService {
private final LeadRepository leadRepository;
private final EventLeadRepository eventLeadRepository;
private final EventLeadInterestRepository eventLeadInterestRepository;
private final EventLeadStatusChangeRepository eventLeadStatusChangeRepository;
public List<LeadMatch> findMatches(LeadMatchRequest req) {
requireCompany(req.companyId());
@@ -115,6 +118,7 @@ public class EventLeadService {
throw new ResponseStatusException(HttpStatus.CONFLICT, "ALREADY_CAPTURED");
}
recordStatusChange(eventLead, null, eventLead.getStatus(), eventLead.getCapturedAt(), req.doneBy());
List<Long> interestIds = saveInterests(eventLead.getId(), req.companyId(), req.interestIds());
return detail(eventLead, lead, interestIds);
}
@@ -154,12 +158,16 @@ public class EventLeadService {
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
eventLead.setSalespersonUserId(req.salespersonUserId());
eventLead.setTemperature(blankToNull(req.temperature()));
String oldStatus = eventLead.getStatus();
if (req.status() != null) eventLead.setStatus(req.status());
eventLead.setNextFollowUpDate(req.nextFollowUpDate());
eventLead.setNotes(blankToNull(req.notes()));
eventLead.setUpdatedBy(req.doneBy());
eventLead.setUpdatedAt(LocalDateTime.now());
eventLead = eventLeadRepository.saveAndFlush(eventLead);
if (req.status() != null && !req.status().equals(oldStatus)) {
recordStatusChange(eventLead, oldStatus, req.status(), eventLead.getUpdatedAt(), req.doneBy());
}
eventLeadInterestRepository.deleteByEventLeadId(eventLead.getId());
List<Long> interestIds = saveInterests(eventLead.getId(), req.companyId(), req.interestIds());
Lead lead = leadRepository.findByUuidAndCompanyId(eventLead.getLeadUuid(), req.companyId())
@@ -167,6 +175,17 @@ public class EventLeadService {
return detail(eventLead, lead, interestIds);
}
private void recordStatusChange(EventLead e, String from, String to, LocalDateTime at, String by) {
EventLeadStatusChange row = new EventLeadStatusChange();
row.setCompanyId(e.getCompanyId());
row.setEventLeadId(e.getId());
row.setFromStatus(from);
row.setToStatus(to);
row.setChangedAt(at);
row.setChangedBy(by);
eventLeadStatusChangeRepository.save(row);
}
private static void requireCompany(Long companyId) {
if (companyId == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED");
}
@@ -0,0 +1,170 @@
package com.solvway.services.counter.dashboard;
import com.solvway.services.counter.dto.LeadDashboardRequest.Bucket;
import com.solvway.services.counter.dto.LeadDashboardResponse;
import com.solvway.services.counter.dashboard.LeadDashboardCalculator.Capture;
import com.solvway.services.counter.dashboard.LeadDashboardCalculator.Overdue;
import com.solvway.services.counter.dashboard.LeadDashboardCalculator.Win;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
class LeadDashboardCalculatorTest {
private static final ZoneId UTC = ZoneId.of("UTC");
private static final LocalDate FROM = LocalDate.of(2026, 11, 1);
private static final LocalDate TO = LocalDate.of(2026, 11, 30);
private static final LocalDateTime T = LocalDateTime.of(2026, 11, 10, 2, 0);
private static Capture cap(long id, long ev, String evName, Long sp, String type, String status, LocalDateTime at) {
return new Capture(id, ev, evName, 2L, sp, type, status, at);
}
private static LeadDashboardResponse calc(Bucket b, List<Capture> c, List<Win> w, List<Overdue> o,
Map<Long, List<Long>> li, Map<Long, String> names) {
return LeadDashboardCalculator.calculate(FROM, TO, b, UTC, c, w, o, li, names);
}
private static LeadDashboardResponse calc(List<Capture> c, List<Win> w, List<Overdue> o) {
return calc(Bucket.DAY, c, w, o, Map.of(), Map.of());
}
@Test
void countsCapturesNewLeadsAndFunnelWithAllKeysInOrder() {
LeadDashboardResponse r = calc(List.of(
cap(1, 10, "A", 7L, "NEW", "OPEN", T), cap(2, 10, "A", 7L, "EXISTING", "WON", T),
cap(3, 10, "A", 7L, "NEW", "OPEN", T)), List.of(), List.of());
assertThat(r.captures()).isEqualTo(3);
assertThat(r.newLeads()).isEqualTo(2);
assertThat(r.funnel().keySet()).containsExactly("OPEN", "CONTACTED", "QUALIFIED", "WON", "LOST");
assertThat(r.funnel()).containsEntry("OPEN", 2L).containsEntry("WON", 1L).containsEntry("LOST", 0L);
}
@Test
void wonInPeriodCountsWinRowsAndMedianIsLowerMiddle() {
LocalDateTime c = LocalDateTime.of(2026, 11, 1, 10, 0);
List<Win> odd = List.of(new Win(1, c, c.plusDays(1)), new Win(2, c, c.plusDays(9)), new Win(3, c, c.plusDays(5)));
assertThat(calc(List.of(), odd, List.of()).wonInPeriod()).isEqualTo(3);
assertThat(calc(List.of(), odd, List.of()).medianDaysToWin()).isEqualTo(5L);
List<Win> even = List.of(new Win(1, c, c.plusDays(2)), new Win(2, c, c.plusDays(8)));
assertThat(calc(List.of(), even, List.of()).medianDaysToWin()).isEqualTo(2L);
}
@Test
void medianIsNullWithoutWins() {
LeadDashboardResponse r = calc(List.of(), List.of(), List.of());
assertThat(r.wonInPeriod()).isZero();
assertThat(r.medianDaysToWin()).isNull();
}
@Test
void medianUsesKualaLumpurDates() {
// 2026-11-01 17:00 UTC = 2 Nov 01:00 KL; 2026-11-03 15:00 UTC = 3 Nov 23:00 KL -> 1 day
Win w = new Win(1, LocalDateTime.of(2026, 11, 1, 17, 0), LocalDateTime.of(2026, 11, 3, 15, 0));
assertThat(calc(List.of(), List.of(w), List.of()).medianDaysToWin()).isEqualTo(1L);
}
@Test
void overdueSumsAndSalespeopleIncludeOverdueOnlyAndUnassigned() {
LeadDashboardResponse r = calc(List.of(
cap(1, 10, "A", 7L, "NEW", "OPEN", T), cap(2, 10, "A", 7L, "NEW", "CONTACTED", T),
cap(3, 10, "A", 7L, "NEW", "WON", T), cap(4, 10, "A", 7L, "NEW", "LOST", T),
cap(5, 10, "A", null, "NEW", "OPEN", T)),
List.of(), List.of(new Overdue(7L, 2), new Overdue(9L, 5), new Overdue(null, 1)));
assertThat(r.overdueFollowUps()).isEqualTo(8);
assertThat(r.salespeople()).extracting(LeadDashboardResponse.Salesperson::userId)
.containsExactly(7L, null, 9L);
LeadDashboardResponse.Salesperson s7 = r.salespeople().get(0);
assertThat(s7.assigned()).isEqualTo(4);
assertThat(s7.worked()).isEqualTo(3);
assertThat(s7.won()).isEqualTo(1);
assertThat(s7.lost()).isEqualTo(1);
assertThat(s7.overdue()).isEqualTo(2);
LeadDashboardResponse.Salesperson s9 = r.salespeople().get(2);
assertThat(s9.assigned()).isZero();
assertThat(s9.overdue()).isEqualTo(5);
LeadDashboardResponse.Salesperson un = r.salespeople().get(1);
assertThat(un.assigned()).isEqualTo(1);
assertThat(un.overdue()).isEqualTo(1);
}
@Test
void salespeopleOrderByAssignedThenOverdueThenUserIdNullLast() {
LeadDashboardResponse r = calc(List.of(
cap(1, 10, "A", null, "NEW", "OPEN", T), cap(2, 10, "A", 5L, "NEW", "OPEN", T),
cap(3, 10, "A", 3L, "NEW", "OPEN", T)), List.of(), List.of());
assertThat(r.salespeople()).extracting(LeadDashboardResponse.Salesperson::userId)
.containsExactly(3L, 5L, null);
}
@Test
void interestWithTwoInterestsCountsUnderBoth() {
LeadDashboardResponse r = calc(Bucket.DAY,
List.of(cap(1, 10, "A", 7L, "NEW", "WON", T), cap(2, 10, "A", 7L, "NEW", "OPEN", T)),
List.of(), List.of(), Map.of(1L, List.of(5L, 6L), 2L, List.of(6L)),
Map.of(5L, "Cookware", 6L, "Appliances"));
assertThat(r.interests()).extracting(LeadDashboardResponse.InterestRow::name, LeadDashboardResponse.InterestRow::captures,
LeadDashboardResponse.InterestRow::won).containsExactly(
org.assertj.core.groups.Tuple.tuple("Appliances", 2L, 1L),
org.assertj.core.groups.Tuple.tuple("Cookware", 1L, 1L));
}
@Test
void eventsOrderedByCapturesDescThenNameWithWonAndUuidAsString() {
LeadDashboardResponse r = calc(List.of(
cap(1, 10, "Zed", 7L, "NEW", "WON", T), cap(2, 20, "Alpha", 7L, "EXISTING", "OPEN", T),
cap(3, 30, "Beta", 7L, "NEW", "OPEN", T), cap(4, 10, "Zed", 7L, "NEW", "OPEN", T)),
List.of(), List.of());
assertThat(r.events()).extracting(LeadDashboardResponse.EventRow::eventUuid).containsExactly("10", "20", "30");
LeadDashboardResponse.EventRow zed = r.events().get(0);
assertThat(zed.captures()).isEqualTo(2);
assertThat(zed.newLeads()).isEqualTo(2);
assertThat(zed.won()).isEqualTo(1);
assertThat(zed.companyId()).isEqualTo(2L);
}
@Test
void eventWithNullNameSortsLastAmongEqualCaptures() {
LeadDashboardResponse r = calc(List.of(
cap(1, 10, null, 7L, "NEW", "OPEN", T), cap(2, 20, "Beta", 7L, "NEW", "OPEN", T),
cap(3, 30, "Alpha", 7L, "NEW", "OPEN", T)), List.of(), List.of());
assertThat(r.events()).extracting(LeadDashboardResponse.EventRow::eventUuid).containsExactly("30", "20", "10");
}
@Test
void dayTrendIsZeroFilledAndAscending() {
LeadDashboardResponse r = calc(List.of(cap(1, 10, "A", 7L, "NEW", "OPEN", LocalDateTime.of(2026, 11, 3, 2, 0))),
List.of(new Win(2, T, LocalDateTime.of(2026, 11, 3, 3, 0))), List.of());
assertThat(r.trend()).hasSize(30);
assertThat(r.trend().get(0).bucket()).isEqualTo(LocalDate.of(2026, 11, 1));
assertThat(r.trend().get(2).bucket()).isEqualTo(LocalDate.of(2026, 11, 3));
assertThat(r.trend().get(2).captures()).isEqualTo(1);
assertThat(r.trend().get(2).wins()).isEqualTo(1);
assertThat(r.trend().get(1).captures()).isZero();
}
@Test
void monthTrendStartsAtFirstOfFromMonth() {
LeadDashboardResponse r = LeadDashboardCalculator.calculate(LocalDate.of(2026, 1, 15), LocalDate.of(2026, 3, 2),
Bucket.MONTH, UTC, List.of(cap(1, 10, "A", 7L, "NEW", "OPEN", LocalDateTime.of(2026, 2, 20, 1, 0))),
List.of(), List.of(), Map.of(), Map.of());
assertThat(r.trend()).extracting(LeadDashboardResponse.TrendPoint::bucket)
.containsExactly(LocalDate.of(2026, 1, 1), LocalDate.of(2026, 2, 1), LocalDate.of(2026, 3, 1));
assertThat(r.trend().get(1).captures()).isEqualTo(1);
}
@Test
void kualaLumpurDayBoundary() {
LeadDashboardResponse r = calc(List.of(
cap(1, 10, "A", 7L, "NEW", "OPEN", LocalDateTime.of(2026, 11, 30, 15, 30)),
cap(2, 10, "A", 7L, "NEW", "OPEN", LocalDateTime.of(2026, 11, 30, 16, 30))), List.of(), List.of());
assertThat(r.trend().get(29).captures()).isEqualTo(1); // 30 Nov
assertThat(r.trend()).hasSize(30);
}
}
@@ -0,0 +1,82 @@
package com.solvway.services.counter.dashboard;
import com.solvway.services.counter.dto.LeadDashboardRequest;
import com.solvway.services.counter.dto.LeadDashboardRequest.Bucket;
import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.InterestRepository;
import com.solvway.services.counter.repo.LeadDashboardRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class LeadDashboardServiceTest {
@Mock private LeadDashboardRepository repo;
@Mock private EventLeadInterestRepository interests;
@Mock private InterestRepository interestRepository;
private LeadDashboardService service() {
return new LeadDashboardService(repo, interests, interestRepository);
}
@Test
void fromAfterToIsInvalidPeriod() {
LeadDashboardRequest req = new LeadDashboardRequest(2L, LocalDate.of(2026, 11, 30), LocalDate.of(2026, 11, 1), Bucket.DAY);
assertThatThrownBy(() -> service().leads(req)).isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(e.getReason()).isEqualTo("INVALID_PERIOD");
});
}
@Test
void missingFieldsAreBadRequest() {
assertThatThrownBy(() -> service().leads(new LeadDashboardRequest(null, null, LocalDate.now(), Bucket.DAY)))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST));
assertThatThrownBy(() -> service().leads(new LeadDashboardRequest(null, LocalDate.now(), LocalDate.now(), null)))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST));
}
@Test
void nullCompanyPassesThroughAndPeriodIsKualaLumpurDaysInSystemZone() {
when(repo.captures(any(), any(), any())).thenReturn(List.of());
when(repo.wins(any(), any(), any())).thenReturn(List.of());
when(repo.overdue(any(), any())).thenReturn(List.of());
service().leads(new LeadDashboardRequest(null, LocalDate.of(2026, 11, 1), LocalDate.of(2026, 11, 30), Bucket.MONTH));
LocalDateTime start = LocalDate.of(2026, 11, 1).atStartOfDay(ZoneId.of("Asia/Kuala_Lumpur"))
.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
LocalDateTime end = LocalDate.of(2026, 12, 1).atStartOfDay(ZoneId.of("Asia/Kuala_Lumpur"))
.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
verify(repo).captures(eq(null), eq(start), eq(end));
verify(repo).wins(eq(null), eq(start), eq(end));
verify(repo).overdue(eq(null), any());
}
@Test
void rangeOf731DaysIsAcceptedAnd732IsRefused() {
LocalDate from = LocalDate.of(2025, 1, 1);
when(repo.captures(any(), any(), any())).thenReturn(List.of());
when(repo.wins(any(), any(), any())).thenReturn(List.of());
when(repo.overdue(any(), any())).thenReturn(List.of());
assertThat(service().leads(new LeadDashboardRequest(null, from, from.plusDays(730), Bucket.DAY)).trend()).hasSize(731);
assertThatThrownBy(() -> service().leads(new LeadDashboardRequest(null, from, from.plusDays(731), Bucket.DAY)))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(e.getReason()).isEqualTo("INVALID_PERIOD");
});
}
}
@@ -9,6 +9,7 @@ import com.solvway.services.counter.model.EventLeadInterestId;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventLeadStatusChangeRepository;
import com.solvway.services.counter.repo.LeadRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -49,12 +50,13 @@ class EventLeadListAndUpdateTest {
@Mock private LeadRepository leadRepository;
@Mock private EventLeadRepository eventLeadRepository;
@Mock private EventLeadInterestRepository eventLeadInterestRepository;
@Mock private EventLeadStatusChangeRepository eventLeadStatusChangeRepository;
private EventLeadService service;
@BeforeEach
void setUp() {
service = new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository);
service = new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository, eventLeadStatusChangeRepository);
}
@Test
@@ -10,6 +10,7 @@ import com.solvway.services.counter.model.EventLeadInterestId;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventLeadStatusChangeRepository;
import com.solvway.services.counter.repo.LeadRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -50,12 +51,13 @@ class EventLeadServiceTest {
@Mock private LeadRepository leadRepository;
@Mock private EventLeadRepository eventLeadRepository;
@Mock private EventLeadInterestRepository eventLeadInterestRepository;
@Mock private EventLeadStatusChangeRepository eventLeadStatusChangeRepository;
private EventLeadService service;
@BeforeEach
void setUp() {
service = new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository);
service = new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository, eventLeadStatusChangeRepository);
}
// --- findMatches ---
@@ -0,0 +1,133 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.dto.EventLeadCaptureRequest;
import com.solvway.services.counter.dto.EventLeadUpdateRequest;
import com.solvway.services.counter.model.EventLead;
import com.solvway.services.counter.model.EventLeadStatusChange;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventLeadStatusChangeRepository;
import com.solvway.services.counter.repo.LeadRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** Event lead status history: capture writes the first row, update writes one row per real status change. */
@ExtendWith(MockitoExtension.class)
class EventLeadStatusHistoryTest {
private static final long COMPANY = 42L;
@Mock private LeadRepository leadRepository;
@Mock private EventLeadRepository eventLeadRepository;
@Mock private EventLeadInterestRepository eventLeadInterestRepository;
@Mock private EventLeadStatusChangeRepository history;
private EventLeadService service() {
return new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository, history);
}
private static EventLeadCaptureRequest capture(String status) {
return new EventLeadCaptureRequest(COMPANY, 1000L, null, "Aisyah", null, null, null, null, 11L, null, status,
List.of(), null, null, "sales1");
}
private static EventLead existing(String status) {
EventLead e = new EventLead();
e.setId(7L);
e.setCompanyId(COMPANY);
e.setLeadUuid(501L);
e.setStatus(status);
return e;
}
private static EventLeadUpdateRequest update(EventLead e, String status) {
return new EventLeadUpdateRequest(COMPANY, e.getUuid(), null, null, status, List.of(), null, null, "sales2");
}
private void stubUpdate(EventLead e) {
when(eventLeadRepository.findByUuidAndCompanyId(e.getUuid(), COMPANY)).thenReturn(Optional.of(e));
when(eventLeadRepository.saveAndFlush(e)).thenReturn(e);
when(leadRepository.findByUuidAndCompanyId(501L, COMPANY)).thenReturn(Optional.of(new Lead()));
}
@Test
void captureWritesTheFirstHistoryRow() {
when(leadRepository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0));
when(eventLeadRepository.saveAndFlush(any())).thenAnswer(inv -> {
EventLead e = inv.getArgument(0);
e.setId(7L);
return e;
});
service().capture(capture("QUALIFIED"));
ArgumentCaptor<EventLeadStatusChange> row = ArgumentCaptor.forClass(EventLeadStatusChange.class);
verify(history).save(row.capture());
assertThat(row.getValue().getFromStatus()).isNull();
assertThat(row.getValue().getToStatus()).isEqualTo("QUALIFIED");
assertThat(row.getValue().getEventLeadId()).isEqualTo(7L);
assertThat(row.getValue().getCompanyId()).isEqualTo(COMPANY);
assertThat(row.getValue().getChangedBy()).isEqualTo("sales1");
assertThat(row.getValue().getChangedAt()).isNotNull();
}
@Test
void captureDefaultsToOpenAndUsesCapturedAt() {
LocalDateTime at = LocalDateTime.of(2026, 11, 3, 10, 0);
when(leadRepository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0));
when(eventLeadRepository.saveAndFlush(any())).thenAnswer(inv -> {
EventLead e = inv.getArgument(0);
e.setId(7L);
e.setCapturedAt(at);
return e;
});
service().capture(capture(null));
ArgumentCaptor<EventLeadStatusChange> row = ArgumentCaptor.forClass(EventLeadStatusChange.class);
verify(history).save(row.capture());
assertThat(row.getValue().getToStatus()).isEqualTo("OPEN");
assertThat(row.getValue().getChangedAt()).isEqualTo(at);
}
@Test
void updateWritesOneRowWhenStatusChanges() {
EventLead e = existing("OPEN");
stubUpdate(e);
service().update(update(e, "WON"));
ArgumentCaptor<EventLeadStatusChange> row = ArgumentCaptor.forClass(EventLeadStatusChange.class);
verify(history).save(row.capture());
assertThat(row.getValue().getFromStatus()).isEqualTo("OPEN");
assertThat(row.getValue().getToStatus()).isEqualTo("WON");
assertThat(row.getValue().getEventLeadId()).isEqualTo(7L);
assertThat(row.getValue().getCompanyId()).isEqualTo(COMPANY);
assertThat(row.getValue().getChangedBy()).isEqualTo("sales2");
assertThat(row.getValue().getChangedAt()).isEqualTo(e.getUpdatedAt());
}
@Test
void updateWritesNoRowWhenStatusIsUnchangedOrNull() {
EventLead e = existing("OPEN");
stubUpdate(e);
service().update(update(e, "OPEN"));
service().update(update(e, null));
verify(history, never()).save(any());
}
}
@@ -12,6 +12,7 @@ import com.solvway.services.counter.model.EventLead;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventLeadStatusChangeRepository;
import com.solvway.services.counter.repo.LeadRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -46,6 +47,7 @@ class LeadCompanyScopeTest {
@Mock private LeadRepository leadRepository;
@Mock private EventLeadRepository eventLeadRepository;
@Mock private EventLeadInterestRepository eventLeadInterestRepository;
@Mock private EventLeadStatusChangeRepository eventLeadStatusChangeRepository;
private LeadService leadService;
private EventLeadService eventLeadService;
@@ -53,7 +55,7 @@ class LeadCompanyScopeTest {
@BeforeEach
void setUp() {
leadService = new LeadService(leadRepository, eventLeadRepository);
eventLeadService = new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository);
eventLeadService = new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository, eventLeadStatusChangeRepository);
}
private static Lead lead(long uuid, long companyId) {