From 9ccbac4aca7aa8a1fc85efb034b7ecff0a16b143 Mon Sep 17 00:00:00 2001 From: Oleksandr Prokhorenko Date: Thu, 24 Sep 2026 22:18:41 +0300 Subject: [PATCH] Added tasks, reminders, and role-specific dashboards --- README.md | 30 +- apps/api/src/access.ts | 4 +- apps/api/src/app.ts | 2 + apps/api/src/crm.ts | 216 +++------ apps/api/src/dashboard.ts | 193 ++++++++ apps/api/src/merchant-query.ts | 37 ++ apps/api/src/reminders.ts | 61 +++ apps/api/src/review-query.ts | 42 ++ apps/api/src/task-policy.ts | 94 ++++ apps/api/src/workflow.ts | 45 +- apps/api/test/integration.test.mjs | 13 +- apps/api/test/tasks-dashboards.test.mjs | 441 ++++++++++++++++++ apps/api/test/unit.test.mjs | 24 + apps/web/src/components/dashboard.tsx | 342 ++++++++++++++ apps/web/src/components/merchant-workflow.tsx | 110 +---- apps/web/src/components/reminders.tsx | 97 ++++ apps/web/src/components/shared.tsx | 24 +- apps/web/src/components/shell.tsx | 2 + apps/web/src/components/tasks.tsx | 361 ++++++++++++++ apps/web/src/lib/directory-params.ts | 11 +- apps/web/src/lib/live-refresh.ts | 19 + apps/web/src/lib/review-params.ts | 12 +- apps/web/src/locales.ts | 5 + apps/web/src/pages/crm.tsx | 283 +++-------- apps/web/src/task-dashboard-locales.ts | 135 ++++++ docs/implementation-checklist.md | 16 + docs/product-brief.md | 8 +- packages/contracts/src/index.ts | 76 ++- .../migration.sql | 3 + packages/database/prisma/schema.prisma | 3 + scripts/test-database.mjs | 1 + tests/tasks-dashboards.spec.ts | 360 ++++++++++++++ tests/workspace.spec.ts | 24 +- 33 files changed, 2583 insertions(+), 511 deletions(-) create mode 100644 apps/api/src/dashboard.ts create mode 100644 apps/api/src/merchant-query.ts create mode 100644 apps/api/src/reminders.ts create mode 100644 apps/api/src/review-query.ts create mode 100644 apps/api/src/task-policy.ts create mode 100644 apps/api/test/tasks-dashboards.test.mjs create mode 100644 apps/web/src/components/dashboard.tsx create mode 100644 apps/web/src/components/reminders.tsx create mode 100644 apps/web/src/components/tasks.tsx create mode 100644 apps/web/src/lib/live-refresh.ts create mode 100644 apps/web/src/task-dashboard-locales.ts create mode 100644 packages/database/prisma/migrations/202609240007_tasks_dashboards/migration.sql create mode 100644 tests/tasks-dashboards.spec.ts diff --git a/README.md b/README.md index e5bc5d9..2fc57be 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ Public routes are `/` and `/login`. CRM routes are `/app`, `/app/merchants`, `/a | GET | `/api/merchants?search=&status=&country=&industry=&ownerId=&page=1` | Scoped combined filters; 8 records per page | | GET | `/api/merchants/:id` | Overview, checklist, notes, tasks, history | | GET | `/api/pipeline` | Scoped merchants grouped in the UI | -| GET | `/api/tasks?filter=ALL` | ALL / OPEN / OVERDUE / UPCOMING / DONE | +| GET | `/api/tasks?filter=ALL` | TODAY / UPCOMING / OVERDUE / DONE; ALL / OPEN retained | | GET | `/api/review-queue` | Compliance-only, oldest review first | Passwords are salted with scrypt. A random session token lives in an HttpOnly, SameSite=Lax cookie; only its SHA-256 digest is stored in PostgreSQL. Sessions expire after eight hours. Every mutation, including login/logout, requires an exact trusted `Origin` and rejects cross-site Fetch Metadata. Local login limits allow 100 attempts per IP and 20 per normalized email per five minutes, include `Retry-After`, and bound the in-memory bucket map to 10,000 entries. These limits are designed for this single-process local prototype. The UI clears private query caches on logout, login and API session rejection. @@ -108,9 +108,9 @@ Apply checked-in additive migrations with `pnpm db:migrate` when upgrading an ex The successful path is **New Lead → Contacted → Qualified → KYB → Compliance Review → Integration → Testing → Live**. **Rejected** is a separate terminal outcome. Luma Labs demonstrates a historical return from Compliance Review to KYB for corrections. -The seed creates 45 merchants, 90 commercial tasks, additional personal compliance tasks, interactions, document checklists and change history, review cycles and chronological stage history spanning 90 days. Fresh fixtures include 7 New Leads, 5 Contacted, 5 Qualified, 6 KYB, 6 Compliance Review, 4 Integration, 4 Testing, 5 Live and 3 Rejected. Dates are relative to the first seed, then preserved. There are no fabricated trend percentages or payment metrics. The dashboard counts visible merchants, current review records, open overdue tasks, and non-initial status changes during the past 30 days. Its activity feed uses persisted interactions and immutable audit events; counts naturally change as fixtures age. +The seed creates 45 merchants, 90 commercial tasks, additional personal compliance tasks, interactions, document checklists and change history, review cycles and chronological stage history spanning 90 days. Fresh fixtures include 7 New Leads, 5 Contacted, 5 Qualified, 6 KYB, 6 Compliance Review, 4 Integration, 4 Testing, 5 Live and 3 Rejected. Dates are relative to the first seed, then preserved. There are no fabricated trend percentages or payment metrics. Role-specific dashboards derive portfolio, workload and review metrics from scoped database records. Its activity feed uses persisted interactions and immutable audit events; counts naturally change as fixtures age. -English is the default; EN/RU selection persists in local storage, including across sign-out. Dates and numbers use `Intl` and the viewer's local timezone. Status, role, industry and document labels are translated from canonical codes. Names, task titles and user notes remain verbatim. Checklist collection, review decisions, interaction logging and task management are available from merchant details. Reminders are derived from stored dates and refresh inside the app, without background notification infrastructure. +English is the default; EN/RU selection persists in local storage, including across sign-out. Dates and numbers use `Intl` and the viewer's local timezone. Status, role, industry and document labels are translated from canonical codes. Names, task titles and user notes remain verbatim. Checklist collection, review decisions, interaction logging and task management are available from merchant details. Reminders and their dismissals persist in PostgreSQL and refresh in the app while visible and on focus or reconnection. ## Verification @@ -140,7 +140,7 @@ The [product brief](docs/product-brief.md) and [implementation checklist](docs/i ## Editing and workflow rules -Head of Sales can edit commercial details for the portfolio, assign/reassign Account Managers, collect KYB documents, and manage commercial activities/tasks. Managers can perform commercial actions only for currently assigned merchants and cannot change ownership. Compliance can read merchant context and KYB across every stage, record reviews and KYB notes, and manage only personal compliance tasks. Head and managers can view related compliance tasks but cannot change them. Query predicates enforce these scopes on lists, search, totals, dashboard, detail children, and mutation targets. +Head of Sales can edit commercial details for the portfolio, assign/reassign Account Managers, collect KYB documents, and manage commercial activities/tasks. Managers can perform commercial actions only for currently assigned merchants and cannot change ownership. Compliance can read merchant context and KYB across every stage, record reviews and KYB notes, and manage only personal compliance tasks. Personal Compliance tasks are private; Head and managers see commercial tasks only. Query predicates enforce these scopes on lists, search, totals, dashboard, detail children, and mutation targets. Only adjacent commercial stage advances are accepted, plus the explicit legacy return-to-KYB action described below. A manager must be assigned before leaving New Lead. Contacted requires a logged call or email. Qualified requires company name, website, contact name/email, country, industry and an estimated volume; zero is valid. In KYB, Head or the assigned Manager records Missing/Received status and collection notes for company registration, ownership structure and authorized-representative identification. These are checklist records, with no uploads. Submission requires all three required checklist records to have received-history evidence and creates one pending review. Company/KYB fields freeze while that review is pending. Compliance can approve with Low/Medium/High risk and a required rationale (atomically advancing to Integration), reject with a reason, or request item-specific corrections stored with the review, separately from collection notes (returning to KYB). Resubmission creates a new review cycle. Decisions and system history cannot be edited. @@ -203,3 +203,25 @@ Current review policy version 2 requires exactly three active KYB records. `docu Merchant detail includes review snapshots, risk and immutable correction notes, activation check history, and server-derived handoff/edit capabilities. Review links use `?tab=onboarding#review-` and remain valid after decisions. Apply the two new additive migrations with `pnpm db:migrate`; do not reset or reseed development data. Old review cycles retain policy version 1 and their original evidence. Legacy beneficial-owner ID and business-activity items become read-only historical requirements. Unfinished merchants receive a new Missing representative-identification record; terminal records remain untouched. Old pending reviews require corrections/resubmission or rejection. Old approvals cannot authorize further activation: use Return to KYB for re-review. Existing decisions, notes, timestamps and passwords are preserved, and no risk or demo results are inferred for existing fixtures. Fresh fixtures include current-policy approval/check evidence; seed reruns preserve existing records. + +## Tasks, reminders, and operational dashboards + +Apply migration `202609240007_tasks_dashboards` with `pnpm db:migrate`; no reset or reseed is required. It adds reminder dismissal, a revision number and an assignee/status/reminder index without changing existing task values. + +Tasks and merchant details share creation, editing, completion and reopening controls. The merchant selector uses the scoped directory. Mutation payloads retain the existing `{version,title,dueAt,remindAt,status}` contract; assignee and task kind are server-derived. Responses include merchant version and task action capabilities. An open editor retains its starting version; a conflict preserves inputs and offers an explicit current-version refresh before resubmission. + +Sales tasks follow the merchant owner; unassigned lead tasks belong to the Head. Reassignment atomically transfers open commercial tasks and resets their reminder dismissal. Completed attribution and Compliance tasks stay intact. A new manager may reopen an inherited completed task; its previous completion is audited before it is assigned to the current manager. Personal Compliance tasks never appear in Sales task lists or dashboards. + +| Endpoint | Behavior | +| -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `GET /api/tasks?filter=TODAY&timeZone=Europe/Kyiv` | Open tasks due during the viewer’s local day, including overdue tasks due today. `UPCOMING` begins tomorrow, `OVERDUE` is due before now, and `DONE` is completed. `ALL` and `OPEN` remain supported. Optional `merchantId` and authorized `assigneeId` filters combine with role scope. | +| `GET /api/reminders` | Only the caller’s visible, open, undismissed tasks with `remindAt <= now`; includes `reminderRevision`. | +| `POST /api/tasks/:id/reminder-dismissal` | `{reminderRevision}`; persists dismissal, is idempotent for that revision, and rejects stale revisions with 409. | +| `GET /api/merchants` | Adds UTC `createdFrom`/`createdTo` inclusive bounds and `cohort=ACTIVE_ONBOARDING\|REACHED_LIVE` to the existing combined filters. | +| `GET /api/review-queue?view=DECISIONS` | Compliance-only decided review history, newest decision first, with optional `decision`, `decidedFrom`, and `decidedTo`. Default view remains pending reviews. | + +The inbox polls every 30 seconds while visible and refreshes immediately on mount, focus, visibility restoration and reconnection. Completion suppresses reminders; reopening preserves dismissal. A change to reminder time or assignee starts a fresh revision. Title-only edits preserve exact stored reminder timestamps. UTC instants are stored and transported; the UI shows local dates/times and uses DST-aware local-day boundaries. No browser storage, external notifications or scheduler is required for reminders. + +Head dashboards show total merchants, created leads during the last 30 days, active onboarding (KYB through Testing), Live merchants, all-stage distribution, manager workload, overdue sales tasks and unassigned New Leads. Workload shows assigned merchants, active onboarding, open sales tasks and overdue sales tasks, including managers with zero work. Managers get their assigned scope and own workload, with next actions first. Compliance gets pending reviews, oldest waiting cycles, 30-day decision counts by outcome and personal review tasks. + +Activation rate is **currently Live / all visible merchants**, including Rejected. Average onboarding duration is **creation to earliest recorded Live transition**, once per visible merchant with such an event. Neither uses current-stage entry time as a substitute. The UI shows denominators/sample counts and honest empty states. Totals and charts come from a repeatable-read database snapshot with one captured time; their drilldowns reuse the same predicates. Thirty-day drilldowns preserve the snapshot’s UTC period bounds in the URL. Live operational lists refresh as records and time change. diff --git a/apps/api/src/access.ts b/apps/api/src/access.ts index e667378..722e76b 100644 --- a/apps/api/src/access.ts +++ b/apps/api/src/access.ts @@ -19,7 +19,9 @@ export function merchantScope(user: User): Prisma.MerchantWhereInput { export function taskScope(user: User): Prisma.TaskWhereInput { return { merchant: merchantScope(user), - ...(user.role === 'COMPLIANCE_OFFICER' ? { assigneeId: user.id, kind: 'COMPLIANCE' } : {}), + ...(user.role === 'COMPLIANCE_OFFICER' + ? { assigneeId: user.id, kind: 'COMPLIANCE' } + : { kind: 'COMMERCIAL' }), }; } export function requireSales(user: User) { diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 489b449..6f7b74a 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -11,6 +11,7 @@ import { NestFactory } from '@nestjs/core'; import cookieParser from 'cookie-parser'; import { createDatabase, PrismaClient } from '@merchantflow/database'; import { AuthController, AuthService, SessionGuard } from './auth.js'; +import { ReminderController } from './reminders.js'; import { CrmController } from './crm.js'; import { WorkflowController } from './workflow.js'; import { DATABASE, ApiError, ErrorFilter } from './shared.js'; @@ -40,6 +41,7 @@ class DatabaseLifecycle implements OnApplicationShutdown { HealthController, AuthController, CrmController, + ReminderController, WorkflowController, PublicLeadController, ], diff --git a/apps/api/src/crm.ts b/apps/api/src/crm.ts index b5314d8..a96572d 100644 --- a/apps/api/src/crm.ts +++ b/apps/api/src/crm.ts @@ -1,16 +1,15 @@ import { Controller, Get, Inject, Param, Query, Req, UseGuards } from '@nestjs/common'; -import { PrismaClient, type Prisma } from '@merchantflow/database'; -import { - statuses, - merchantQuerySchema, - taskQuerySchema, - reviewQueueQuerySchema, -} from '@merchantflow/contracts'; +import { PrismaClient } from '@merchantflow/database'; +import { merchantQuerySchema, reviewQueueQuerySchema } from '@merchantflow/contracts'; import { SessionGuard } from './auth.js'; import { DATABASE, ApiError, type AuthRequest } from './shared.js'; import { capabilities, merchantScope, taskScope } from './access.js'; import { evidenceInclude } from './workflow-policy.js'; import { merchantHistory } from './history.js'; +import { taskSelect, taskDto, taskWhere, pendingReviews } from './task-policy.js'; +import { merchantWhere } from './merchant-query.js'; +import { reviewWhere } from './review-query.js'; +import { dashboardData } from './dashboard.js'; const merchantSelect = { id: true, name: true, @@ -43,21 +42,6 @@ const eventSelect = { merchant: { select: { id: true, name: true } }, actor: { select: { name: true } }, } as const; -const taskSelect = { - id: true, - title: true, - status: true, - kind: true, - createdAt: true, - updatedAt: true, - dueAt: true, - remindAt: true, - completedAt: true, - merchant: { select: { id: true, name: true } }, - assignee: { select: { id: true, name: true } }, - creator: { select: { name: true } }, - completedBy: { select: { name: true } }, -} as const; const activitySelect = { id: true, kind: true, @@ -80,37 +64,8 @@ export class CrmController { }); } @Get('merchants') async merchants(@Req() req: AuthRequest, @Query() query: unknown) { - const { - page: requestedPage, - search, - status, - country, - industry, - ownerId, - } = merchantQuerySchema.parse(query); - if (ownerId && req.user.role === 'ACCOUNT_MANAGER') throw new ApiError('FORBIDDEN', 403); - const where: Prisma.MerchantWhereInput = { - AND: [ - merchantScope(req.user), - ...(status ? [{ status }] : []), - ...(country ? [{ country }] : []), - ...(industry ? [{ industry }] : []), - ...(ownerId ? [{ ownerId: ownerId === 'unassigned' ? null : ownerId }] : []), - ...(search - ? [ - { - OR: [ - { name: { contains: search, mode: 'insensitive' as const } }, - { contactEmail: { contains: search, mode: 'insensitive' as const } }, - { legalName: { contains: search, mode: 'insensitive' as const } }, - { contactName: { contains: search, mode: 'insensitive' as const } }, - { website: { contains: search, mode: 'insensitive' as const } }, - ], - }, - ] - : []), - ], - }; + const { page: requestedPage } = merchantQuerySchema.parse(query); + const where = merchantWhere(req.user, query); return this.db.$transaction( async (tx) => { const total = await tx.merchant.count({ where }); @@ -181,7 +136,11 @@ export class CrmController { events: { select: eventSelect, orderBy: { occurredAt: 'desc' } }, tasks: { where: taskScope(req.user), select: taskSelect, orderBy: { dueAt: 'asc' } }, activities: { - select: { ...activitySelect, metadata: true }, + select: { + ...activitySelect, + metadata: true, + actor: { select: { id: true, name: true, role: true } }, + }, orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }], }, reviews: { @@ -208,11 +167,37 @@ export class CrmController { where: { AND: [merchantScope(req.user), { id }] }, include: evidenceInclude, }); - const history = await merchantHistory(merchant, tx); + // Personal task audit entries follow the same privacy boundary as the task itself. + // Old creation audits lack taskKind; their authenticated actor role supplies the kind. + const activities = merchant.activities.filter((activity) => { + if ( + activity.kind !== 'AUDIT' || + !['Task created', 'Task updated'].includes(activity.text) + ) + return true; + const meta = + activity.metadata && + typeof activity.metadata === 'object' && + !Array.isArray(activity.metadata) + ? activity.metadata + : {}; + const complianceTask = + meta.taskKind === 'COMPLIANCE' || + (!meta.taskKind && activity.actor?.role === 'COMPLIANCE_OFFICER'); + return req.user.role === 'COMPLIANCE_OFFICER' + ? complianceTask && + (meta.assigneeId === req.user.id || activity.actor?.id === req.user.id) + : !complianceTask; + }); + const history = await merchantHistory({ ...merchant, activities }, tx); return { ...merchant, + tasks: merchant.tasks.map((task) => taskDto(task, req.user)), activationChecks: evidence.reviews.flatMap((review) => review.activationChecks), - activities: merchant.activities.map(({ metadata: _metadata, ...activity }) => activity), + activities: activities.map(({ metadata: _metadata, actor, ...activity }) => ({ + ...activity, + actor: actor ? { id: actor.id, name: actor.name } : null, + })), capabilities: capabilities(req.user, evidence), history, }; @@ -241,63 +226,41 @@ export class CrmController { { isolationLevel: 'RepeatableRead' }, ); } - @Get('tasks') tasks(@Req() req: AuthRequest, @Query() query: unknown) { - const { filter } = taskQuerySchema.parse(query); - const where: Prisma.TaskWhereInput = taskScope(req.user); - if (filter === 'DONE') where.status = 'DONE'; - if (['OPEN', 'OVERDUE', 'UPCOMING'].includes(filter)) where.status = 'OPEN'; - if (filter === 'OVERDUE') where.dueAt = { lt: new Date() }; - if (filter === 'UPCOMING') where.dueAt = { gte: new Date() }; - return this.db.task.findMany({ - where, + @Get('tasks') async tasks(@Req() req: AuthRequest, @Query() query: unknown) { + const rows = await this.db.task.findMany({ + where: taskWhere(req.user, query), select: taskSelect, - orderBy: [{ status: 'asc' }, { dueAt: 'asc' }], + orderBy: [{ status: 'asc' }, { dueAt: 'asc' }, { id: 'asc' }], }); + return rows.map((task) => taskDto(task, req.user)); } @Get('review-queue') async reviewQueue(@Req() req: AuthRequest, @Query() query: unknown) { if (req.user.role !== 'COMPLIANCE_OFFICER') throw new ApiError('FORBIDDEN', 403); - const { search, ownerId, waiting } = reviewQueueQuerySchema.parse(query); - const base: Prisma.ComplianceReviewWhereInput = { - decision: 'PENDING', - merchant: { AND: [merchantScope(req.user), { status: 'COMPLIANCE_REVIEW' }] }, - }; + const { view } = reviewQueueQuerySchema.parse(query); + const pending = pendingReviews(req.user); return this.db.$transaction( async (tx) => { - const pendingCount = await tx.complianceReview.count({ where: base }); + const pendingCount = await tx.complianceReview.count({ where: pending }); const owners = await tx.user.findMany({ where: { role: 'ACCOUNT_MANAGER' }, select: { id: true, name: true }, orderBy: { name: 'asc' }, }); const items = await tx.complianceReview.findMany({ - where: { - AND: [ - base, - { - ...(waiting !== 'ALL' - ? { submittedAt: { lte: new Date(Date.now() - Number(waiting) * 3600000) } } - : {}), - merchant: { - ...(ownerId ? { ownerId: ownerId === 'unassigned' ? null : ownerId } : {}), - ...(search - ? { - OR: ['name', 'legalName', 'contactName', 'contactEmail', 'website'].map( - (field) => ({ [field]: { contains: search, mode: 'insensitive' } }), - ), - } - : {}), - }, - }, - ], - }, + where: reviewWhere(req.user, query), select: { id: true, cycle: true, policyVersion: true, + decision: true, + decidedAt: true, submittedAt: true, merchant: { select: merchantSelect }, }, - orderBy: [{ submittedAt: 'asc' }, { id: 'asc' }], + orderBy: + view === 'PENDING' + ? [{ submittedAt: 'asc' }, { id: 'asc' }] + : [{ decidedAt: 'desc' }, { id: 'asc' }], }); return { items, @@ -309,70 +272,7 @@ export class CrmController { { isolationLevel: 'RepeatableRead' }, ); } - @Get('dashboard') async dashboard(@Req() req: AuthRequest) { - const scope = merchantScope(req.user); - const distributionQuery = this.db.merchant.groupBy({ - by: ['status'], - orderBy: { status: 'asc' }, - where: scope, - _count: { _all: true }, - }); - const [ - merchantCount, - reviewCount, - overdueTasks, - transitionsLast30Days, - distribution, - recentEvents, - upcomingTasks, - recentActivities, - ] = await this.db.$transaction([ - this.db.merchant.count({ where: scope }), - this.db.complianceReview.count({ - where: { decision: 'PENDING', merchant: { AND: [scope, { status: 'COMPLIANCE_REVIEW' }] } }, - }), - this.db.task.count({ - where: { ...taskScope(req.user), status: 'OPEN', dueAt: { lt: new Date() } }, - }), - this.db.statusEvent.count({ - where: { - merchant: scope, - fromStatus: { not: null }, - occurredAt: { gte: new Date(Date.now() - 30 * 86400000) }, - }, - }), - distributionQuery, - this.db.statusEvent.findMany({ - where: { merchant: scope }, - select: eventSelect, - orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }], - take: 6, - }), - this.db.task.findMany({ - where: { ...taskScope(req.user), status: 'OPEN' }, - select: taskSelect, - orderBy: { dueAt: 'asc' }, - take: 4, - }), - this.db.activity.findMany({ - where: { merchant: scope }, - select: activitySelect, - orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }], - take: 8, - }), - ]); - return { - merchantCount, - reviewCount, - overdueTasks, - transitionsLast30Days, - distribution: statuses.map((status) => ({ - status, - count: distribution.find((d) => d.status === status)?._count._all ?? 0, - })), - recentEvents, - upcomingTasks, - recentActivities, - }; + @Get('dashboard') dashboard(@Req() req: AuthRequest) { + return dashboardData(this.db, req.user); } } diff --git a/apps/api/src/dashboard.ts b/apps/api/src/dashboard.ts new file mode 100644 index 0000000..b5bd90a --- /dev/null +++ b/apps/api/src/dashboard.ts @@ -0,0 +1,193 @@ +import { activeOnboardingStages, statuses, type User } from '@merchantflow/contracts'; +import type { PrismaClient } from '@merchantflow/database'; +import { merchantScope, taskScope } from './access.js'; +import { merchantWhere } from './merchant-query.js'; +import { reviewWhere } from './review-query.js'; +import { pendingReviews, taskDto, taskSelect, taskWhere } from './task-policy.js'; +export async function dashboardData(db: PrismaClient, user: User) { + const now = new Date(); + const periodStart = new Date(now.getTime() - 30 * 86400000); + return db.$transaction( + async (tx) => { + const scope = merchantScope(user); + const merchants = await tx.merchant.findMany({ + where: scope, + select: { + id: true, + ownerId: true, + status: true, + createdAt: true, + events: { + where: { toStatus: 'LIVE' }, + orderBy: { occurredAt: 'asc' }, + take: 1, + select: { occurredAt: true }, + }, + }, + }); + const distribution = statuses.map((status) => ({ + status, + count: merchants.filter((m) => m.status === status).length, + })); + const liveMerchants = distribution.find((d) => d.status === 'LIVE')!.count; + const durations = merchants.flatMap((m) => + m.events.length + ? [(m.events[0]!.occurredAt.getTime() - m.createdAt.getTime()) / 86400000] + : [], + ); + const [ + newLeads, + activeOnboarding, + unassignedLeads, + reviewCount, + overdueTasks, + transitionsLast30Days, + recentEvents, + upcomingTasks, + recentActivities, + managers, + tasks, + oldestReviews, + decisions, + ] = await Promise.all([ + tx.merchant.count({ + where: merchantWhere(user, { + createdFrom: periodStart.toISOString(), + createdTo: now.toISOString(), + }), + }), + tx.merchant.count({ where: merchantWhere(user, { cohort: 'ACTIVE_ONBOARDING' }) }), + user.role === 'ACCOUNT_MANAGER' + ? Promise.resolve(0) + : tx.merchant.count({ + where: merchantWhere(user, { ownerId: 'unassigned', status: 'NEW_LEAD' }), + }), + tx.complianceReview.count({ where: pendingReviews(user) }), + tx.task.count({ where: taskWhere(user, { filter: 'OVERDUE' }, now) }), + tx.statusEvent.count({ + where: { + merchant: scope, + fromStatus: { not: null }, + occurredAt: { gte: periodStart, lte: now }, + }, + }), + tx.statusEvent.findMany({ + where: { merchant: scope }, + select: { + id: true, + fromStatus: true, + toStatus: true, + occurredAt: true, + note: true, + merchant: { select: { id: true, name: true } }, + actor: { select: { name: true } }, + }, + orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }], + take: 6, + }), + tx.task.findMany({ + where: taskWhere(user, { filter: 'OPEN' }, now), + select: taskSelect, + orderBy: [{ dueAt: 'asc' }, { id: 'asc' }], + take: 6, + }), + tx.activity.findMany({ + where: { merchant: scope, kind: { not: 'AUDIT' } }, + select: { + id: true, + kind: true, + text: true, + occurredAt: true, + updatedAt: true, + actor: { select: { id: true, name: true } }, + merchant: { select: { id: true, name: true } }, + }, + orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }], + take: 8, + }), + user.role === 'COMPLIANCE_OFFICER' + ? Promise.resolve([]) + : tx.user.findMany({ + where: { + role: 'ACCOUNT_MANAGER', + ...(user.role === 'ACCOUNT_MANAGER' ? { id: user.id } : {}), + }, + select: { id: true, name: true }, + orderBy: { name: 'asc' }, + }), + tx.task.findMany({ + where: { AND: [taskScope(user), { status: 'OPEN' }] }, + select: { assigneeId: true, dueAt: true }, + }), + user.role === 'COMPLIANCE_OFFICER' + ? tx.complianceReview.findMany({ + where: reviewWhere(user, {}), + select: { + id: true, + cycle: true, + submittedAt: true, + merchant: { select: { id: true, name: true } }, + }, + orderBy: [{ submittedAt: 'asc' }, { id: 'asc' }], + take: 5, + }) + : Promise.resolve([]), + user.role === 'COMPLIANCE_OFFICER' + ? tx.complianceReview.groupBy({ + by: ['decision'], + where: reviewWhere(user, { + view: 'DECISIONS', + decidedFrom: periodStart.toISOString(), + decidedTo: now.toISOString(), + }), + _count: { _all: true }, + }) + : Promise.resolve([]), + ]); + const decisionCounts = (['APPROVED', 'CORRECTIONS', 'REJECTED'] as const).map((decision) => ({ + decision, + count: decisions.find((d) => d.decision === decision)?._count._all ?? 0, + })); + return { + asOf: now, + periodStart, + merchantCount: merchants.length, + newLeads, + activeOnboarding, + liveMerchants, + unassignedLeads, + activation: { + numerator: liveMerchants, + denominator: merchants.length, + rate: merchants.length ? liveMerchants / merchants.length : null, + }, + onboardingDuration: { + averageDays: durations.length + ? durations.reduce((a, b) => a + b, 0) / durations.length + : null, + sampleCount: durations.length, + }, + workload: managers.map((manager) => ({ + ...manager, + merchants: merchants.filter((m) => m.ownerId === manager.id).length, + activeOnboarding: merchants.filter( + (m) => m.ownerId === manager.id && activeOnboardingStages.some((s) => s === m.status), + ).length, + openTasks: tasks.filter((t) => t.assigneeId === manager.id).length, + overdueTasks: tasks.filter((t) => t.assigneeId === manager.id && t.dueAt < now).length, + })), + oldestReviews, + decisions: decisionCounts, + decisionsLast30Days: decisionCounts.reduce((sum, d) => sum + d.count, 0), + reviewCount, + overdueTasks, + transitionsLast30Days, + distribution, + recentEvents, + upcomingTasks: upcomingTasks.map((task) => taskDto(task, user)), + recentActivities, + }; + }, + { isolationLevel: 'RepeatableRead' }, + ); +} diff --git a/apps/api/src/merchant-query.ts b/apps/api/src/merchant-query.ts new file mode 100644 index 0000000..5920f20 --- /dev/null +++ b/apps/api/src/merchant-query.ts @@ -0,0 +1,37 @@ +import { activeOnboardingStages, merchantQuerySchema, type User } from '@merchantflow/contracts'; +import type { Prisma } from '@merchantflow/database'; +import { merchantScope } from './access.js'; +import { ApiError } from './shared.js'; +export function merchantWhere(user: User, input: unknown): Prisma.MerchantWhereInput { + const { search, status, country, industry, ownerId, createdFrom, createdTo, cohort } = + merchantQuerySchema.parse(input); + if (ownerId && user.role === 'ACCOUNT_MANAGER') throw new ApiError('FORBIDDEN', 403); + return { + AND: [ + merchantScope(user), + { + ...(status ? { status } : {}), + ...(country ? { country } : {}), + ...(industry ? { industry } : {}), + ...(ownerId ? { ownerId: ownerId === 'unassigned' ? null : ownerId } : {}), + ...(createdFrom || createdTo + ? { + createdAt: { + ...(createdFrom ? { gte: new Date(createdFrom) } : {}), + ...(createdTo ? { lte: new Date(createdTo) } : {}), + }, + } + : {}), + ...(cohort === 'REACHED_LIVE' ? { events: { some: { toStatus: 'LIVE' } } } : {}), + ...(search + ? { + OR: ['name', 'contactEmail', 'legalName', 'contactName', 'website'].map((field) => ({ + [field]: { contains: search, mode: 'insensitive' }, + })), + } + : {}), + }, + ...(cohort === 'ACTIVE_ONBOARDING' ? [{ status: { in: [...activeOnboardingStages] } }] : []), + ], + }; +} diff --git a/apps/api/src/reminders.ts b/apps/api/src/reminders.ts new file mode 100644 index 0000000..97be320 --- /dev/null +++ b/apps/api/src/reminders.ts @@ -0,0 +1,61 @@ +import { Body, Controller, Get, Inject, Param, Post, Req, UseGuards } from '@nestjs/common'; +import { PrismaClient } from '@merchantflow/database'; +import { reminderDismissalSchema } from '@merchantflow/contracts'; +import { SessionGuard } from './auth.js'; +import { taskScope } from './access.js'; +import { taskDto, taskSelect } from './task-policy.js'; +import { ApiError, DATABASE, type AuthRequest } from './shared.js'; +@UseGuards(SessionGuard) +@Controller() +export class ReminderController { + constructor(@Inject(DATABASE) private readonly db: PrismaClient) {} + @Get('reminders') async inbox(@Req() req: AuthRequest) { + const rows = await this.db.task.findMany({ + where: { + AND: [ + taskScope(req.user), + { + assigneeId: req.user.id, + status: 'OPEN', + remindAt: { lte: new Date() }, + reminderDismissedAt: null, + }, + ], + }, + select: taskSelect, + orderBy: [{ remindAt: 'asc' }, { id: 'asc' }], + }); + return rows.map((task) => taskDto(task, req.user)); + } + @Post('tasks/:id/reminder-dismissal') async dismiss( + @Req() req: AuthRequest, + @Param('id') id: string, + @Body() body: unknown, + ) { + const { reminderRevision } = reminderDismissalSchema.parse(body); + return this.db.$transaction(async (tx) => { + const scope = { AND: [taskScope(req.user), { id, assigneeId: req.user.id }] }; + const updated = await tx.task.updateMany({ + where: { + AND: [ + scope, + { + reminderRevision, + status: 'OPEN', + remindAt: { lte: new Date() }, + reminderDismissedAt: null, + }, + ], + }, + data: { reminderDismissedAt: new Date() }, + }); + if (!updated.count) { + const task = await tx.task.findFirst({ where: scope }); + if (!task) throw new ApiError('NOT_FOUND', 404); + if (task.reminderRevision !== reminderRevision || !task.reminderDismissedAt) + throw new ApiError('CONFLICT', 409); + } + return { ok: true }; + }); + } +} diff --git a/apps/api/src/review-query.ts b/apps/api/src/review-query.ts new file mode 100644 index 0000000..d66d792 --- /dev/null +++ b/apps/api/src/review-query.ts @@ -0,0 +1,42 @@ +import type { Prisma } from '@merchantflow/database'; +import { reviewQueueQuerySchema, type User } from '@merchantflow/contracts'; +import { merchantScope } from './access.js'; +import { pendingReviews } from './task-policy.js'; +export function reviewWhere( + user: User, + input: unknown, + now = new Date(), +): Prisma.ComplianceReviewWhereInput { + const { search, ownerId, waiting, view, decision, decidedFrom, decidedTo } = + reviewQueueQuerySchema.parse(input); + return { + AND: [ + view === 'PENDING' + ? pendingReviews(user) + : { + merchant: merchantScope(user), + decision: decision ?? { not: 'PENDING' }, + decidedAt: { + not: null, + ...(decidedFrom ? { gte: new Date(decidedFrom) } : {}), + ...(decidedTo ? { lte: new Date(decidedTo) } : {}), + }, + }, + { + ...(view === 'PENDING' && waiting !== 'ALL' + ? { submittedAt: { lte: new Date(now.getTime() - Number(waiting) * 3600000) } } + : {}), + merchant: { + ...(ownerId ? { ownerId: ownerId === 'unassigned' ? null : ownerId } : {}), + ...(search + ? { + OR: ['name', 'legalName', 'contactName', 'contactEmail', 'website'].map( + (field) => ({ [field]: { contains: search, mode: 'insensitive' } }), + ), + } + : {}), + }, + }, + ], + }; +} diff --git a/apps/api/src/task-policy.ts b/apps/api/src/task-policy.ts new file mode 100644 index 0000000..2f6fce0 --- /dev/null +++ b/apps/api/src/task-policy.ts @@ -0,0 +1,94 @@ +import type { Prisma } from '@merchantflow/database'; +import type { User } from '@merchantflow/contracts'; +import { taskQuerySchema } from '@merchantflow/contracts'; +import { taskScope } from './access.js'; +import { ApiError } from './shared.js'; + +export const taskSelect = { + id: true, + title: true, + status: true, + kind: true, + createdAt: true, + updatedAt: true, + dueAt: true, + remindAt: true, + reminderRevision: true, + completedAt: true, + merchant: { select: { id: true, name: true, version: true } }, + assignee: { select: { id: true, name: true } }, + creator: { select: { name: true } }, + completedBy: { select: { name: true } }, +} as const; +type TaskRow = Prisma.TaskGetPayload<{ select: typeof taskSelect }>; +export function taskDto(task: TaskRow, user: User) { + const own = user.role !== 'ACCOUNT_MANAGER' || task.assignee.id === user.id; + return { + ...task, + capabilities: { + edit: own, + complete: own && task.status === 'OPEN', + reopen: task.status === 'DONE', + }, + }; +} + +// Find real local midnight, including 23/25-hour days and zones with midnight transitions. +export function localDayBounds(now: Date, timeZone: string) { + const format = new Intl.DateTimeFormat('en-CA', { + timeZone, + year: 'numeric', + month: '2-digit', + day: '2-digit', + }); + const key = (ms: number) => { + const parts = format.formatToParts(ms); + return ['year', 'month', 'day'] + .map((type) => parts.find((p) => p.type === type)!.value) + .join('-'); + }; + const today = key(now.getTime()); + const nominal = Date.parse(`${today}T00:00:00Z`); + const boundary = (target: string, center: number) => { + let lo = center - 36 * 3600000, + hi = center + 36 * 3600000; + while (lo < hi) { + const mid = Math.floor((lo + hi) / 2); + if (key(mid) < target) lo = mid + 1; + else hi = mid; + } + return new Date(lo); + }; + return { + start: boundary(today, nominal), + end: boundary(new Date(nominal + 86400000).toISOString().slice(0, 10), nominal + 86400000), + }; +} +export function taskWhere(user: User, input: unknown, now = new Date()): Prisma.TaskWhereInput { + const { filter, merchantId, assigneeId, timeZone } = taskQuerySchema.parse(input); + if (assigneeId && user.role !== 'HEAD_OF_SALES' && assigneeId !== user.id) + throw new ApiError('FORBIDDEN', 403); + const bounds = filter === 'TODAY' || filter === 'UPCOMING' ? localDayBounds(now, timeZone) : null; + return { + AND: [ + taskScope(user), + { + ...(merchantId ? { merchantId } : {}), + ...(assigneeId ? { assigneeId } : {}), + ...(filter === 'DONE' ? { status: 'DONE' } : filter !== 'ALL' ? { status: 'OPEN' } : {}), + ...(filter === 'OVERDUE' ? { dueAt: { lt: now } } : {}), + ...(filter === 'TODAY' ? { dueAt: { gte: bounds!.start, lt: bounds!.end } } : {}), + ...(filter === 'UPCOMING' ? { dueAt: { gte: bounds!.end } } : {}), + }, + ], + }; +} +export function pendingReviews(user: User): Prisma.ComplianceReviewWhereInput { + return { + decision: 'PENDING', + merchant: { + ...(user.role === 'ACCOUNT_MANAGER' ? { ownerId: user.id } : {}), + status: 'COMPLIANCE_REVIEW', + }, + }; +} diff --git a/apps/api/src/workflow.ts b/apps/api/src/workflow.ts index 5494e38..cc34545 100644 --- a/apps/api/src/workflow.ts +++ b/apps/api/src/workflow.ts @@ -206,7 +206,11 @@ export class WorkflowController { await tx.merchant.updateMany({ where: { id }, data: { ownerId } }); await tx.task.updateMany({ where: { merchantId: id, kind: 'COMMERCIAL', status: 'OPEN' }, - data: { assigneeId: ownerId }, + data: { + assigneeId: ownerId, + reminderDismissedAt: null, + reminderRevision: { increment: 1 }, + }, }); await this.audit(tx, req, id, 'Manager assignment updated', { previousOwnerId: merchant.ownerId, @@ -498,6 +502,24 @@ export class WorkflowController { : null; if (taskId && !existing) throw new ApiError('NOT_FOUND', 404); if (existing && existing.kind !== kind) throw new ApiError('FORBIDDEN', 403); + if ( + existing && + req.user.role === 'ACCOUNT_MANAGER' && + existing.assigneeId !== req.user.id && + !(existing.status === 'DONE' && status === 'OPEN') + ) + throw new ApiError('FORBIDDEN', 403); + const assigneeId = + kind === 'COMPLIANCE' + ? req.user.id + : status === 'DONE' && existing + ? existing.assigneeId + : (merchant.ownerId ?? existing?.assigneeId ?? req.user.id); + const reminderChanged = + existing && + (existing.assigneeId !== assigneeId || + (existing.remindAt?.getTime() ?? null) !== + (remindAt ? new Date(remindAt).getTime() : null)); const completion = status === 'DONE' ? { @@ -506,6 +528,10 @@ export class WorkflowController { } : { completedAt: null, completedById: null }; const data = { + assigneeId, + ...(reminderChanged + ? { reminderDismissedAt: null, reminderRevision: { increment: 1 } } + : {}), title, dueAt: new Date(dueAt), remindAt: remindAt ? new Date(remindAt) : null, @@ -517,18 +543,27 @@ export class WorkflowController { where: { AND: [taskScope(req.user), { id: existing.id, merchantId: id }] }, data, }); - else - await tx.task.create({ + else { + const created = await tx.task.create({ data: { ...data, + reminderRevision: 0, kind, creatorId: req.user.id, merchantId: id, - assigneeId: kind === 'COMPLIANCE' ? req.user.id : (merchant.ownerId ?? req.user.id), + assigneeId, }, }); + taskId = created.id; + } await this.audit(tx, req, id, existing ? 'Task updated' : 'Task created', { - taskId: taskId ?? null, + taskId: taskId!, + taskKind: kind, + assigneeId, + previousStatus: existing?.status ?? null, + previousAssigneeId: existing?.assigneeId ?? null, + previousCompletedAt: existing?.completedAt?.toISOString() ?? null, + previousCompletedById: existing?.completedById ?? null, title, status, }); diff --git a/apps/api/test/integration.test.mjs b/apps/api/test/integration.test.mjs index b61126b..6c41205 100644 --- a/apps/api/test/integration.test.mjs +++ b/apps/api/test/integration.test.mjs @@ -125,7 +125,7 @@ for (const [account, total] of [ merchantId: { in: ids }, ...(account === 'compliance' ? { kind: 'COMPLIANCE', assigneeId: 'user-compliance' } - : {}), + : { kind: 'COMMERCIAL' }), }, }), ); @@ -151,7 +151,7 @@ for (const [account, total] of [ merchantId: { in: ids }, ...(account === 'compliance' ? { kind: 'COMPLIANCE', assigneeId: 'user-compliance' } - : {}), + : { kind: 'COMMERCIAL' }), status: 'OPEN', dueAt: { lt: new Date() }, }, @@ -775,7 +775,7 @@ test('reassignment transfers open commercial tasks; concurrent writes and former ); const before = await get(); assert.equal((await get(comp)).tasks.length, 1); - const personal = before.tasks.find((t) => t.kind === 'COMPLIANCE'); + const personal = (await get(comp)).tasks.find((t) => t.kind === 'COMPLIANCE'); assert.equal( ( await mutate(`/merchants/${id}/tasks/${personal.id}`, head, { @@ -783,7 +783,7 @@ test('reassignment transfers open commercial tasks; concurrent writes and former version: before.version, }) ).status, - 403, + 404, ); const commercial = before.tasks.find((t) => t.kind === 'COMMERCIAL'); assert.equal( @@ -828,7 +828,10 @@ test('reassignment transfers open commercial tasks; concurrent writes and former .filter((t) => t.status === 'DONE') .every((t) => t.assignee.id === 'user-manager1'), ); - assert.equal(after.tasks.find((t) => t.kind === 'COMPLIANCE').assignee.id, 'user-compliance'); + assert.equal( + (await get(comp)).tasks.find((t) => t.kind === 'COMPLIANCE').assignee.id, + 'user-compliance', + ); assert.equal((await request(`/merchants/${id}`, alex)).status, 404); assert.equal( ( diff --git a/apps/api/test/tasks-dashboards.test.mjs b/apps/api/test/tasks-dashboards.test.mjs new file mode 100644 index 0000000..031f51d --- /dev/null +++ b/apps/api/test/tasks-dashboards.test.mjs @@ -0,0 +1,441 @@ +import { before, after, test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createDatabase } from '@merchantflow/database'; +import { dashboardSchema, taskListSchema } from '@merchantflow/contracts'; +if (!process.env.DATABASE_URL?.endsWith('/merchantflow_test')) + throw new Error('Isolated test database required'); +const db = createDatabase(process.env.DATABASE_URL); +let app, base; +const cookies = {}; +async function start() { + const { createApp } = await import('../dist/app.js'); + app = await createApp(); + await app.listen(0, '127.0.0.1'); + base = (await app.getUrl()) + '/api'; +} +async function request(path, account = 'head', body, method = body ? 'POST' : 'GET') { + const response = await fetch(base + path, { + method, + headers: { + origin: process.env.APP_ORIGIN ?? 'http://localhost:5173', + ...(cookies[account] ? { cookie: cookies[account] } : {}), + ...(body ? { 'content-type': 'application/json' } : {}), + }, + ...(body ? { body: JSON.stringify(body) } : {}), + }); + return { status: response.status, body: await response.json(), headers: response.headers }; +} +async function login(account) { + const r = await request('/auth/login', account, { + email: `${account}@merchantflow.test`, + password: 'MerchantFlow123!', + }); + assert.equal(r.status, 201); + cookies[account] = r.headers.get('set-cookie').split(';')[0]; +} +before(async () => { + await start(); + for (const a of ['head', 'alex', 'sam', 'compliance']) await login(a); +}); +after(async () => { + await db.merchant.deleteMany({ where: { id: { startsWith: 'tasks-check-' } } }); + await db.user.deleteMany({ where: { id: 'tasks-empty-manager' } }); + await app?.close(); + await db.$disconnect(); +}); +async function fixture(id, ownerId = 'user-manager1') { + return db.merchant.create({ + data: { + id, + name: id, + contactName: 'Test', + contactEmail: 'test@example.test', + ownerId, + createdAt: new Date(), + status: 'NEW_LEAD', + }, + }); +} +async function detail(id, account = 'head') { + const r = await request(`/merchants/${id}`, account); + assert.equal(r.status, 200); + return r.body; +} +async function save(id, account, fields, taskId) { + const m = await detail(id, account); + return request( + `/merchants/${id}/tasks${taskId ? '/' + taskId : ''}`, + account, + { version: m.version, ...fields }, + taskId ? 'PATCH' : 'POST', + ); +} +const input = (overrides = {}) => ({ + title: 'Actionable task', + dueAt: new Date(Date.now() + 86400000).toISOString(), + remindAt: new Date(Date.now() - 1000).toISOString(), + status: 'OPEN', + ...overrides, +}); + +test('seed dashboards and drilldowns match independent scoped records and earliest Live events', async () => { + const rows = await db.merchant.findMany({ + include: { events: true, tasks: true, reviews: true }, + }); + assert.equal(rows.length, 45); + for (const [account, owner] of [ + ['head', null], + ['alex', 'user-manager1'], + ['sam', 'user-manager2'], + ['compliance', null], + ]) { + const response = await request('/dashboard', account); + assert.equal(response.status, 200); + const d = dashboardSchema.parse(response.body); + const visible = rows.filter((m) => !owner || m.ownerId === owner); + const asOf = new Date(d.asOf), + start = new Date(d.periodStart); + const live = visible.filter((m) => m.status === 'LIVE').length; + const durations = visible.flatMap((m) => { + const first = m.events + .filter((e) => e.toStatus === 'LIVE') + .sort((a, b) => a.occurredAt - b.occurredAt)[0]; + return first ? [(first.occurredAt - m.createdAt) / 86400000] : []; + }); + assert.equal(d.merchantCount, visible.length); + assert.equal(d.liveMerchants, live); + assert.equal(d.activation.rate, live / visible.length); + assert.equal(d.onboardingDuration.sampleCount, durations.length); + assert.equal( + d.onboardingDuration.averageDays, + durations.reduce((a, b) => a + b, 0) / durations.length, + ); + assert.equal( + d.newLeads, + visible.filter((m) => m.createdAt >= start && m.createdAt <= asOf).length, + ); + assert.equal( + d.activeOnboarding, + visible.filter((m) => + ['KYB', 'COMPLIANCE_REVIEW', 'INTEGRATION', 'TESTING'].includes(m.status), + ).length, + ); + for (const row of d.distribution) + assert.equal(row.count, visible.filter((m) => m.status === row.status).length); + assert.equal( + d.distribution.reduce((n, s) => n + s.count, 0), + visible.length, + ); + const tasks = visible + .flatMap((m) => m.tasks) + .filter((t) => + account === 'compliance' + ? t.kind === 'COMPLIANCE' && t.assigneeId === 'user-compliance' + : t.kind === 'COMMERCIAL', + ); + assert.equal(d.overdueTasks, tasks.filter((t) => t.status === 'OPEN' && t.dueAt < asOf).length); + assert.equal( + ( + await request( + `/merchants?${new URLSearchParams({ createdFrom: d.periodStart, createdTo: d.asOf })}`, + account, + ) + ).body.total, + d.newLeads, + ); + assert.equal( + (await request('/merchants?cohort=ACTIVE_ONBOARDING', account)).body.total, + d.activeOnboarding, + ); + assert.equal( + (await request('/merchants?cohort=REACHED_LIVE', account)).body.total, + d.onboardingDuration.sampleCount, + ); + if (owner) + assert.deepEqual( + d.workload.map((w) => w.id), + [owner], + ); + for (const w of d.workload) { + assert.equal(w.merchants, visible.filter((m) => m.ownerId === w.id).length); + assert.equal( + w.openTasks, + tasks.filter((t) => t.assigneeId === w.id && t.status === 'OPEN').length, + ); + } + if (account === 'compliance') { + const expected = visible + .flatMap((m) => m.reviews) + .filter((r) => r.decision !== 'PENDING' && r.decidedAt >= start && r.decidedAt <= asOf); + assert.equal(d.decisionsLast30Days, expected.length); + const history = await request( + `/review-queue?${new URLSearchParams({ view: 'DECISIONS', decidedFrom: d.periodStart, decidedTo: d.asOf })}`, + account, + ); + assert.equal(history.body.filteredCount, expected.length); + assert.deepEqual( + d.oldestReviews.map((r) => r.id), + visible + .flatMap((m) => + m.status === 'COMPLIANCE_REVIEW' + ? m.reviews.filter((r) => r.decision === 'PENDING') + : [], + ) + .sort((a, b) => a.submittedAt - b.submittedAt || a.id.localeCompare(b.id)) + .slice(0, 5) + .map((r) => r.id), + ); + } + } +}); + +test('task endpoints enforce manager isolation and private Compliance tasks', async () => { + for (const [account, other, ownId, hiddenId] of [ + ['alex', 'sam', 'merchant-01', 'merchant-02'], + ['sam', 'alex', 'merchant-02', 'merchant-01'], + ]) { + const hidden = await detail(hiddenId, other); + const task = hidden.tasks[0]; + assert.equal((await request(`/merchants/${hiddenId}`, account)).status, 404); + assert.deepEqual((await request(`/tasks?merchantId=${hiddenId}`, account)).body, []); + assert.equal( + ( + await request(`/merchants/${hiddenId}/tasks`, account, { + version: hidden.version, + ...input(), + }) + ).status, + 404, + ); + assert.equal( + ( + await request( + `/merchants/${ownId}/tasks/${task.id}`, + account, + { version: (await detail(ownId, account)).version, ...input() }, + 'PATCH', + ) + ).status, + 404, + ); + assert.equal( + (await request(`/tasks/${task.id}/reminder-dismissal`, account, { reminderRevision: 0 })) + .status, + 404, + ); + assert.equal((await request(`/tasks?assigneeId=${task.assignee.id}`, account)).status, 403); + const list = taskListSchema.parse((await request('/tasks', account)).body); + assert.ok(list.every((t) => t.kind === 'COMMERCIAL')); + assert.equal( + (await request(`/merchants?search=${encodeURIComponent(hidden.name)}`, account)).body.total, + 0, + ); + } + const id = 'tasks-check-private'; + await fixture(id); + assert.equal((await save(id, 'compliance', input())).status, 201); + const privateTask = (await detail(id, 'compliance')).tasks[0]; + for (const account of ['head', 'alex']) { + assert.equal((await detail(id, account)).tasks.length, 0); + assert.ok(!(await detail(id, account)).history.some((entry) => entry.text === 'Task created')); + assert.equal((await save(id, account, input(), privateTask.id)).status, 404); + assert.ok(!(await request('/reminders', account)).body.some((t) => t.id === privateTask.id)); + } + assert.equal((await request('/reminders', 'anonymous')).status, 401); + assert.equal( + (await request(`/tasks/${privateTask.id}/reminder-dismissal`, 'head', { reminderRevision: 0 })) + .status, + 404, + ); + await db.merchant.delete({ where: { id } }); +}); + +test('reminder timing, dismissal, completion, rescheduling and API restart persist correctly', async (t) => { + const id = 'tasks-check-reminders'; + await fixture(id); + const now = Date.now(); + t.mock.timers.enable({ apis: ['Date'], now }); + const fields = input({ + dueAt: new Date(now + 3600000).toISOString(), + remindAt: new Date(now + 1000).toISOString(), + }); + assert.equal((await save(id, 'alex', fields)).status, 201); + let task = (await detail(id, 'alex')).tasks[0]; + const inbox = async () => + (await request('/reminders', 'alex')).body.filter((x) => x.id === task.id); + assert.equal((await inbox()).length, 0); + t.mock.timers.setTime(now + 1000); + assert.equal((await inbox()).length, 1); + t.mock.timers.setTime(now + 1001); + assert.equal((await inbox()).length, 1); + assert.equal( + ( + await request(`/tasks/${task.id}/reminder-dismissal`, 'alex', { + reminderRevision: task.reminderRevision, + }) + ).status, + 201, + ); + assert.equal( + ( + await request(`/tasks/${task.id}/reminder-dismissal`, 'alex', { + reminderRevision: task.reminderRevision, + }) + ).status, + 201, + ); + assert.equal((await inbox()).length, 0); + await app.close(); + await start(); + assert.equal((await inbox()).length, 0); + assert.equal((await save(id, 'alex', { ...fields, status: 'DONE' }, task.id)).status, 200); + assert.equal((await save(id, 'alex', fields, task.id)).status, 200); + assert.equal((await inbox()).length, 0); + const changed = { ...fields, remindAt: new Date(now).toISOString() }; + assert.equal((await save(id, 'alex', changed, task.id)).status, 200); + assert.equal((await inbox()).length, 1); + assert.equal( + ( + await request(`/tasks/${task.id}/reminder-dismissal`, 'alex', { + reminderRevision: task.reminderRevision, + }) + ).status, + 409, + ); + assert.equal((await save(id, 'alex', { ...changed, status: 'DONE' }, task.id)).status, 200); + assert.equal((await inbox()).length, 0); + assert.equal((await save(id, 'alex', changed, task.id)).status, 200); + assert.equal((await inbox()).length, 1); + const reopened = await db.task.findUniqueOrThrow({ where: { id: task.id } }); + assert.equal(reopened.completedAt, null); + assert.equal(reopened.completedById, null); + assert.equal((await save(id, 'alex', { ...changed, remindAt: null }, task.id)).status, 200); + assert.equal((await inbox()).length, 0); + t.mock.timers.reset(); + await db.merchant.delete({ where: { id } }); +}); + +test('reassignment transfers only open sales tasks and reopening preserves prior completion in audit', async () => { + const id = 'tasks-check-handoff'; + await fixture(id); + const fields = input(); + for (const [account, status] of [ + ['alex', 'OPEN'], + ['alex', 'DONE'], + ['compliance', 'OPEN'], + ]) + assert.equal((await save(id, account, { ...fields, status })).status, 201); + const before = await detail(id); + const open = before.tasks.find((t) => t.status === 'OPEN'), + done = before.tasks.find((t) => t.status === 'DONE'); + await request(`/tasks/${open.id}/reminder-dismissal`, 'alex', { reminderRevision: 0 }); + const results = await Promise.all([ + request( + `/merchants/${id}/assignment`, + 'head', + { version: before.version, ownerId: 'user-manager2' }, + 'PATCH', + ), + request( + `/merchants/${id}/tasks/${open.id}`, + 'alex', + { version: before.version, ...fields, title: 'Racing edit' }, + 'PATCH', + ), + ]); + assert.equal(results.filter((r) => r.status === 200).length, 1); + if (results[0].status !== 200) + assert.equal( + ( + await request( + `/merchants/${id}/assignment`, + 'head', + { version: (await detail(id)).version, ownerId: 'user-manager2' }, + 'PATCH', + ) + ).status, + 200, + ); + assert.equal((await request(`/merchants/${id}`, 'alex')).status, 404); + assert.equal( + (await request(`/tasks/${open.id}/reminder-dismissal`, 'alex', { reminderRevision: 0 })).status, + 404, + ); + let after = await detail(id, 'sam'); + assert.equal(after.tasks.find((t) => t.id === open.id).assignee.id, 'user-manager2'); + assert.equal(after.tasks.find((t) => t.id === done.id).assignee.id, 'user-manager1'); + assert.equal((await detail(id, 'compliance')).tasks[0].assignee.id, 'user-compliance'); + assert.ok((await request('/reminders', 'sam')).body.some((t) => t.id === open.id)); + assert.equal((await save(id, 'sam', { ...fields, status: 'DONE' }, done.id)).status, 403); + assert.equal((await save(id, 'sam', fields, done.id)).status, 200); + after = await detail(id, 'sam'); + assert.equal(after.tasks.find((t) => t.id === done.id).assignee.id, 'user-manager2'); + const audit = await db.activity.findMany({ where: { merchantId: id, kind: 'AUDIT' } }); + assert.ok( + audit.some( + (a) => + a.metadata?.taskId === done.id && + a.metadata.previousCompletedById === 'user-manager1' && + a.metadata.previousCompletedAt, + ), + ); + await db.merchant.delete({ where: { id } }); +}); + +test('empty portfolios, zero-history metrics, first-Live deduplication and date bounds are honest', async () => { + const original = await db.user.findUniqueOrThrow({ where: { id: 'user-manager1' } }); + await db.user.create({ + data: { + id: 'tasks-empty-manager', + name: 'Empty manager', + email: 'empty@merchantflow.test', + passwordHash: original.passwordHash, + role: 'ACCOUNT_MANAGER', + }, + }); + await login('empty'); + let d = (await request('/dashboard', 'empty')).body; + assert.equal(d.merchantCount, 0); + assert.equal(d.activation.rate, null); + assert.equal(d.onboardingDuration.averageDays, null); + assert.equal(d.onboardingDuration.sampleCount, 0); + const now = new Date(), + start = new Date(now - 30 * 86400000); + const id = 'tasks-check-metrics'; + await fixture(id, 'tasks-empty-manager'); + await db.merchant.update({ where: { id }, data: { createdAt: start, status: 'LIVE' } }); + d = (await request('/dashboard', 'empty')).body; + assert.equal(d.activation.rate, 1); + assert.equal(d.onboardingDuration.averageDays, null); + for (const days of [5, 8]) + await db.statusEvent.create({ + data: { + merchantId: id, + toStatus: 'LIVE', + occurredAt: new Date(start.getTime() + days * 86400000), + }, + }); + d = (await request('/dashboard', 'empty')).body; + assert.equal(d.onboardingDuration.sampleCount, 1); + assert.equal(d.onboardingDuration.averageDays, 5); + assert.equal( + ( + await request( + `/merchants?${new URLSearchParams({ createdFrom: start.toISOString(), createdTo: start.toISOString() })}`, + 'empty', + ) + ).body.total, + 1, + ); + assert.equal( + ( + await request( + `/merchants?${new URLSearchParams({ createdFrom: new Date(start.getTime() + 1).toISOString() })}`, + 'empty', + ) + ).body.total, + 0, + ); + await db.merchant.delete({ where: { id } }); + await db.user.delete({ where: { id: 'tasks-empty-manager' } }); +}); diff --git a/apps/api/test/unit.test.mjs b/apps/api/test/unit.test.mjs index d4dec7e..adbae63 100644 --- a/apps/api/test/unit.test.mjs +++ b/apps/api/test/unit.test.mjs @@ -34,3 +34,27 @@ test('every role receives its exact merchant scope', () => { assert.deepEqual(merchantScope({ role: 'COMPLIANCE_OFFICER' }), {}); assert.deepEqual(merchantScope({ role: 'unexpected' }), { id: '__no_access__' }); }); + +test('task day boundaries use the viewer time zone through DST and include exact due instants', async () => { + const { localDayBounds, taskWhere } = await import('../dist/task-policy.js'); + for (const [date, hours] of [ + ['2026-03-08T12:00:00Z', 23], + ['2026-11-01T12:00:00Z', 25], + ]) { + const { start, end } = localDayBounds(new Date(date), 'America/New_York'); + assert.equal((end - start) / 3600000, hours); + } + const now = new Date('2026-09-24T22:00:00Z'); + const { start, end } = localDayBounds(now, 'Europe/Kyiv'); + assert.equal(start.toISOString(), '2026-09-24T21:00:00.000Z'); + assert.equal(end.toISOString(), '2026-09-25T21:00:00.000Z'); + const user = { id: 'manager', role: 'ACCOUNT_MANAGER' }; + assert.deepEqual( + taskWhere(user, { filter: 'TODAY', timeZone: 'Europe/Kyiv' }, now).AND[1].dueAt, + { gte: start, lt: end }, + ); + assert.deepEqual( + taskWhere(user, { filter: 'UPCOMING', timeZone: 'Europe/Kyiv' }, now).AND[1].dueAt, + { gte: end }, + ); +}); diff --git a/apps/web/src/components/dashboard.tsx b/apps/web/src/components/dashboard.tsx new file mode 100644 index 0000000..368a03b --- /dev/null +++ b/apps/web/src/components/dashboard.tsx @@ -0,0 +1,342 @@ +import { useOutletContext, Link } from 'react-router'; +import { useQuery } from '@tanstack/react-query'; +import { useTranslation } from 'react-i18next'; +import { dashboardSchema, type User } from '@merchantflow/contracts'; +import { z } from 'zod'; +import { api } from '../lib/api'; +import { useFormat } from '../lib/format'; +import { useLiveRefresh } from '../lib/live-refresh'; +import { + EmptyState, + LinkButton, + PageHeader, + QueryBoundary, + SectionHeader, + stageColors, +} from './shared'; +import { ActionableTask } from './tasks'; +import { StageAge } from './sales-workspace'; +import { RecentInteractions } from './merchant-workflow'; +type Data = z.infer; +function Metric({ + title, + value, + hint, + to, +}: { + title: string; + value: string | number; + hint?: string; + to: string; +}) { + return ( + +

{title}

+

{value}

+ {hint &&

{hint}

} + + ); +} +function BusinessMetrics({ data }: { data: Data }) { + const { t } = useTranslation(); + const f = useFormat(); + return ( +
+ + +
+ ); +} +function Priorities({ data, compliance = false }: { data: Data; compliance?: boolean }) { + const { t } = useTranslation(); + return ( +
+ + {t('common.viewAll')} + + } + /> + {data.upcomingTasks.length ? ( + data.upcomingTasks.map((task) => ) + ) : ( + + )} +
+ ); +} +function SalesDashboard({ data, user }: { data: Data; user: User }) { + const { t } = useTranslation(); + const f = useFormat(); + const manager = user.role === 'ACCOUNT_MANAGER'; + const createdQuery = new URLSearchParams({ createdFrom: data.periodStart, createdTo: data.asOf }); + return ( +
+
+ + + + +
+
+ + {!manager && ( + + )} +
+ {manager && } + +
+ + {t('dashboard.openPipeline')} + + } + /> + {data.merchantCount ? ( +
+ + ) : ( + + )} +
+
+ +
+ {data.workload.map((row) => { + const owner = manager ? '' : `ownerId=${row.id}`; + return ( +
+

{row.name}

+
+ {[ + ['assigned', row.merchants, `/app/merchants?${owner}`], + [ + 'active', + row.activeOnboarding, + `/app/merchants?cohort=ACTIVE_ONBOARDING${owner ? '&' + owner : ''}`, + ], + ['openTasks', row.openTasks, `/app/tasks?filter=OPEN&assigneeId=${row.id}`], + ['overdue', row.overdueTasks, `/app/tasks?filter=OVERDUE&assigneeId=${row.id}`], + ].map(([label, value, to]) => ( +
+
{t(`operations.${label}`)}
+
+ + {f.number(Number(value))} + +
+
+ ))} +
+
+ ); + })} +
+
+ {!manager && } +
+ + {data.recentActivities.length ? ( + + ) : ( + + )} +
+
+ ); +} +function ComplianceDashboard({ data }: { data: Data }) { + const { t } = useTranslation(); + const f = useFormat(); + const history = `/app/review-queue?${new URLSearchParams({ view: 'DECISIONS', decidedFrom: data.periodStart, decidedTo: data.asOf })}`; + return ( +
+
+ + + +
+
+ + {t('common.viewAll')} + + } + /> + {data.oldestReviews.length ? ( +
+ {data.oldestReviews.map((review) => ( + + {review.merchant.name} + + · {f.dateTime(review.submittedAt)} + + + ))} +
+ ) : ( + + )} +
+
+ {data.decisions.map((d) => ( + + ))} +
+ + +
+ ); +} +export function Dashboard() { + const { t } = useTranslation(); + const user = useOutletContext(); + const query = useQuery({ + queryKey: ['dashboard'], + queryFn: ({ signal }) => api('/dashboard', dashboardSchema, { signal }), + }); + useLiveRefresh(query.refetch); + const role = + user.role === 'HEAD_OF_SALES' + ? 'head' + : user.role === 'ACCOUNT_MANAGER' + ? 'manager' + : 'compliance'; + return ( + <> + + {t(role === 'compliance' ? 'review.title' : 'dashboard.view')} + + } + /> + + {(data) => + role === 'compliance' ? ( + + ) : ( + + ) + } + + + ); +} diff --git a/apps/web/src/components/merchant-workflow.tsx b/apps/web/src/components/merchant-workflow.tsx index 6f4fb2e..e03b3d6 100644 --- a/apps/web/src/components/merchant-workflow.tsx +++ b/apps/web/src/components/merchant-workflow.tsx @@ -12,15 +12,13 @@ import { isRequiredDocument, sources, statuses, - taskInputSchema, type MerchantDetail, - type Task, } from '@merchantflow/contracts'; import { api } from '../lib/api'; import { Editor, useAction, type Field } from './workflow-form'; import { StageActions } from './sales-workspace'; import { useFormat } from '../lib/format'; -import { Button, SectionHeader, TaskRow } from './shared'; +import { Button, SectionHeader } from './shared'; const identityFields = [ 'name', @@ -431,111 +429,7 @@ export function InteractionHistory({ merchant: m }: { merchant: MerchantDetail } ); } -const localDate = (value: string) => { - const date = new Date(value); - return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16); -}; -const isoDate = (value: string) => { - const date = new Date(value); - return Number.isFinite(date.getTime()) ? date.toISOString() : ''; -}; -export function MerchantTasks({ merchant: m }: { merchant: MerchantDetail }) { - const { t } = useTranslation(); - const [edit, setEdit] = useState(null); - const action = useAction(m, () => setEdit(null)); - const existing = m.tasks.find((task) => task.id === edit); - const complete = (task: Task) => - action.mutate({ - path: `/tasks/${task.id}`, - body: { - version: m.version, - title: task.title, - dueAt: task.dueAt, - remindAt: task.remindAt, - status: 'DONE', - }, - }); - return ( -
- { - action.reset(); - setEdit('new'); - }} - > - {t('workflow.addTask')} - - } - /> -
{action.feedback}
- {m.tasks.map((task) => ( -
- - {task.kind === m.capabilities.manageTaskKind && ( -
- - {task.status === 'OPEN' && ( - - )} -
- )} -
- ))} - {edit && ( - ({ value, label: t(`tasks.${value}`) })), - }, - ]} - initial={{ - title: existing?.title ?? '', - dueAt: localDate(existing?.dueAt ?? new Date(Date.now() + 86400000).toISOString()), - remindAt: existing?.remindAt ? localDate(existing.remindAt) : '', - status: existing?.status ?? 'OPEN', - }} - schema={taskInputSchema} - build={(values) => ({ - ...values, - version: m.version, - dueAt: isoDate(values.dueAt!), - remindAt: values.remindAt ? isoDate(values.remindAt) : null, - })} - submit={(body) => - action.mutate({ - path: `/tasks${existing ? `/${existing.id}` : ''}`, - method: existing ? 'PATCH' : 'POST', - body, - }) - } - close={() => setEdit(null)} - pending={action.isPending} - feedback={action.feedback} - /> - )} -
- ); -} +export { MerchantTasks } from './tasks'; export function RecentInteractions({ activities }: { activities: MerchantDetail['activities'] }) { const { t } = useTranslation(); const f = useFormat(); diff --git a/apps/web/src/components/reminders.tsx b/apps/web/src/components/reminders.tsx new file mode 100644 index 0000000..44e833b --- /dev/null +++ b/apps/web/src/components/reminders.tsx @@ -0,0 +1,97 @@ +import { useState } from 'react'; +import { useMutation, useQuery } from '@tanstack/react-query'; +import { useTranslation } from 'react-i18next'; +import { Bell } from 'lucide-react'; +import { mutationResultSchema, taskListSchema, type Task } from '@merchantflow/contracts'; +import { + Sheet, + SheetContent, + SheetTitle, + SheetDescription, +} from '@merchantflow/ui/components/sheet'; +import { api, queryClient } from '../lib/api'; +import { useLiveRefresh } from '../lib/live-refresh'; +import { Button, EmptyState, QueryBoundary, TaskRow } from './shared'; +export function ReminderInbox() { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + const query = useQuery({ + queryKey: ['reminders'], + queryFn: ({ signal }) => api('/reminders', taskListSchema, { signal }), + staleTime: 0, + refetchOnMount: 'always', + refetchOnWindowFocus: 'always', + refetchOnReconnect: 'always', + }); + useLiveRefresh(query.refetch); + const dismissal = useMutation({ + mutationFn: (task: Task) => + api(`/tasks/${task.id}/reminder-dismissal`, mutationResultSchema, { + method: 'POST', + body: JSON.stringify({ reminderRevision: task.reminderRevision }), + }), + onSettled: () => queryClient.invalidateQueries({ queryKey: ['reminders'] }), + }); + const count = query.data?.length; + return ( + <> + + + + {t('operations.reminders')} + {t('operations.inboxDescription')} + {dismissal.isError && ( +

+ {t('operations.remindersError')} +

+ )} + + {(tasks) => + tasks.length ? ( +
+ {tasks.map((task) => ( +
+ setOpen(false)} /> + +
+ ))} +
+ ) : ( + + ) + } +
+
+
+ + ); +} diff --git a/apps/web/src/components/shared.tsx b/apps/web/src/components/shared.tsx index 3455277..e3fb9ec 100644 --- a/apps/web/src/components/shared.tsx +++ b/apps/web/src/components/shared.tsx @@ -248,7 +248,15 @@ export function MerchantCard({ merchant, className }: { merchant: Merchant; clas ); } -export function TaskRow({ task, compact = false }: { task: Task; compact?: boolean }) { +export function TaskRow({ + task, + compact = false, + onNavigate, +}: { + task: Task; + compact?: boolean; + onNavigate?: () => void; +}) { const { t } = useTranslation(); const f = useFormat(); const done = task.status === 'DONE'; @@ -272,14 +280,20 @@ export function TaskRow({ task, compact = false }: { task: Task; compact?: boole {task.title}

- + {task.merchant.name} - {done ? t('tasks.completed') : t('tasks.due', { date: f.shortDate(task.dueAt) })} + {done + ? `${t('tasks.completed')} · ${f.dateTime(task.completedAt ?? task.dueAt)}` + : t('tasks.due', { date: f.dateTime(task.dueAt) })} {overdue && ` · ${t('tasks.OVERDUE')}`}
@@ -290,8 +304,8 @@ export function TaskRow({ task, compact = false }: { task: Task; compact?: boole )} diff --git a/apps/web/src/components/shell.tsx b/apps/web/src/components/shell.tsx index 1f587ea..01b41c7 100644 --- a/apps/web/src/components/shell.tsx +++ b/apps/web/src/components/shell.tsx @@ -1,3 +1,4 @@ +import { ReminderInbox } from './reminders'; import { useState, useEffect } from 'react'; import { NavLink, Navigate, Outlet, useLocation, useNavigate } from 'react-router'; import { useQuery, useMutation } from '@tanstack/react-query'; @@ -171,6 +172,7 @@ function AuthenticatedShell({ user }: { user: User }) { {f.date(new Date())} + diff --git a/apps/web/src/components/tasks.tsx b/apps/web/src/components/tasks.tsx new file mode 100644 index 0000000..be2858b --- /dev/null +++ b/apps/web/src/components/tasks.tsx @@ -0,0 +1,361 @@ +import { useState } from 'react'; +import { useQuery } from '@tanstack/react-query'; +import { useOutletContext, useSearchParams } from 'react-router'; +import { useTranslation } from 'react-i18next'; +import { + merchantDetailSchema, + merchantListSchema, + taskInputSchema, + taskListSchema, + taskFilters, + type MerchantDetail, + type Task, + type User, + type TaskFilter, +} from '@merchantflow/contracts'; +import { Input } from '@merchantflow/ui/components/input'; +import { + Sheet, + SheetContent, + SheetTitle, + SheetDescription, +} from '@merchantflow/ui/components/sheet'; +import { api, ApiError } from '../lib/api'; +import { useLiveRefresh, viewerTimeZone } from '../lib/live-refresh'; +import { Button, EmptyState, PageHeader, QueryBoundary, SectionHeader, TaskRow } from './shared'; +import { Editor, useAction } from './workflow-form'; +const localDate = (value: string) => { + const date = new Date(value); + return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16); +}; +const isoDate = (value: string) => { + const date = new Date(value); + return Number.isFinite(date.getTime()) ? date.toISOString() : ''; +}; +function TaskEditor({ + merchant, + task, + close, + assignee, +}: { + merchant: { id: string; version: number }; + task?: Task; + close: () => void; + assignee: string; +}) { + const { t } = useTranslation(); + const [version, setVersion] = useState(merchant.version); + const [refreshed, setRefreshed] = useState(false); + const [refreshError, setRefreshError] = useState(false); + const action = useAction(merchant, close); + const feedback = ( + <> + {action.feedback} + {refreshed && ( +

+ {t('operations.versionLoaded')} +

+ )} + {refreshError &&

{t('common.errorTitle')}

} + {action.error instanceof ApiError && action.error.status === 409 && ( + + )} + + ); + return ( + ({ value, label: t(`tasks.${value}`) })), + }, + ]} + initial={{ + title: task?.title ?? '', + dueAt: localDate(task?.dueAt ?? new Date(Date.now() + 86400000).toISOString()), + remindAt: task?.remindAt ? localDate(task.remindAt) : '', + status: task?.status ?? 'OPEN', + }} + schema={taskInputSchema} + build={(values) => ({ + ...values, + version, + dueAt: task && values.dueAt === localDate(task.dueAt) ? task.dueAt : isoDate(values.dueAt!), + remindAt: + task?.remindAt && values.remindAt === localDate(task.remindAt) + ? task.remindAt + : values.remindAt + ? isoDate(values.remindAt) + : null, + })} + submit={(body) => + action.mutate({ + path: `/tasks${task ? `/${task.id}` : ''}`, + method: task ? 'PATCH' : 'POST', + body, + }) + } + close={close} + pending={action.isPending} + feedback={feedback} + /> + ); +} +export function ActionableTask({ task }: { task: Task }) { + const { t } = useTranslation(); + const [editing, setEditing] = useState(null); + const action = useAction(task.merchant); + const changeStatus = (status: 'OPEN' | 'DONE') => + action.mutate({ + path: `/tasks/${task.id}`, + body: { + version: task.merchant.version, + title: task.title, + dueAt: task.dueAt, + remindAt: task.remindAt, + status, + }, + }); + return ( +
+ +
+ {task.capabilities.edit && ( + + )} + {task.capabilities.complete && ( + + )} + {task.capabilities.reopen && ( + + )} + {action.feedback} +
+ {editing && ( + setEditing(null)} + /> + )} +
+ ); +} +function TaskComposer({ merchant, close }: { merchant?: MerchantDetail; close: () => void }) { + const { t } = useTranslation(); + const user = useOutletContext(); + const [search, setSearch] = useState(''); + const [page, setPage] = useState(1); + const [selected, setSelected] = useState(null); + const directory = useQuery({ + queryKey: ['merchants', 'task-picker', search, page], + queryFn: ({ signal }) => + api(`/merchants?${new URLSearchParams({ search, page: String(page) })}`, merchantListSchema, { + signal, + }), + enabled: !merchant && !selected, + }); + const detail = useQuery({ + queryKey: ['merchant', selected], + queryFn: ({ signal }) => api(`/merchants/${selected}`, merchantDetailSchema, { signal }), + enabled: !!selected, + }); + const current = merchant ?? detail.data; + if (current) + return ( + + ); + return ( + { + if (!open) close(); + }} + > + + {t('operations.chooseMerchant')} + {t('operations.ownerRule')} + {selected ? ( + {() => null} + ) : ( + <> + { + setSearch(e.target.value); + setPage(1); + }} + /> + + {(data) => ( +
+ {data.items.map((m) => ( + + ))} + {!data.items.length && } +
+ + +
+
+ )} +
+ + )} +
+
+ ); +} +export function MerchantTasks({ merchant }: { merchant: MerchantDetail }) { + const { t } = useTranslation(); + const [creating, setCreating] = useState(false); + return ( +
+ setCreating(true)}> + {t('workflow.addTask')} + + } + /> + {merchant.tasks.length ? ( + merchant.tasks.map((task) => ) + ) : ( + + )} + {creating && setCreating(false)} />} +
+ ); +} +export function Tasks() { + const { t } = useTranslation(); + const [params, setParams] = useSearchParams(); + const [creating, setCreating] = useState(false); + const raw = params.get('filter'); + const filter: TaskFilter = taskFilters.includes(raw as TaskFilter) + ? (raw as TaskFilter) + : 'TODAY'; + const queryParams = new URLSearchParams({ filter, timeZone: viewerTimeZone() }); + for (const key of ['merchantId', 'assigneeId']) + if (params.get(key)) queryParams.set(key, params.get(key)!); + const serialized = queryParams.toString(); + const query = useQuery({ + queryKey: ['tasks', serialized], + queryFn: ({ signal }) => api(`/tasks?${serialized}`, taskListSchema, { signal }), + }); + useLiveRefresh(query.refetch); + const hint = { + TODAY: 'todayHint', + UPCOMING: 'upcomingHint', + OVERDUE: 'overdueHint', + DONE: 'completedHint', + ALL: 'ownerRule', + OPEN: 'ownerRule', + }[filter]; + return ( + <> + setCreating(true)}>{t('workflow.addTask')}} + /> +
+
+ {taskFilters.map((value) => ( + + ))} + {(params.has('merchantId') || params.has('assigneeId')) && ( + + )} +
+ + {(tasks) => + tasks.length ? ( + tasks.map((task) => ) + ) : ( + + ) + } + +
+ {creating && setCreating(false)} />} + + ); +} diff --git a/apps/web/src/lib/directory-params.ts b/apps/web/src/lib/directory-params.ts index 8107c8c..eafaa14 100644 --- a/apps/web/src/lib/directory-params.ts +++ b/apps/web/src/lib/directory-params.ts @@ -5,7 +5,16 @@ export function directoryParams(input: URLSearchParams, role: Role) { const search = input.get('search')?.slice(0, 100); // Preserve typing whitespace; the server normalizes the search term. if (search) result.set('search', search); - for (const key of ['status', 'country', 'industry', 'ownerId', 'page'] as const) { + for (const key of [ + 'status', + 'country', + 'industry', + 'ownerId', + 'page', + 'createdFrom', + 'createdTo', + 'cohort', + ] as const) { if (key === 'ownerId' && role === 'ACCOUNT_MANAGER') continue; const raw = input.get(key); if (!raw) continue; diff --git a/apps/web/src/lib/live-refresh.ts b/apps/web/src/lib/live-refresh.ts new file mode 100644 index 0000000..d5ecd0b --- /dev/null +++ b/apps/web/src/lib/live-refresh.ts @@ -0,0 +1,19 @@ +import { useEffect } from 'react'; +export function useLiveRefresh(refetch: () => unknown) { + useEffect(() => { + const refresh = () => { + if (document.visibilityState === 'visible') void refetch(); + }; + window.addEventListener('focus', refresh); + window.addEventListener('online', refresh); + document.addEventListener('visibilitychange', refresh); + const timer = window.setInterval(refresh, 30000); + return () => { + window.clearInterval(timer); + window.removeEventListener('focus', refresh); + window.removeEventListener('online', refresh); + document.removeEventListener('visibilitychange', refresh); + }; + }, [refetch]); +} +export const viewerTimeZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone; diff --git a/apps/web/src/lib/review-params.ts b/apps/web/src/lib/review-params.ts index 3db1433..170c13c 100644 --- a/apps/web/src/lib/review-params.ts +++ b/apps/web/src/lib/review-params.ts @@ -3,9 +3,17 @@ export function reviewParams(input: URLSearchParams) { const result = new URLSearchParams(); const search = input.get('search')?.slice(0, 100); if (search) result.set('search', search); - for (const key of ['ownerId', 'waiting'] as const) { + for (const key of [ + 'ownerId', + 'waiting', + 'view', + 'decision', + 'decidedFrom', + 'decidedTo', + ] as const) { const parsed = reviewQueueQuerySchema.shape[key].safeParse(input.get(key) ?? undefined); - if (parsed.success && parsed.data && parsed.data !== 'ALL') result.set(key, parsed.data); + if (parsed.success && parsed.data && parsed.data !== 'ALL' && parsed.data !== 'PENDING') + result.set(key, parsed.data); } return result; } diff --git a/apps/web/src/locales.ts b/apps/web/src/locales.ts index 5544f70..d6059ad 100644 --- a/apps/web/src/locales.ts +++ b/apps/web/src/locales.ts @@ -1,8 +1,10 @@ +import { operationsEn, operationsRu } from './task-dashboard-locales'; import { onboardingEn, onboardingRu } from './onboarding-locales'; import { salesEn, salesRu } from './sales-locales'; import { workflowEn, workflowRu } from './workflow-locales'; import { landingEn, landingRu } from './landing-locales'; export const en = { + operations: operationsEn, onboarding: onboardingEn, workflow: workflowEn, workspace: salesEn, @@ -204,6 +206,7 @@ export const en = { stageCount: '{{number}} of 8 stages', }, tasks: { + TODAY: 'Today', title: 'Tasks', description: 'A little structure for the next right step.', ALL: 'All tasks', @@ -236,6 +239,7 @@ export const en = { }, }; export const ru = { + operations: operationsRu, onboarding: onboardingRu, workflow: workflowRu, workspace: salesRu, @@ -440,6 +444,7 @@ export const ru = { stageCount: '{{number}} из 8 этапов', }, tasks: { + TODAY: 'Сегодня', title: 'Задачи', description: 'Немного порядка для следующего верного шага.', ALL: 'Все задачи', diff --git a/apps/web/src/pages/crm.tsx b/apps/web/src/pages/crm.tsx index 3c10ef6..a0dddb1 100644 --- a/apps/web/src/pages/crm.tsx +++ b/apps/web/src/pages/crm.tsx @@ -6,7 +6,6 @@ import { ReviewHistory, InteractionHistory, MerchantTasks, - RecentInteractions, } from '../components/merchant-workflow'; import { useEffect, useState } from 'react'; import { Link, useLocation, useOutletContext, useParams, useSearchParams } from 'react-router'; @@ -14,12 +13,8 @@ import { keepPreviousData, useQuery } from '@tanstack/react-query'; import { useTranslation } from 'react-i18next'; import { ArrowRight, - ArrowUpRight, ArrowLeft, - Building2, - ShieldCheck, Clock3, - Activity, Search, ChevronLeft, ChevronRight, @@ -31,19 +26,15 @@ import { LoaderCircle, } from 'lucide-react'; import { - dashboardSchema, merchantListSchema, merchantDetailSchema, reviewQueueSchema, pipelineBoardSchema, merchantFiltersSchema, - taskListSchema, statuses, statusSchema, - taskFilters, canSeeReviewQueue, type User, - type TaskFilter, type Merchant, } from '@merchantflow/contracts'; import { Input } from '@merchantflow/ui/components/input'; @@ -70,154 +61,11 @@ import { Button, StatusBadge, Avatar, - TaskRow, MerchantCard, EmptyState, stageColors, } from '../components/shared'; -export function Dashboard() { - const { t } = useTranslation(); - const f = useFormat(); - const user = useOutletContext(); - const query = useQuery({ - queryKey: ['dashboard'], - queryFn: ({ signal }) => api('/dashboard', dashboardSchema, { signal }), - }); - return ( - <> - - {t('dashboard.view')} - - - } - /> - - {(data) => ( -
-
- {[ - { key: 'merchants', value: data.merchantCount, Icon: Building2 }, - { key: 'reviews', value: data.reviewCount, Icon: ShieldCheck }, - { key: 'overdue', value: data.overdueTasks, Icon: Clock3 }, - { key: 'changes', value: data.transitionsLast30Days, Icon: Activity }, - ].map(({ key, value, Icon }, i) => ( -
-
-

- {t(`dashboard.${key}`)} -

-
-
-
-

- {f.number(value)} -

-

- {t(`dashboard.${key}Hint`)} -

-
- ))} -
-
- - {t('dashboard.openPipeline')} - - - } - /> -
- -
-
-
- - -
-
- - {t('common.viewAll')} - - - } - /> -
- {data.upcomingTasks.length ? ( - data.upcomingTasks.map((task) => ) - ) : ( - - )} -
-
-
-
-
-
- )} -
- - ); -} +export { Dashboard } from '../components/dashboard'; function useDebounced(value: string) { const [debounced, setDebounced] = useState(value); useEffect(() => { @@ -469,6 +317,23 @@ export function Merchants() { )} + {(normalized.has('cohort') || + normalized.has('createdFrom') || + normalized.has('createdTo')) && ( +
+ {normalized.get('cohort') &&

{t(`operations.${normalized.get('cohort')}`)}

} + {(normalized.has('createdFrom') || normalized.has('createdTo')) && ( +

+ {t('operations.createdWindow', { + from: normalized.get('createdFrom') + ? f.dateTime(normalized.get('createdFrom')!) + : '—', + to: normalized.get('createdTo') ? f.dateTime(normalized.get('createdTo')!) : '—', + })} +

+ )} +
+ )} {filters.isError && (
{t('common.errorTitle')}{' '} @@ -880,54 +745,7 @@ export function Pipeline() { ); } -export function Tasks() { - const { t } = useTranslation(); - const [params, setParams] = useSearchParams(); - const raw = params.get('filter'); - const filter: TaskFilter = taskFilters.includes(raw as TaskFilter) ? (raw as TaskFilter) : 'ALL'; - const query = useQuery({ - queryKey: ['tasks', filter], - queryFn: ({ signal }) => api(`/tasks?filter=${filter}`, taskListSchema, { signal }), - refetchInterval: 60000, - }); - return ( - <> - -
-
- {taskFilters.map((s) => ( - - ))} -
- - {(tasks) => - tasks.length ? ( -
- {tasks.map((task) => ( - - ))} -
- ) : ( - - ) - } -
-
- - ); -} +export { Tasks } from '../components/tasks'; export function ReviewQueue() { const user = useOutletContext(); const { t } = useTranslation(); @@ -935,6 +753,7 @@ export function ReviewQueue() { const [params, setParams] = useSearchParams(); const filters = reviewParams(params); const serialized = filters.toString(); + const decided = filters.get('view') === 'DECISIONS'; const allowed = canSeeReviewQueue(user.role); const query = useQuery({ queryKey: ['review-queue', serialized], @@ -951,10 +770,38 @@ export function ReviewQueue() { return ( <> +
+ + +
+ {decided && (filters.has('decidedFrom') || filters.has('decidedTo')) && ( +

+ {t('operations.decisionWindow', { + from: filters.get('decidedFrom') ? f.dateTime(filters.get('decidedFrom')!) : '—', + to: filters.get('decidedTo') ? f.dateTime(filters.get('decidedTo')!) : '—', + })} +

+ )}
@@ -1009,7 +862,7 @@ export function ReviewQueue() {
- {t('review.order')} + {t(decided ? 'operations.decisionHistory' : 'review.order')} {serialized && (