Added tasks, reminders, and role-specific dashboards
This commit is contained in:
@@ -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?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/merchants/:id` | Overview, checklist, notes, tasks, history |
|
||||||
| GET | `/api/pipeline` | Scoped merchants grouped in the UI |
|
| 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 |
|
| 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.
|
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 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
|
## Verification
|
||||||
|
|
||||||
@@ -140,7 +140,7 @@ The [product brief](docs/product-brief.md) and [implementation checklist](docs/i
|
|||||||
|
|
||||||
## Editing and workflow rules
|
## 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.
|
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-<id>` and remain valid after decisions.
|
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-<id>` 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.
|
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.
|
||||||
|
|||||||
@@ -19,7 +19,9 @@ export function merchantScope(user: User): Prisma.MerchantWhereInput {
|
|||||||
export function taskScope(user: User): Prisma.TaskWhereInput {
|
export function taskScope(user: User): Prisma.TaskWhereInput {
|
||||||
return {
|
return {
|
||||||
merchant: merchantScope(user),
|
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) {
|
export function requireSales(user: User) {
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import { NestFactory } from '@nestjs/core';
|
|||||||
import cookieParser from 'cookie-parser';
|
import cookieParser from 'cookie-parser';
|
||||||
import { createDatabase, PrismaClient } from '@merchantflow/database';
|
import { createDatabase, PrismaClient } from '@merchantflow/database';
|
||||||
import { AuthController, AuthService, SessionGuard } from './auth.js';
|
import { AuthController, AuthService, SessionGuard } from './auth.js';
|
||||||
|
import { ReminderController } from './reminders.js';
|
||||||
import { CrmController } from './crm.js';
|
import { CrmController } from './crm.js';
|
||||||
import { WorkflowController } from './workflow.js';
|
import { WorkflowController } from './workflow.js';
|
||||||
import { DATABASE, ApiError, ErrorFilter } from './shared.js';
|
import { DATABASE, ApiError, ErrorFilter } from './shared.js';
|
||||||
@@ -40,6 +41,7 @@ class DatabaseLifecycle implements OnApplicationShutdown {
|
|||||||
HealthController,
|
HealthController,
|
||||||
AuthController,
|
AuthController,
|
||||||
CrmController,
|
CrmController,
|
||||||
|
ReminderController,
|
||||||
WorkflowController,
|
WorkflowController,
|
||||||
PublicLeadController,
|
PublicLeadController,
|
||||||
],
|
],
|
||||||
|
|||||||
+58
-158
@@ -1,16 +1,15 @@
|
|||||||
import { Controller, Get, Inject, Param, Query, Req, UseGuards } from '@nestjs/common';
|
import { Controller, Get, Inject, Param, Query, Req, UseGuards } from '@nestjs/common';
|
||||||
import { PrismaClient, type Prisma } from '@merchantflow/database';
|
import { PrismaClient } from '@merchantflow/database';
|
||||||
import {
|
import { merchantQuerySchema, reviewQueueQuerySchema } from '@merchantflow/contracts';
|
||||||
statuses,
|
|
||||||
merchantQuerySchema,
|
|
||||||
taskQuerySchema,
|
|
||||||
reviewQueueQuerySchema,
|
|
||||||
} from '@merchantflow/contracts';
|
|
||||||
import { SessionGuard } from './auth.js';
|
import { SessionGuard } from './auth.js';
|
||||||
import { DATABASE, ApiError, type AuthRequest } from './shared.js';
|
import { DATABASE, ApiError, type AuthRequest } from './shared.js';
|
||||||
import { capabilities, merchantScope, taskScope } from './access.js';
|
import { capabilities, merchantScope, taskScope } from './access.js';
|
||||||
import { evidenceInclude } from './workflow-policy.js';
|
import { evidenceInclude } from './workflow-policy.js';
|
||||||
import { merchantHistory } from './history.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 = {
|
const merchantSelect = {
|
||||||
id: true,
|
id: true,
|
||||||
name: true,
|
name: true,
|
||||||
@@ -43,21 +42,6 @@ const eventSelect = {
|
|||||||
merchant: { select: { id: true, name: true } },
|
merchant: { select: { id: true, name: true } },
|
||||||
actor: { select: { name: true } },
|
actor: { select: { name: true } },
|
||||||
} as const;
|
} 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 = {
|
const activitySelect = {
|
||||||
id: true,
|
id: true,
|
||||||
kind: true,
|
kind: true,
|
||||||
@@ -80,37 +64,8 @@ export class CrmController {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
@Get('merchants') async merchants(@Req() req: AuthRequest, @Query() query: unknown) {
|
@Get('merchants') async merchants(@Req() req: AuthRequest, @Query() query: unknown) {
|
||||||
const {
|
const { page: requestedPage } = merchantQuerySchema.parse(query);
|
||||||
page: requestedPage,
|
const where = merchantWhere(req.user, query);
|
||||||
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 } },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
]
|
|
||||||
: []),
|
|
||||||
],
|
|
||||||
};
|
|
||||||
return this.db.$transaction(
|
return this.db.$transaction(
|
||||||
async (tx) => {
|
async (tx) => {
|
||||||
const total = await tx.merchant.count({ where });
|
const total = await tx.merchant.count({ where });
|
||||||
@@ -181,7 +136,11 @@ export class CrmController {
|
|||||||
events: { select: eventSelect, orderBy: { occurredAt: 'desc' } },
|
events: { select: eventSelect, orderBy: { occurredAt: 'desc' } },
|
||||||
tasks: { where: taskScope(req.user), select: taskSelect, orderBy: { dueAt: 'asc' } },
|
tasks: { where: taskScope(req.user), select: taskSelect, orderBy: { dueAt: 'asc' } },
|
||||||
activities: {
|
activities: {
|
||||||
select: { ...activitySelect, metadata: true },
|
select: {
|
||||||
|
...activitySelect,
|
||||||
|
metadata: true,
|
||||||
|
actor: { select: { id: true, name: true, role: true } },
|
||||||
|
},
|
||||||
orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }],
|
orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }],
|
||||||
},
|
},
|
||||||
reviews: {
|
reviews: {
|
||||||
@@ -208,11 +167,37 @@ export class CrmController {
|
|||||||
where: { AND: [merchantScope(req.user), { id }] },
|
where: { AND: [merchantScope(req.user), { id }] },
|
||||||
include: evidenceInclude,
|
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 {
|
return {
|
||||||
...merchant,
|
...merchant,
|
||||||
|
tasks: merchant.tasks.map((task) => taskDto(task, req.user)),
|
||||||
activationChecks: evidence.reviews.flatMap((review) => review.activationChecks),
|
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),
|
capabilities: capabilities(req.user, evidence),
|
||||||
history,
|
history,
|
||||||
};
|
};
|
||||||
@@ -241,63 +226,41 @@ export class CrmController {
|
|||||||
{ isolationLevel: 'RepeatableRead' },
|
{ isolationLevel: 'RepeatableRead' },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@Get('tasks') tasks(@Req() req: AuthRequest, @Query() query: unknown) {
|
@Get('tasks') async tasks(@Req() req: AuthRequest, @Query() query: unknown) {
|
||||||
const { filter } = taskQuerySchema.parse(query);
|
const rows = await this.db.task.findMany({
|
||||||
const where: Prisma.TaskWhereInput = taskScope(req.user);
|
where: taskWhere(req.user, query),
|
||||||
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,
|
|
||||||
select: taskSelect,
|
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) {
|
@Get('review-queue') async reviewQueue(@Req() req: AuthRequest, @Query() query: unknown) {
|
||||||
if (req.user.role !== 'COMPLIANCE_OFFICER') throw new ApiError('FORBIDDEN', 403);
|
if (req.user.role !== 'COMPLIANCE_OFFICER') throw new ApiError('FORBIDDEN', 403);
|
||||||
const { search, ownerId, waiting } = reviewQueueQuerySchema.parse(query);
|
const { view } = reviewQueueQuerySchema.parse(query);
|
||||||
const base: Prisma.ComplianceReviewWhereInput = {
|
const pending = pendingReviews(req.user);
|
||||||
decision: 'PENDING',
|
|
||||||
merchant: { AND: [merchantScope(req.user), { status: 'COMPLIANCE_REVIEW' }] },
|
|
||||||
};
|
|
||||||
return this.db.$transaction(
|
return this.db.$transaction(
|
||||||
async (tx) => {
|
async (tx) => {
|
||||||
const pendingCount = await tx.complianceReview.count({ where: base });
|
const pendingCount = await tx.complianceReview.count({ where: pending });
|
||||||
const owners = await tx.user.findMany({
|
const owners = await tx.user.findMany({
|
||||||
where: { role: 'ACCOUNT_MANAGER' },
|
where: { role: 'ACCOUNT_MANAGER' },
|
||||||
select: { id: true, name: true },
|
select: { id: true, name: true },
|
||||||
orderBy: { name: 'asc' },
|
orderBy: { name: 'asc' },
|
||||||
});
|
});
|
||||||
const items = await tx.complianceReview.findMany({
|
const items = await tx.complianceReview.findMany({
|
||||||
where: {
|
where: reviewWhere(req.user, query),
|
||||||
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' } }),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
: {}),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
cycle: true,
|
cycle: true,
|
||||||
policyVersion: true,
|
policyVersion: true,
|
||||||
|
decision: true,
|
||||||
|
decidedAt: true,
|
||||||
submittedAt: true,
|
submittedAt: true,
|
||||||
merchant: { select: merchantSelect },
|
merchant: { select: merchantSelect },
|
||||||
},
|
},
|
||||||
orderBy: [{ submittedAt: 'asc' }, { id: 'asc' }],
|
orderBy:
|
||||||
|
view === 'PENDING'
|
||||||
|
? [{ submittedAt: 'asc' }, { id: 'asc' }]
|
||||||
|
: [{ decidedAt: 'desc' }, { id: 'asc' }],
|
||||||
});
|
});
|
||||||
return {
|
return {
|
||||||
items,
|
items,
|
||||||
@@ -309,70 +272,7 @@ export class CrmController {
|
|||||||
{ isolationLevel: 'RepeatableRead' },
|
{ isolationLevel: 'RepeatableRead' },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@Get('dashboard') async dashboard(@Req() req: AuthRequest) {
|
@Get('dashboard') dashboard(@Req() req: AuthRequest) {
|
||||||
const scope = merchantScope(req.user);
|
return dashboardData(this.db, 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,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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' },
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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] } }] : []),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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 };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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' } }),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -206,7 +206,11 @@ export class WorkflowController {
|
|||||||
await tx.merchant.updateMany({ where: { id }, data: { ownerId } });
|
await tx.merchant.updateMany({ where: { id }, data: { ownerId } });
|
||||||
await tx.task.updateMany({
|
await tx.task.updateMany({
|
||||||
where: { merchantId: id, kind: 'COMMERCIAL', status: 'OPEN' },
|
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', {
|
await this.audit(tx, req, id, 'Manager assignment updated', {
|
||||||
previousOwnerId: merchant.ownerId,
|
previousOwnerId: merchant.ownerId,
|
||||||
@@ -498,6 +502,24 @@ export class WorkflowController {
|
|||||||
: null;
|
: null;
|
||||||
if (taskId && !existing) throw new ApiError('NOT_FOUND', 404);
|
if (taskId && !existing) throw new ApiError('NOT_FOUND', 404);
|
||||||
if (existing && existing.kind !== kind) throw new ApiError('FORBIDDEN', 403);
|
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 =
|
const completion =
|
||||||
status === 'DONE'
|
status === 'DONE'
|
||||||
? {
|
? {
|
||||||
@@ -506,6 +528,10 @@ export class WorkflowController {
|
|||||||
}
|
}
|
||||||
: { completedAt: null, completedById: null };
|
: { completedAt: null, completedById: null };
|
||||||
const data = {
|
const data = {
|
||||||
|
assigneeId,
|
||||||
|
...(reminderChanged
|
||||||
|
? { reminderDismissedAt: null, reminderRevision: { increment: 1 } }
|
||||||
|
: {}),
|
||||||
title,
|
title,
|
||||||
dueAt: new Date(dueAt),
|
dueAt: new Date(dueAt),
|
||||||
remindAt: remindAt ? new Date(remindAt) : null,
|
remindAt: remindAt ? new Date(remindAt) : null,
|
||||||
@@ -517,18 +543,27 @@ export class WorkflowController {
|
|||||||
where: { AND: [taskScope(req.user), { id: existing.id, merchantId: id }] },
|
where: { AND: [taskScope(req.user), { id: existing.id, merchantId: id }] },
|
||||||
data,
|
data,
|
||||||
});
|
});
|
||||||
else
|
else {
|
||||||
await tx.task.create({
|
const created = await tx.task.create({
|
||||||
data: {
|
data: {
|
||||||
...data,
|
...data,
|
||||||
|
reminderRevision: 0,
|
||||||
kind,
|
kind,
|
||||||
creatorId: req.user.id,
|
creatorId: req.user.id,
|
||||||
merchantId: 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', {
|
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,
|
title,
|
||||||
status,
|
status,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -125,7 +125,7 @@ for (const [account, total] of [
|
|||||||
merchantId: { in: ids },
|
merchantId: { in: ids },
|
||||||
...(account === 'compliance'
|
...(account === 'compliance'
|
||||||
? { kind: 'COMPLIANCE', assigneeId: 'user-compliance' }
|
? { kind: 'COMPLIANCE', assigneeId: 'user-compliance' }
|
||||||
: {}),
|
: { kind: 'COMMERCIAL' }),
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -151,7 +151,7 @@ for (const [account, total] of [
|
|||||||
merchantId: { in: ids },
|
merchantId: { in: ids },
|
||||||
...(account === 'compliance'
|
...(account === 'compliance'
|
||||||
? { kind: 'COMPLIANCE', assigneeId: 'user-compliance' }
|
? { kind: 'COMPLIANCE', assigneeId: 'user-compliance' }
|
||||||
: {}),
|
: { kind: 'COMMERCIAL' }),
|
||||||
status: 'OPEN',
|
status: 'OPEN',
|
||||||
dueAt: { lt: new Date() },
|
dueAt: { lt: new Date() },
|
||||||
},
|
},
|
||||||
@@ -775,7 +775,7 @@ test('reassignment transfers open commercial tasks; concurrent writes and former
|
|||||||
);
|
);
|
||||||
const before = await get();
|
const before = await get();
|
||||||
assert.equal((await get(comp)).tasks.length, 1);
|
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(
|
assert.equal(
|
||||||
(
|
(
|
||||||
await mutate(`/merchants/${id}/tasks/${personal.id}`, head, {
|
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,
|
version: before.version,
|
||||||
})
|
})
|
||||||
).status,
|
).status,
|
||||||
403,
|
404,
|
||||||
);
|
);
|
||||||
const commercial = before.tasks.find((t) => t.kind === 'COMMERCIAL');
|
const commercial = before.tasks.find((t) => t.kind === 'COMMERCIAL');
|
||||||
assert.equal(
|
assert.equal(
|
||||||
@@ -828,7 +828,10 @@ test('reassignment transfers open commercial tasks; concurrent writes and former
|
|||||||
.filter((t) => t.status === 'DONE')
|
.filter((t) => t.status === 'DONE')
|
||||||
.every((t) => t.assignee.id === 'user-manager1'),
|
.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((await request(`/merchants/${id}`, alex)).status, 404);
|
||||||
assert.equal(
|
assert.equal(
|
||||||
(
|
(
|
||||||
|
|||||||
@@ -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: '[email protected]',
|
||||||
|
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: '[email protected]',
|
||||||
|
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' } });
|
||||||
|
});
|
||||||
@@ -34,3 +34,27 @@ test('every role receives its exact merchant scope', () => {
|
|||||||
assert.deepEqual(merchantScope({ role: 'COMPLIANCE_OFFICER' }), {});
|
assert.deepEqual(merchantScope({ role: 'COMPLIANCE_OFFICER' }), {});
|
||||||
assert.deepEqual(merchantScope({ role: 'unexpected' }), { id: '__no_access__' });
|
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 },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|||||||
@@ -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<typeof dashboardSchema>;
|
||||||
|
function Metric({
|
||||||
|
title,
|
||||||
|
value,
|
||||||
|
hint,
|
||||||
|
to,
|
||||||
|
}: {
|
||||||
|
title: string;
|
||||||
|
value: string | number;
|
||||||
|
hint?: string;
|
||||||
|
to: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<Link to={to} className="surface hover-surface block p-5">
|
||||||
|
<h2 className="text-xs font-medium text-muted-foreground">{title}</h2>
|
||||||
|
<p className="my-4 text-3xl font-semibold tracking-tight tabular-nums">{value}</p>
|
||||||
|
{hint && <p className="text-xs leading-relaxed text-muted-foreground">{hint}</p>}
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function BusinessMetrics({ data }: { data: Data }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const f = useFormat();
|
||||||
|
return (
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<Metric
|
||||||
|
title={t('operations.activation')}
|
||||||
|
value={
|
||||||
|
data.activation.rate === null
|
||||||
|
? '—'
|
||||||
|
: `${f.number(Number((100 * data.activation.rate).toFixed(1)))}%`
|
||||||
|
}
|
||||||
|
hint={
|
||||||
|
data.activation.denominator
|
||||||
|
? t('operations.activationHint', {
|
||||||
|
live: data.activation.numerator,
|
||||||
|
total: data.activation.denominator,
|
||||||
|
})
|
||||||
|
: t('operations.noMerchants')
|
||||||
|
}
|
||||||
|
to="/app/merchants?status=LIVE"
|
||||||
|
/>
|
||||||
|
<Metric
|
||||||
|
title={t('operations.duration')}
|
||||||
|
value={
|
||||||
|
data.onboardingDuration.averageDays === null
|
||||||
|
? '—'
|
||||||
|
: t('operations.days', {
|
||||||
|
value: f.number(Number(data.onboardingDuration.averageDays.toFixed(1))),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
hint={
|
||||||
|
data.onboardingDuration.sampleCount
|
||||||
|
? t('operations.durationHint', { count: data.onboardingDuration.sampleCount })
|
||||||
|
: t('operations.noLive')
|
||||||
|
}
|
||||||
|
to="/app/merchants?cohort=REACHED_LIVE"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function Priorities({ data, compliance = false }: { data: Data; compliance?: boolean }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<section className="surface">
|
||||||
|
<SectionHeader
|
||||||
|
title={t(compliance ? 'operations.reviewTasks' : 'operations.next')}
|
||||||
|
description={t('operations.nextHint')}
|
||||||
|
action={
|
||||||
|
<LinkButton to="/app/tasks?filter=OPEN" variant="ghost">
|
||||||
|
{t('common.viewAll')}
|
||||||
|
</LinkButton>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{data.upcomingTasks.length ? (
|
||||||
|
data.upcomingTasks.map((task) => <ActionableTask key={task.id} task={task} />)
|
||||||
|
) : (
|
||||||
|
<EmptyState title={t('operations.noTasks')} />
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
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 (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
|
||||||
|
<Metric
|
||||||
|
title={t('operations.total')}
|
||||||
|
value={f.number(data.merchantCount)}
|
||||||
|
to="/app/merchants"
|
||||||
|
/>
|
||||||
|
<Metric
|
||||||
|
title={t('operations.newLeads')}
|
||||||
|
value={f.number(data.newLeads)}
|
||||||
|
hint={t('operations.newHint')}
|
||||||
|
to={`/app/merchants?${createdQuery}`}
|
||||||
|
/>
|
||||||
|
<Metric
|
||||||
|
title={t('operations.active')}
|
||||||
|
value={f.number(data.activeOnboarding)}
|
||||||
|
hint={t('operations.activeHint')}
|
||||||
|
to="/app/merchants?cohort=ACTIVE_ONBOARDING"
|
||||||
|
/>
|
||||||
|
<Metric
|
||||||
|
title={t('operations.live')}
|
||||||
|
value={f.number(data.liveMerchants)}
|
||||||
|
to="/app/merchants?status=LIVE"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<Metric
|
||||||
|
title={t('operations.overdue')}
|
||||||
|
value={f.number(data.overdueTasks)}
|
||||||
|
hint={t('operations.overdueHint')}
|
||||||
|
to="/app/tasks?filter=OVERDUE"
|
||||||
|
/>
|
||||||
|
{!manager && (
|
||||||
|
<Metric
|
||||||
|
title={t('operations.unassigned')}
|
||||||
|
value={f.number(data.unassignedLeads)}
|
||||||
|
to="/app/merchants?status=NEW_LEAD&ownerId=unassigned"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{manager && <Priorities data={data} />}
|
||||||
|
<BusinessMetrics data={data} />
|
||||||
|
<section className="surface">
|
||||||
|
<SectionHeader
|
||||||
|
title={t('dashboard.pipeline')}
|
||||||
|
description={t('dashboard.pipelineText')}
|
||||||
|
action={
|
||||||
|
<LinkButton to="/app/pipeline" variant="ghost">
|
||||||
|
{t('dashboard.openPipeline')}
|
||||||
|
</LinkButton>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{data.merchantCount ? (
|
||||||
|
<div className="px-5 pb-5">
|
||||||
|
<div className="mb-5 flex h-3 gap-1 overflow-hidden rounded-full" aria-hidden="true">
|
||||||
|
{data.distribution
|
||||||
|
.filter((d) => d.count)
|
||||||
|
.map((d) => (
|
||||||
|
<div
|
||||||
|
key={d.status}
|
||||||
|
style={{ flex: d.count, backgroundColor: stageColors[d.status] }}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-9">
|
||||||
|
{data.distribution.map((d) => (
|
||||||
|
<Link
|
||||||
|
className="min-h-11 rounded-md p-1"
|
||||||
|
key={d.status}
|
||||||
|
to={`/app/merchants?status=${d.status}`}
|
||||||
|
>
|
||||||
|
<span className="text-xs text-muted-foreground">{t(`statuses.${d.status}`)}</span>
|
||||||
|
<span className="mt-2 block text-lg font-semibold tabular-nums">
|
||||||
|
{f.number(d.count)}
|
||||||
|
</span>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<EmptyState title={t('operations.noMerchants')} />
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
<section className="surface">
|
||||||
|
<SectionHeader title={t(manager ? 'operations.ownWorkload' : 'operations.workload')} />
|
||||||
|
<div className="grid gap-4 px-5 pb-5 sm:grid-cols-2">
|
||||||
|
{data.workload.map((row) => {
|
||||||
|
const owner = manager ? '' : `ownerId=${row.id}`;
|
||||||
|
return (
|
||||||
|
<article key={row.id} className="rounded-lg border p-4">
|
||||||
|
<h3 className="mb-3 text-sm font-semibold">{row.name}</h3>
|
||||||
|
<dl className="space-y-3 text-sm">
|
||||||
|
{[
|
||||||
|
['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]) => (
|
||||||
|
<div key={label} className="flex justify-between gap-3">
|
||||||
|
<dt>{t(`operations.${label}`)}</dt>
|
||||||
|
<dd>
|
||||||
|
<Link className="font-semibold underline tabular-nums" to={String(to)}>
|
||||||
|
{f.number(Number(value))}
|
||||||
|
</Link>
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</dl>
|
||||||
|
</article>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{!manager && <Priorities data={data} />}
|
||||||
|
<section className="surface">
|
||||||
|
<SectionHeader title={t('dashboard.activity')} description={t('dashboard.activityText')} />
|
||||||
|
{data.recentActivities.length ? (
|
||||||
|
<RecentInteractions activities={data.recentActivities} />
|
||||||
|
) : (
|
||||||
|
<EmptyState title={t('operations.noActivity')} />
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
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 (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="grid gap-4 sm:grid-cols-3">
|
||||||
|
<Metric
|
||||||
|
title={t('operations.pending')}
|
||||||
|
value={f.number(data.reviewCount)}
|
||||||
|
to="/app/review-queue"
|
||||||
|
/>
|
||||||
|
<Metric
|
||||||
|
title={t('operations.decisions')}
|
||||||
|
value={f.number(data.decisionsLast30Days)}
|
||||||
|
hint={t('operations.decisionsHint')}
|
||||||
|
to={history}
|
||||||
|
/>
|
||||||
|
<Metric
|
||||||
|
title={t('operations.overdue')}
|
||||||
|
value={f.number(data.overdueTasks)}
|
||||||
|
hint={t('operations.personal')}
|
||||||
|
to="/app/tasks?filter=OVERDUE"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<section className="surface">
|
||||||
|
<SectionHeader
|
||||||
|
title={t('operations.oldest')}
|
||||||
|
action={
|
||||||
|
<LinkButton to="/app/review-queue" variant="ghost">
|
||||||
|
{t('common.viewAll')}
|
||||||
|
</LinkButton>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{data.oldestReviews.length ? (
|
||||||
|
<div className="divide-y px-5 pb-3">
|
||||||
|
{data.oldestReviews.map((review) => (
|
||||||
|
<Link
|
||||||
|
className="flex min-h-16 flex-wrap items-center justify-between gap-3 py-4"
|
||||||
|
key={review.id}
|
||||||
|
to={`/app/merchants/${review.merchant.id}?tab=onboarding#review-${review.id}`}
|
||||||
|
>
|
||||||
|
<span className="text-sm font-semibold">{review.merchant.name}</span>
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
<StageAge since={review.submittedAt} waiting /> · {f.dateTime(review.submittedAt)}
|
||||||
|
</span>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<EmptyState title={t('operations.noReviews')} />
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
<div className="grid gap-4 sm:grid-cols-3">
|
||||||
|
{data.decisions.map((d) => (
|
||||||
|
<Metric
|
||||||
|
key={d.decision}
|
||||||
|
title={t(`workflow.${d.decision}`)}
|
||||||
|
value={f.number(d.count)}
|
||||||
|
to={`${history}&decision=${d.decision}`}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<Priorities data={data} compliance />
|
||||||
|
<BusinessMetrics data={data} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
export function Dashboard() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const user = useOutletContext<User>();
|
||||||
|
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 (
|
||||||
|
<>
|
||||||
|
<PageHeader
|
||||||
|
title={t(`operations.${role}Title`)}
|
||||||
|
description={t(`operations.${role}Description`)}
|
||||||
|
eyebrow={t('dashboard.eyebrow')}
|
||||||
|
action={
|
||||||
|
<LinkButton to={role === 'compliance' ? '/app/review-queue' : '/app/merchants'}>
|
||||||
|
{t(role === 'compliance' ? 'review.title' : 'dashboard.view')}
|
||||||
|
</LinkButton>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<QueryBoundary query={query}>
|
||||||
|
{(data) =>
|
||||||
|
role === 'compliance' ? (
|
||||||
|
<ComplianceDashboard data={data} />
|
||||||
|
) : (
|
||||||
|
<SalesDashboard data={data} user={user} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
</QueryBoundary>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -12,15 +12,13 @@ import {
|
|||||||
isRequiredDocument,
|
isRequiredDocument,
|
||||||
sources,
|
sources,
|
||||||
statuses,
|
statuses,
|
||||||
taskInputSchema,
|
|
||||||
type MerchantDetail,
|
type MerchantDetail,
|
||||||
type Task,
|
|
||||||
} from '@merchantflow/contracts';
|
} from '@merchantflow/contracts';
|
||||||
import { api } from '../lib/api';
|
import { api } from '../lib/api';
|
||||||
import { Editor, useAction, type Field } from './workflow-form';
|
import { Editor, useAction, type Field } from './workflow-form';
|
||||||
import { StageActions } from './sales-workspace';
|
import { StageActions } from './sales-workspace';
|
||||||
import { useFormat } from '../lib/format';
|
import { useFormat } from '../lib/format';
|
||||||
import { Button, SectionHeader, TaskRow } from './shared';
|
import { Button, SectionHeader } from './shared';
|
||||||
|
|
||||||
const identityFields = [
|
const identityFields = [
|
||||||
'name',
|
'name',
|
||||||
@@ -431,111 +429,7 @@ export function InteractionHistory({ merchant: m }: { merchant: MerchantDetail }
|
|||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const localDate = (value: string) => {
|
export { MerchantTasks } from './tasks';
|
||||||
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<string | null>(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 (
|
|
||||||
<section className="surface" id="tasks">
|
|
||||||
<SectionHeader
|
|
||||||
title={t('merchants.tasks')}
|
|
||||||
description={t('workflow.taskOwnership')}
|
|
||||||
action={
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
onClick={() => {
|
|
||||||
action.reset();
|
|
||||||
setEdit('new');
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{t('workflow.addTask')}
|
|
||||||
</Button>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<div className="p-5">{action.feedback}</div>
|
|
||||||
{m.tasks.map((task) => (
|
|
||||||
<div key={task.id} className="border-t">
|
|
||||||
<TaskRow task={task} />
|
|
||||||
{task.kind === m.capabilities.manageTaskKind && (
|
|
||||||
<div className="flex flex-wrap gap-2 px-5 pb-4">
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
onClick={() => {
|
|
||||||
action.reset();
|
|
||||||
setEdit(task.id);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{t('workflow.editTask')}
|
|
||||||
</Button>
|
|
||||||
{task.status === 'OPEN' && (
|
|
||||||
<Button variant="ghost" disabled={action.isPending} onClick={() => complete(task)}>
|
|
||||||
{t('workflow.complete')}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
{edit && (
|
|
||||||
<Editor
|
|
||||||
title={t(existing ? 'workflow.editTask' : 'workflow.addTask')}
|
|
||||||
fields={[
|
|
||||||
{ name: 'title' },
|
|
||||||
{ name: 'dueAt', type: 'datetime-local' },
|
|
||||||
{ name: 'remindAt', type: 'datetime-local' },
|
|
||||||
{
|
|
||||||
name: 'status',
|
|
||||||
options: ['OPEN', 'DONE'].map((value) => ({ 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}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
export function RecentInteractions({ activities }: { activities: MerchantDetail['activities'] }) {
|
export function RecentInteractions({ activities }: { activities: MerchantDetail['activities'] }) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const f = useFormat();
|
const f = useFormat();
|
||||||
|
|||||||
@@ -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 (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
className="relative"
|
||||||
|
aria-label={
|
||||||
|
query.isError || count === undefined
|
||||||
|
? t('operations.reminders')
|
||||||
|
: t('operations.remindersCount', { count })
|
||||||
|
}
|
||||||
|
onClick={() => {
|
||||||
|
setOpen(true);
|
||||||
|
void query.refetch();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Bell className="size-5" aria-hidden="true" />
|
||||||
|
<span aria-live="polite" className="tabular-nums">
|
||||||
|
{query.isError ? '!' : count ? count : ''}
|
||||||
|
</span>
|
||||||
|
</Button>
|
||||||
|
<Sheet open={open} onOpenChange={setOpen}>
|
||||||
|
<SheetContent
|
||||||
|
closeLabel={t('common.close')}
|
||||||
|
className="w-full! overflow-y-auto p-5 sm:max-w-lg!"
|
||||||
|
>
|
||||||
|
<SheetTitle>{t('operations.reminders')}</SheetTitle>
|
||||||
|
<SheetDescription>{t('operations.inboxDescription')}</SheetDescription>
|
||||||
|
{dismissal.isError && (
|
||||||
|
<p role="alert" className="text-sm text-destructive">
|
||||||
|
{t('operations.remindersError')}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<QueryBoundary query={query}>
|
||||||
|
{(tasks) =>
|
||||||
|
tasks.length ? (
|
||||||
|
<div>
|
||||||
|
{tasks.map((task) => (
|
||||||
|
<div className="border-b pb-3" key={task.id}>
|
||||||
|
<TaskRow task={task} onNavigate={() => setOpen(false)} />
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
disabled={dismissal.isPending}
|
||||||
|
onClick={() => dismissal.mutate(task)}
|
||||||
|
>
|
||||||
|
{t('operations.dismiss')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<EmptyState
|
||||||
|
title={t('operations.noReminders')}
|
||||||
|
description={t('operations.noRemindersHint')}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
</QueryBoundary>
|
||||||
|
</SheetContent>
|
||||||
|
</Sheet>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -248,7 +248,15 @@ export function MerchantCard({ merchant, className }: { merchant: Merchant; clas
|
|||||||
</Link>
|
</Link>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
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 { t } = useTranslation();
|
||||||
const f = useFormat();
|
const f = useFormat();
|
||||||
const done = task.status === 'DONE';
|
const done = task.status === 'DONE';
|
||||||
@@ -272,14 +280,20 @@ export function TaskRow({ task, compact = false }: { task: Task; compact?: boole
|
|||||||
{task.title}
|
{task.title}
|
||||||
</p>
|
</p>
|
||||||
<div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs">
|
<div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs">
|
||||||
<Link to={`/app/merchants/${task.merchant.id}`} className="font-medium hover:underline">
|
<Link
|
||||||
|
to={`/app/merchants/${task.merchant.id}?tab=tasks#task-${task.id}`}
|
||||||
|
onClick={onNavigate}
|
||||||
|
className="font-medium hover:underline"
|
||||||
|
>
|
||||||
{task.merchant.name}
|
{task.merchant.name}
|
||||||
</Link>
|
</Link>
|
||||||
<span className="text-muted-foreground" aria-hidden="true">
|
<span className="text-muted-foreground" aria-hidden="true">
|
||||||
·
|
·
|
||||||
</span>
|
</span>
|
||||||
<span className={overdue ? 'text-amber-800' : 'text-muted-foreground'}>
|
<span className={overdue ? 'text-amber-800' : 'text-muted-foreground'}>
|
||||||
{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')}`}
|
{overdue && ` · ${t('tasks.OVERDUE')}`}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -290,8 +304,8 @@ export function TaskRow({ task, compact = false }: { task: Task; compact?: boole
|
|||||||
<span className="inline-flex items-center gap-1">
|
<span className="inline-flex items-center gap-1">
|
||||||
<Bell className="size-3" aria-hidden="true" />
|
<Bell className="size-3" aria-hidden="true" />
|
||||||
{new Date(task.remindAt).getTime() <= Date.now()
|
{new Date(task.remindAt).getTime() <= Date.now()
|
||||||
? t('tasks.reminderDue')
|
? `${t('tasks.reminderDue')} · ${f.dateTime(task.remindAt)}`
|
||||||
: `${t('tasks.reminder')}: ${f.date(task.remindAt)}`}
|
: `${t('tasks.reminder')}: ${f.dateTime(task.remindAt)}`}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { ReminderInbox } from './reminders';
|
||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { NavLink, Navigate, Outlet, useLocation, useNavigate } from 'react-router';
|
import { NavLink, Navigate, Outlet, useLocation, useNavigate } from 'react-router';
|
||||||
import { useQuery, useMutation } from '@tanstack/react-query';
|
import { useQuery, useMutation } from '@tanstack/react-query';
|
||||||
@@ -171,6 +172,7 @@ function AuthenticatedShell({ user }: { user: User }) {
|
|||||||
<span className="hidden text-xs text-muted-foreground xl:block">
|
<span className="hidden text-xs text-muted-foreground xl:block">
|
||||||
{f.date(new Date())}
|
{f.date(new Date())}
|
||||||
</span>
|
</span>
|
||||||
|
<ReminderInbox />
|
||||||
<LanguageSwitch />
|
<LanguageSwitch />
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|||||||
@@ -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 && (
|
||||||
|
<p role="status" className="text-sm">
|
||||||
|
{t('operations.versionLoaded')}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{refreshError && <p role="alert">{t('common.errorTitle')}</p>}
|
||||||
|
{action.error instanceof ApiError && action.error.status === 409 && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
type="button"
|
||||||
|
onClick={async () => {
|
||||||
|
try {
|
||||||
|
const latest = await api(`/merchants/${merchant.id}`, merchantDetailSchema);
|
||||||
|
setVersion(latest.version);
|
||||||
|
setRefreshed(true);
|
||||||
|
setRefreshError(false);
|
||||||
|
action.reset();
|
||||||
|
} catch {
|
||||||
|
setRefreshError(true);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t('operations.reloadVersion')}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<Editor
|
||||||
|
title={t(task ? 'workflow.editTask' : 'workflow.addTask')}
|
||||||
|
description={`${t('operations.assignee', { name: assignee })} · ${t('operations.timeZone', { zone: viewerTimeZone() })}`}
|
||||||
|
fields={[
|
||||||
|
{ name: 'title' },
|
||||||
|
{ name: 'dueAt', type: 'datetime-local' },
|
||||||
|
{ name: 'remindAt', type: 'datetime-local' },
|
||||||
|
{
|
||||||
|
name: 'status',
|
||||||
|
options: ['OPEN', 'DONE'].map((value) => ({ 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<Task | null>(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 (
|
||||||
|
<div id={`task-${task.id}`} className="border-t first:border-0 scroll-mt-5">
|
||||||
|
<TaskRow task={task} />
|
||||||
|
<div className="flex flex-wrap items-center gap-2 px-5 pb-4">
|
||||||
|
{task.capabilities.edit && (
|
||||||
|
<Button variant="outline" onClick={() => setEditing(task)}>
|
||||||
|
{t('workflow.editTask')}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{task.capabilities.complete && (
|
||||||
|
<Button variant="ghost" disabled={action.isPending} onClick={() => changeStatus('DONE')}>
|
||||||
|
{t('workflow.complete')}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{task.capabilities.reopen && (
|
||||||
|
<Button variant="ghost" disabled={action.isPending} onClick={() => changeStatus('OPEN')}>
|
||||||
|
{t('operations.reopen')}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{action.feedback}
|
||||||
|
</div>
|
||||||
|
{editing && (
|
||||||
|
<TaskEditor
|
||||||
|
merchant={editing.merchant}
|
||||||
|
task={editing}
|
||||||
|
assignee={editing.assignee.name}
|
||||||
|
close={() => setEditing(null)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function TaskComposer({ merchant, close }: { merchant?: MerchantDetail; close: () => void }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const user = useOutletContext<User>();
|
||||||
|
const [search, setSearch] = useState('');
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [selected, setSelected] = useState<string | null>(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 (
|
||||||
|
<TaskEditor
|
||||||
|
merchant={current}
|
||||||
|
assignee={
|
||||||
|
user.role === 'COMPLIANCE_OFFICER' ? user.name : (current.owner?.name ?? user.name)
|
||||||
|
}
|
||||||
|
close={close}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<Sheet
|
||||||
|
open
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
if (!open) close();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<SheetContent closeLabel={t('common.close')} className="overflow-y-auto p-6">
|
||||||
|
<SheetTitle>{t('operations.chooseMerchant')}</SheetTitle>
|
||||||
|
<SheetDescription>{t('operations.ownerRule')}</SheetDescription>
|
||||||
|
{selected ? (
|
||||||
|
<QueryBoundary query={detail}>{() => null}</QueryBoundary>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Input
|
||||||
|
aria-label={t('operations.searchMerchant')}
|
||||||
|
value={search}
|
||||||
|
onChange={(e) => {
|
||||||
|
setSearch(e.target.value);
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<QueryBoundary query={directory}>
|
||||||
|
{(data) => (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{data.items.map((m) => (
|
||||||
|
<Button
|
||||||
|
key={m.id}
|
||||||
|
variant="outline"
|
||||||
|
className="h-auto w-full justify-start whitespace-normal py-3 text-left"
|
||||||
|
onClick={() => setSelected(m.id)}
|
||||||
|
>
|
||||||
|
{m.name}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
{!data.items.length && <EmptyState title={t('common.noResults')} />}
|
||||||
|
<div className="flex justify-between gap-2">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
disabled={data.page <= 1}
|
||||||
|
onClick={() => setPage((p) => p - 1)}
|
||||||
|
>
|
||||||
|
{t('common.previous')}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
disabled={data.page * data.pageSize >= data.total}
|
||||||
|
onClick={() => setPage((p) => p + 1)}
|
||||||
|
>
|
||||||
|
{t('common.next')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</QueryBoundary>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</SheetContent>
|
||||||
|
</Sheet>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
export function MerchantTasks({ merchant }: { merchant: MerchantDetail }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [creating, setCreating] = useState(false);
|
||||||
|
return (
|
||||||
|
<section id="tasks" className="surface">
|
||||||
|
<SectionHeader
|
||||||
|
title={t('merchants.tasks')}
|
||||||
|
description={t('operations.ownerRule')}
|
||||||
|
action={
|
||||||
|
<Button variant="outline" onClick={() => setCreating(true)}>
|
||||||
|
{t('workflow.addTask')}
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{merchant.tasks.length ? (
|
||||||
|
merchant.tasks.map((task) => <ActionableTask key={task.id} task={task} />)
|
||||||
|
) : (
|
||||||
|
<EmptyState title={t('operations.noTasks')} />
|
||||||
|
)}
|
||||||
|
{creating && <TaskComposer merchant={merchant} close={() => setCreating(false)} />}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
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 (
|
||||||
|
<>
|
||||||
|
<PageHeader
|
||||||
|
title={t('tasks.title')}
|
||||||
|
description={`${t(`operations.${hint}`)} ${t('operations.timeZone', { zone: viewerTimeZone() })}`}
|
||||||
|
action={<Button onClick={() => setCreating(true)}>{t('workflow.addTask')}</Button>}
|
||||||
|
/>
|
||||||
|
<section className="surface overflow-hidden">
|
||||||
|
<div
|
||||||
|
role="group"
|
||||||
|
aria-label={t('tasks.filter')}
|
||||||
|
className="flex flex-wrap gap-1 border-b p-3"
|
||||||
|
>
|
||||||
|
{taskFilters.map((value) => (
|
||||||
|
<Button
|
||||||
|
key={value}
|
||||||
|
variant="ghost"
|
||||||
|
aria-pressed={filter === value}
|
||||||
|
className={filter === value ? 'bg-secondary' : ''}
|
||||||
|
onClick={() => {
|
||||||
|
const next = new URLSearchParams(params);
|
||||||
|
next.set('filter', value);
|
||||||
|
setParams(next);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t(`tasks.${value}`)}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
{(params.has('merchantId') || params.has('assigneeId')) && (
|
||||||
|
<Button variant="outline" onClick={() => setParams({ filter })}>
|
||||||
|
{t('common.clear')}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<QueryBoundary query={query}>
|
||||||
|
{(tasks) =>
|
||||||
|
tasks.length ? (
|
||||||
|
tasks.map((task) => <ActionableTask task={task} key={task.id} />)
|
||||||
|
) : (
|
||||||
|
<EmptyState
|
||||||
|
title={t('operations.noTasks')}
|
||||||
|
description={t('operations.noTasksHint')}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
</QueryBoundary>
|
||||||
|
</section>
|
||||||
|
{creating && <TaskComposer close={() => setCreating(false)} />}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -5,7 +5,16 @@ export function directoryParams(input: URLSearchParams, role: Role) {
|
|||||||
const search = input.get('search')?.slice(0, 100);
|
const search = input.get('search')?.slice(0, 100);
|
||||||
// Preserve typing whitespace; the server normalizes the search term.
|
// Preserve typing whitespace; the server normalizes the search term.
|
||||||
if (search) result.set('search', search);
|
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;
|
if (key === 'ownerId' && role === 'ACCOUNT_MANAGER') continue;
|
||||||
const raw = input.get(key);
|
const raw = input.get(key);
|
||||||
if (!raw) continue;
|
if (!raw) continue;
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -3,9 +3,17 @@ export function reviewParams(input: URLSearchParams) {
|
|||||||
const result = new URLSearchParams();
|
const result = new URLSearchParams();
|
||||||
const search = input.get('search')?.slice(0, 100);
|
const search = input.get('search')?.slice(0, 100);
|
||||||
if (search) result.set('search', search);
|
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);
|
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;
|
return result;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
|
import { operationsEn, operationsRu } from './task-dashboard-locales';
|
||||||
import { onboardingEn, onboardingRu } from './onboarding-locales';
|
import { onboardingEn, onboardingRu } from './onboarding-locales';
|
||||||
import { salesEn, salesRu } from './sales-locales';
|
import { salesEn, salesRu } from './sales-locales';
|
||||||
import { workflowEn, workflowRu } from './workflow-locales';
|
import { workflowEn, workflowRu } from './workflow-locales';
|
||||||
import { landingEn, landingRu } from './landing-locales';
|
import { landingEn, landingRu } from './landing-locales';
|
||||||
export const en = {
|
export const en = {
|
||||||
|
operations: operationsEn,
|
||||||
onboarding: onboardingEn,
|
onboarding: onboardingEn,
|
||||||
workflow: workflowEn,
|
workflow: workflowEn,
|
||||||
workspace: salesEn,
|
workspace: salesEn,
|
||||||
@@ -204,6 +206,7 @@ export const en = {
|
|||||||
stageCount: '{{number}} of 8 stages',
|
stageCount: '{{number}} of 8 stages',
|
||||||
},
|
},
|
||||||
tasks: {
|
tasks: {
|
||||||
|
TODAY: 'Today',
|
||||||
title: 'Tasks',
|
title: 'Tasks',
|
||||||
description: 'A little structure for the next right step.',
|
description: 'A little structure for the next right step.',
|
||||||
ALL: 'All tasks',
|
ALL: 'All tasks',
|
||||||
@@ -236,6 +239,7 @@ export const en = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
export const ru = {
|
export const ru = {
|
||||||
|
operations: operationsRu,
|
||||||
onboarding: onboardingRu,
|
onboarding: onboardingRu,
|
||||||
workflow: workflowRu,
|
workflow: workflowRu,
|
||||||
workspace: salesRu,
|
workspace: salesRu,
|
||||||
@@ -440,6 +444,7 @@ export const ru = {
|
|||||||
stageCount: '{{number}} из 8 этапов',
|
stageCount: '{{number}} из 8 этапов',
|
||||||
},
|
},
|
||||||
tasks: {
|
tasks: {
|
||||||
|
TODAY: 'Сегодня',
|
||||||
title: 'Задачи',
|
title: 'Задачи',
|
||||||
description: 'Немного порядка для следующего верного шага.',
|
description: 'Немного порядка для следующего верного шага.',
|
||||||
ALL: 'Все задачи',
|
ALL: 'Все задачи',
|
||||||
|
|||||||
+67
-210
@@ -6,7 +6,6 @@ import {
|
|||||||
ReviewHistory,
|
ReviewHistory,
|
||||||
InteractionHistory,
|
InteractionHistory,
|
||||||
MerchantTasks,
|
MerchantTasks,
|
||||||
RecentInteractions,
|
|
||||||
} from '../components/merchant-workflow';
|
} from '../components/merchant-workflow';
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { Link, useLocation, useOutletContext, useParams, useSearchParams } from 'react-router';
|
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 { useTranslation } from 'react-i18next';
|
||||||
import {
|
import {
|
||||||
ArrowRight,
|
ArrowRight,
|
||||||
ArrowUpRight,
|
|
||||||
ArrowLeft,
|
ArrowLeft,
|
||||||
Building2,
|
|
||||||
ShieldCheck,
|
|
||||||
Clock3,
|
Clock3,
|
||||||
Activity,
|
|
||||||
Search,
|
Search,
|
||||||
ChevronLeft,
|
ChevronLeft,
|
||||||
ChevronRight,
|
ChevronRight,
|
||||||
@@ -31,19 +26,15 @@ import {
|
|||||||
LoaderCircle,
|
LoaderCircle,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import {
|
import {
|
||||||
dashboardSchema,
|
|
||||||
merchantListSchema,
|
merchantListSchema,
|
||||||
merchantDetailSchema,
|
merchantDetailSchema,
|
||||||
reviewQueueSchema,
|
reviewQueueSchema,
|
||||||
pipelineBoardSchema,
|
pipelineBoardSchema,
|
||||||
merchantFiltersSchema,
|
merchantFiltersSchema,
|
||||||
taskListSchema,
|
|
||||||
statuses,
|
statuses,
|
||||||
statusSchema,
|
statusSchema,
|
||||||
taskFilters,
|
|
||||||
canSeeReviewQueue,
|
canSeeReviewQueue,
|
||||||
type User,
|
type User,
|
||||||
type TaskFilter,
|
|
||||||
type Merchant,
|
type Merchant,
|
||||||
} from '@merchantflow/contracts';
|
} from '@merchantflow/contracts';
|
||||||
import { Input } from '@merchantflow/ui/components/input';
|
import { Input } from '@merchantflow/ui/components/input';
|
||||||
@@ -70,154 +61,11 @@ import {
|
|||||||
Button,
|
Button,
|
||||||
StatusBadge,
|
StatusBadge,
|
||||||
Avatar,
|
Avatar,
|
||||||
TaskRow,
|
|
||||||
MerchantCard,
|
MerchantCard,
|
||||||
EmptyState,
|
EmptyState,
|
||||||
stageColors,
|
stageColors,
|
||||||
} from '../components/shared';
|
} from '../components/shared';
|
||||||
export function Dashboard() {
|
export { Dashboard } from '../components/dashboard';
|
||||||
const { t } = useTranslation();
|
|
||||||
const f = useFormat();
|
|
||||||
const user = useOutletContext<User>();
|
|
||||||
const query = useQuery({
|
|
||||||
queryKey: ['dashboard'],
|
|
||||||
queryFn: ({ signal }) => api('/dashboard', dashboardSchema, { signal }),
|
|
||||||
});
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<PageHeader
|
|
||||||
title={t('dashboard.title')}
|
|
||||||
description={t('dashboard.description')}
|
|
||||||
eyebrow={t('dashboard.eyebrow')}
|
|
||||||
action={
|
|
||||||
<LinkButton to="/app/merchants">
|
|
||||||
{t('dashboard.view')}
|
|
||||||
<ArrowUpRight className="size-4" />
|
|
||||||
</LinkButton>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<QueryBoundary query={query}>
|
|
||||||
{(data) => (
|
|
||||||
<div className="space-y-6">
|
|
||||||
<div className="grid grid-cols-1 gap-3 min-[360px]:grid-cols-2 xl:grid-cols-4">
|
|
||||||
{[
|
|
||||||
{ 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) => (
|
|
||||||
<section key={key} className="surface p-5">
|
|
||||||
<div className="flex items-center justify-between gap-2">
|
|
||||||
<h2 className="text-xs font-medium text-muted-foreground">
|
|
||||||
{t(`dashboard.${key}`)}
|
|
||||||
</h2>
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'flex size-8 shrink-0 items-center justify-center rounded-lg',
|
|
||||||
i === 0 ? 'bg-[#edf4de] text-[#526a2e]' : 'bg-muted text-muted-foreground',
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<Icon className="size-4" aria-hidden="true" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<p className="mb-2 mt-4 text-[32px] font-semibold leading-none tracking-tight tabular-nums">
|
|
||||||
{f.number(value)}
|
|
||||||
</p>
|
|
||||||
<p className="mt-3 text-[11px] text-muted-foreground">
|
|
||||||
{t(`dashboard.${key}Hint`)}
|
|
||||||
</p>
|
|
||||||
</section>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<section className="surface">
|
|
||||||
<SectionHeader
|
|
||||||
title={t('dashboard.pipeline')}
|
|
||||||
description={t('dashboard.pipelineText')}
|
|
||||||
action={
|
|
||||||
<LinkButton to="/app/pipeline" variant="ghost" className="text-xs">
|
|
||||||
{t('dashboard.openPipeline')}
|
|
||||||
<ArrowRight className="size-3.5" />
|
|
||||||
</LinkButton>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<div className="px-5 pb-6 pt-6 sm:px-6">
|
|
||||||
<div
|
|
||||||
className="mb-5 flex h-3 gap-1 overflow-hidden rounded-full"
|
|
||||||
aria-hidden="true"
|
|
||||||
>
|
|
||||||
{data.distribution
|
|
||||||
.filter((s) => s.status !== 'REJECTED' && s.count > 0)
|
|
||||||
.map((s) => (
|
|
||||||
<div
|
|
||||||
key={s.status}
|
|
||||||
style={{ flex: s.count, backgroundColor: stageColors[s.status] }}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<div className="grid grid-cols-2 gap-x-4 gap-y-4 sm:grid-cols-4 xl:grid-cols-8">
|
|
||||||
{data.distribution
|
|
||||||
.filter((s) => s.status !== 'REJECTED')
|
|
||||||
.map((s) => (
|
|
||||||
<Link
|
|
||||||
to={`/app/merchants?status=${s.status}`}
|
|
||||||
key={s.status}
|
|
||||||
className="flex min-h-11 flex-col justify-center gap-2 rounded-md"
|
|
||||||
>
|
|
||||||
<span className="flex items-start gap-1.5 text-[10px] leading-tight text-muted-foreground">
|
|
||||||
<span
|
|
||||||
style={{ backgroundColor: stageColors[s.status] }}
|
|
||||||
className="mt-0.5 size-1.5 shrink-0 rounded-full"
|
|
||||||
/>
|
|
||||||
{t(`statuses.${s.status}`)}
|
|
||||||
</span>
|
|
||||||
<span className="pl-3 text-lg font-semibold tabular-nums">
|
|
||||||
{f.number(s.count)}
|
|
||||||
</span>
|
|
||||||
</Link>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
<div className="grid gap-6 xl:grid-cols-[1.12fr_1fr]">
|
|
||||||
<section className="surface">
|
|
||||||
<SectionHeader
|
|
||||||
title={t('dashboard.activity')}
|
|
||||||
description={t('dashboard.activityText')}
|
|
||||||
/>
|
|
||||||
<RecentInteractions activities={data.recentActivities} />
|
|
||||||
</section>
|
|
||||||
<section className="surface self-start">
|
|
||||||
<SectionHeader
|
|
||||||
title={t('dashboard.priorities')}
|
|
||||||
description={t('dashboard.prioritiesText')}
|
|
||||||
action={
|
|
||||||
<LinkButton to="/app/tasks" variant="ghost" className="text-xs">
|
|
||||||
{t('common.viewAll')}
|
|
||||||
<ArrowRight className="size-3.5" />
|
|
||||||
</LinkButton>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<div className="mt-4">
|
|
||||||
{data.upcomingTasks.length ? (
|
|
||||||
data.upcomingTasks.map((task) => <TaskRow key={task.id} task={task} compact />)
|
|
||||||
) : (
|
|
||||||
<EmptyState title={t('tasks.empty')} />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="m-5 flex items-center gap-2 rounded-lg bg-[#f6f8f1] p-3 text-[11px] text-muted-foreground">
|
|
||||||
<ShieldCheck className="size-4 shrink-0 text-[#617d37]" aria-hidden="true" />
|
|
||||||
{t(
|
|
||||||
`dashboard.${user.role === 'HEAD_OF_SALES' ? 'scopeHead' : user.role === 'COMPLIANCE_OFFICER' ? 'scopeCompliance' : 'scopeManager'}`,
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</QueryBoundary>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
function useDebounced(value: string) {
|
function useDebounced(value: string) {
|
||||||
const [debounced, setDebounced] = useState(value);
|
const [debounced, setDebounced] = useState(value);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -469,6 +317,23 @@ export function Merchants() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{(normalized.has('cohort') ||
|
||||||
|
normalized.has('createdFrom') ||
|
||||||
|
normalized.has('createdTo')) && (
|
||||||
|
<div className="border-b px-5 py-3 text-sm text-muted-foreground">
|
||||||
|
{normalized.get('cohort') && <p>{t(`operations.${normalized.get('cohort')}`)}</p>}
|
||||||
|
{(normalized.has('createdFrom') || normalized.has('createdTo')) && (
|
||||||
|
<p>
|
||||||
|
{t('operations.createdWindow', {
|
||||||
|
from: normalized.get('createdFrom')
|
||||||
|
? f.dateTime(normalized.get('createdFrom')!)
|
||||||
|
: '—',
|
||||||
|
to: normalized.get('createdTo') ? f.dateTime(normalized.get('createdTo')!) : '—',
|
||||||
|
})}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{filters.isError && (
|
{filters.isError && (
|
||||||
<div role="alert" className="px-5 py-3 text-sm">
|
<div role="alert" className="px-5 py-3 text-sm">
|
||||||
{t('common.errorTitle')}{' '}
|
{t('common.errorTitle')}{' '}
|
||||||
@@ -880,54 +745,7 @@ export function Pipeline() {
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function Tasks() {
|
export { Tasks } from '../components/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 (
|
|
||||||
<>
|
|
||||||
<PageHeader title={t('tasks.title')} description={t('tasks.description')} />
|
|
||||||
<section className="surface overflow-hidden">
|
|
||||||
<div
|
|
||||||
className="flex flex-wrap gap-1 border-b p-3"
|
|
||||||
role="group"
|
|
||||||
aria-label={t('tasks.filter')}
|
|
||||||
>
|
|
||||||
{taskFilters.map((s) => (
|
|
||||||
<Button
|
|
||||||
key={s}
|
|
||||||
variant="ghost"
|
|
||||||
aria-pressed={filter === s}
|
|
||||||
onClick={() => setParams(s === 'ALL' ? {} : { filter: s }, { replace: true })}
|
|
||||||
className={cn('text-xs', filter === s && 'bg-secondary')}
|
|
||||||
>
|
|
||||||
{t(`tasks.${s}`)}
|
|
||||||
</Button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<QueryBoundary query={query}>
|
|
||||||
{(tasks) =>
|
|
||||||
tasks.length ? (
|
|
||||||
<div>
|
|
||||||
{tasks.map((task) => (
|
|
||||||
<TaskRow key={task.id} task={task} />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<EmptyState title={t('tasks.empty')} description={t('tasks.emptyText')} />
|
|
||||||
)
|
|
||||||
}
|
|
||||||
</QueryBoundary>
|
|
||||||
</section>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
export function ReviewQueue() {
|
export function ReviewQueue() {
|
||||||
const user = useOutletContext<User>();
|
const user = useOutletContext<User>();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -935,6 +753,7 @@ export function ReviewQueue() {
|
|||||||
const [params, setParams] = useSearchParams();
|
const [params, setParams] = useSearchParams();
|
||||||
const filters = reviewParams(params);
|
const filters = reviewParams(params);
|
||||||
const serialized = filters.toString();
|
const serialized = filters.toString();
|
||||||
|
const decided = filters.get('view') === 'DECISIONS';
|
||||||
const allowed = canSeeReviewQueue(user.role);
|
const allowed = canSeeReviewQueue(user.role);
|
||||||
const query = useQuery({
|
const query = useQuery({
|
||||||
queryKey: ['review-queue', serialized],
|
queryKey: ['review-queue', serialized],
|
||||||
@@ -951,10 +770,38 @@ export function ReviewQueue() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title={t('review.title')}
|
title={t(decided ? 'operations.decisionHistory' : 'review.title')}
|
||||||
description={t('review.description')}
|
description={t('review.description')}
|
||||||
eyebrow={t('review.eyebrow')}
|
eyebrow={t('review.eyebrow')}
|
||||||
/>
|
/>
|
||||||
|
<div
|
||||||
|
className="mb-4 flex flex-wrap gap-2"
|
||||||
|
role="group"
|
||||||
|
aria-label={t('operations.decisionHistory')}
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
variant={decided ? 'ghost' : 'outline'}
|
||||||
|
aria-pressed={!decided}
|
||||||
|
onClick={() => setParams({})}
|
||||||
|
>
|
||||||
|
{t('operations.pending')}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={decided ? 'outline' : 'ghost'}
|
||||||
|
aria-pressed={decided}
|
||||||
|
onClick={() => setParams({ view: 'DECISIONS' })}
|
||||||
|
>
|
||||||
|
{t('operations.decisionHistory')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{decided && (filters.has('decidedFrom') || filters.has('decidedTo')) && (
|
||||||
|
<p className="mb-4 text-sm text-muted-foreground">
|
||||||
|
{t('operations.decisionWindow', {
|
||||||
|
from: filters.get('decidedFrom') ? f.dateTime(filters.get('decidedFrom')!) : '—',
|
||||||
|
to: filters.get('decidedTo') ? f.dateTime(filters.get('decidedTo')!) : '—',
|
||||||
|
})}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
<section aria-label={t('onboarding.queueFilters')} className="mb-5 grid gap-3 sm:grid-cols-3">
|
<section aria-label={t('onboarding.queueFilters')} className="mb-5 grid gap-3 sm:grid-cols-3">
|
||||||
<label className="space-y-2 text-xs text-muted-foreground">
|
<label className="space-y-2 text-xs text-muted-foreground">
|
||||||
<span>{t('onboarding.search')}</span>
|
<span>{t('onboarding.search')}</span>
|
||||||
@@ -981,17 +828,23 @@ export function ReviewQueue() {
|
|||||||
</NativeSelect>
|
</NativeSelect>
|
||||||
</label>
|
</label>
|
||||||
<label className="space-y-2 text-xs text-muted-foreground">
|
<label className="space-y-2 text-xs text-muted-foreground">
|
||||||
<span>{t('onboarding.waitingTime')}</span>
|
<span>{t(decided ? 'workflow.decision' : 'onboarding.waitingTime')}</span>
|
||||||
<NativeSelect
|
<NativeSelect
|
||||||
className="w-full"
|
className="w-full"
|
||||||
value={filters.get('waiting') ?? 'ALL'}
|
value={filters.get(decided ? 'decision' : 'waiting') ?? 'ALL'}
|
||||||
onChange={(event) => update('waiting', event.target.value)}
|
onChange={(event) => update(decided ? 'decision' : 'waiting', event.target.value)}
|
||||||
>
|
>
|
||||||
{['ALL', '24', '72'].map((value) => (
|
{(decided ? ['ALL', 'APPROVED', 'CORRECTIONS', 'REJECTED'] : ['ALL', '24', '72']).map(
|
||||||
|
(value) => (
|
||||||
<option key={value} value={value}>
|
<option key={value} value={value}>
|
||||||
{t(`onboarding.waiting.${value}`)}
|
{t(
|
||||||
|
decided && value !== 'ALL'
|
||||||
|
? `workflow.${value}`
|
||||||
|
: `onboarding.waiting.${value}`,
|
||||||
|
)}
|
||||||
</option>
|
</option>
|
||||||
))}
|
),
|
||||||
|
)}
|
||||||
</NativeSelect>
|
</NativeSelect>
|
||||||
</label>
|
</label>
|
||||||
</section>
|
</section>
|
||||||
@@ -1009,7 +862,7 @@ export function ReviewQueue() {
|
|||||||
</div>
|
</div>
|
||||||
<span className="inline-flex items-center gap-2 text-xs text-muted-foreground">
|
<span className="inline-flex items-center gap-2 text-xs text-muted-foreground">
|
||||||
<Clock3 className="size-4" />
|
<Clock3 className="size-4" />
|
||||||
{t('review.order')}
|
{t(decided ? 'operations.decisionHistory' : 'review.order')}
|
||||||
</span>
|
</span>
|
||||||
{serialized && (
|
{serialized && (
|
||||||
<Button variant="ghost" onClick={() => setParams({})}>
|
<Button variant="ghost" onClick={() => setParams({})}>
|
||||||
@@ -1042,10 +895,14 @@ export function ReviewQueue() {
|
|||||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||||
<div>
|
<div>
|
||||||
<p className="text-sm">
|
<p className="text-sm">
|
||||||
|
{decided ? (
|
||||||
|
t(`workflow.${review.decision}`)
|
||||||
|
) : (
|
||||||
<StageAge since={review.submittedAt} waiting />
|
<StageAge since={review.submittedAt} waiting />
|
||||||
|
)}
|
||||||
</p>
|
</p>
|
||||||
<p className="mt-1 text-xs text-muted-foreground">
|
<p className="mt-1 text-xs text-muted-foreground">
|
||||||
{f.dateTime(review.submittedAt)}
|
{f.dateTime(review.decidedAt ?? review.submittedAt)}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<LinkButton
|
<LinkButton
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
export const operationsEn = {
|
||||||
|
headTitle: 'Portfolio overview',
|
||||||
|
managerTitle: 'My merchant workspace',
|
||||||
|
complianceTitle: 'Review workspace',
|
||||||
|
headDescription: 'Portfolio health, team workload, and the next actions that need attention.',
|
||||||
|
managerDescription: 'Your assigned merchants, overdue follow-ups, and next actions.',
|
||||||
|
complianceDescription: 'Waiting reviews, recent decisions, and your personal review tasks.',
|
||||||
|
total: 'Total merchants',
|
||||||
|
newLeads: 'New leads · 30 days',
|
||||||
|
active: 'Active onboarding',
|
||||||
|
live: 'Live merchants',
|
||||||
|
newHint: 'Created in the last 30 days, including merchants that have advanced.',
|
||||||
|
activeHint: 'KYB, Compliance Review, Integration, and Testing.',
|
||||||
|
unassigned: 'Unassigned leads',
|
||||||
|
activation: 'Activation rate',
|
||||||
|
activationHint: '{{live}} Live / {{total}} visible merchants, including Rejected.',
|
||||||
|
duration: 'Average onboarding duration',
|
||||||
|
durationHint: 'Creation to first Live transition · {{count}} merchants.',
|
||||||
|
days: '{{value}} days',
|
||||||
|
noMerchants: 'No merchants yet',
|
||||||
|
noLive: 'No recorded Live transitions yet',
|
||||||
|
workload: 'Manager workload',
|
||||||
|
ownWorkload: 'My workload',
|
||||||
|
assigned: 'Assigned merchants',
|
||||||
|
openTasks: 'Open tasks',
|
||||||
|
next: 'Next actions',
|
||||||
|
nextHint: 'Open tasks ordered by due time, with overdue follow-ups first.',
|
||||||
|
overdue: 'Overdue tasks',
|
||||||
|
noTasks: 'No tasks in this view',
|
||||||
|
noTasksHint: 'Create a task or choose another view.',
|
||||||
|
pending: 'Pending reviews',
|
||||||
|
oldest: 'Oldest waiting reviews',
|
||||||
|
decisions: 'Decisions · 30 days',
|
||||||
|
decisionsHint: 'Review cycles decided in the last 30 days, including corrections.',
|
||||||
|
decisionHistory: 'Decision history',
|
||||||
|
noReviews: 'No reviews waiting',
|
||||||
|
reviewTasks: 'My review tasks',
|
||||||
|
allTasks: 'All tasks',
|
||||||
|
today: 'Today',
|
||||||
|
reopen: 'Reopen task',
|
||||||
|
merchant: 'Merchant',
|
||||||
|
chooseMerchant: 'Choose a merchant',
|
||||||
|
searchMerchant: 'Search merchants',
|
||||||
|
assignee: 'Assignee: {{name}}',
|
||||||
|
ownerRule: 'Sales tasks follow the merchant owner. Review tasks belong to you.',
|
||||||
|
timeZone: 'Times shown in {{zone}}',
|
||||||
|
reloadVersion: 'Load current version',
|
||||||
|
versionLoaded: 'Current version loaded. Review your changes before saving.',
|
||||||
|
reminders: 'Reminders',
|
||||||
|
remindersCount: 'Reminders ({{count}})',
|
||||||
|
dismiss: 'Dismiss reminder',
|
||||||
|
inboxDescription: 'Scheduled reminders for your open tasks. Dismissals are saved across visits.',
|
||||||
|
noReminders: 'You’re all caught up',
|
||||||
|
noRemindersHint: 'Reminders appear here when their scheduled time arrives.',
|
||||||
|
remindersError: 'Reminders could not be refreshed. Try again.',
|
||||||
|
upcomingHint: 'Open tasks due tomorrow or later.',
|
||||||
|
todayHint: 'Open tasks due today in your time zone, including overdue tasks.',
|
||||||
|
overdueHint: 'Open tasks whose due time has passed.',
|
||||||
|
completedHint: 'Completed tasks, with their recorded assignee and completion time.',
|
||||||
|
cohort: 'Dashboard filter',
|
||||||
|
createdWindow: 'Created: {{from}} – {{to}}',
|
||||||
|
ACTIVE_ONBOARDING: 'Active onboarding',
|
||||||
|
REACHED_LIVE: 'Recorded Live transition',
|
||||||
|
decisionWindow: 'Decided: {{from}} – {{to}}',
|
||||||
|
noActivity: 'No activity yet',
|
||||||
|
personal: 'Your personal review tasks',
|
||||||
|
};
|
||||||
|
export const operationsRu: typeof operationsEn = {
|
||||||
|
headTitle: 'Обзор портфеля',
|
||||||
|
managerTitle: 'Мои мерчанты',
|
||||||
|
complianceTitle: 'Проверки комплаенса',
|
||||||
|
headDescription: 'Состояние портфеля, загрузка команды и ближайшие действия.',
|
||||||
|
managerDescription: 'Закреплённые мерчанты, просроченные задачи и ближайшие действия.',
|
||||||
|
complianceDescription: 'Ожидающие проверки, недавние решения и ваши личные задачи.',
|
||||||
|
total: 'Всего мерчантов',
|
||||||
|
newLeads: 'Новые лиды · 30 дней',
|
||||||
|
active: 'Активный онбординг',
|
||||||
|
live: 'Мерчанты Live',
|
||||||
|
newHint: 'Созданы за последние 30 дней, включая перешедших на следующие этапы.',
|
||||||
|
activeHint: 'KYB, проверка комплаенса, интеграция и тестирование.',
|
||||||
|
unassigned: 'Лиды без менеджера',
|
||||||
|
activation: 'Доля активации',
|
||||||
|
activationHint: '{{live}} Live / {{total}} доступных мерчантов, включая отклонённых.',
|
||||||
|
duration: 'Среднее время онбординга',
|
||||||
|
durationHint: 'От создания до первого перехода в Live · {{count}} мерчантов.',
|
||||||
|
days: '{{value}} дн.',
|
||||||
|
noMerchants: 'Пока нет мерчантов',
|
||||||
|
noLive: 'Переходов в Live пока нет',
|
||||||
|
workload: 'Загрузка менеджеров',
|
||||||
|
ownWorkload: 'Моя загрузка',
|
||||||
|
assigned: 'Закреплённые мерчанты',
|
||||||
|
openTasks: 'Открытые задачи',
|
||||||
|
next: 'Следующие действия',
|
||||||
|
nextHint: 'Открытые задачи по сроку выполнения, сначала просроченные.',
|
||||||
|
overdue: 'Просроченные задачи',
|
||||||
|
noTasks: 'В этом разделе нет задач',
|
||||||
|
noTasksHint: 'Создайте задачу или выберите другой раздел.',
|
||||||
|
pending: 'Ожидающие проверки',
|
||||||
|
oldest: 'Дольше всего ожидают',
|
||||||
|
decisions: 'Решения · 30 дней',
|
||||||
|
decisionsHint: 'Циклы проверки с решением за последние 30 дней, включая исправления.',
|
||||||
|
decisionHistory: 'История решений',
|
||||||
|
noReviews: 'Нет ожидающих проверок',
|
||||||
|
reviewTasks: 'Мои задачи по проверкам',
|
||||||
|
allTasks: 'Все задачи',
|
||||||
|
today: 'Сегодня',
|
||||||
|
reopen: 'Открыть задачу снова',
|
||||||
|
merchant: 'Мерчант',
|
||||||
|
chooseMerchant: 'Выберите мерчанта',
|
||||||
|
searchMerchant: 'Поиск мерчантов',
|
||||||
|
assignee: 'Исполнитель: {{name}}',
|
||||||
|
ownerRule: 'Задачи продаж следуют за менеджером мерчанта. Задачи по проверкам принадлежат вам.',
|
||||||
|
timeZone: 'Время указано для {{zone}}',
|
||||||
|
reloadVersion: 'Загрузить текущую версию',
|
||||||
|
versionLoaded: 'Текущая версия загружена. Проверьте изменения перед сохранением.',
|
||||||
|
reminders: 'Напоминания',
|
||||||
|
remindersCount: 'Напоминания ({{count}})',
|
||||||
|
dismiss: 'Скрыть напоминание',
|
||||||
|
inboxDescription:
|
||||||
|
'Запланированные напоминания об открытых задачах. Скрытые напоминания сохраняются между посещениями.',
|
||||||
|
noReminders: 'Всё под контролем',
|
||||||
|
noRemindersHint: 'Напоминания появятся здесь в запланированное время.',
|
||||||
|
remindersError: 'Не удалось обновить напоминания. Попробуйте снова.',
|
||||||
|
upcomingHint: 'Открытые задачи со сроком завтра или позже.',
|
||||||
|
todayHint: 'Открытые задачи на сегодня по вашему часовому поясу, включая просроченные.',
|
||||||
|
overdueHint: 'Открытые задачи, срок которых уже прошёл.',
|
||||||
|
completedHint: 'Завершённые задачи с сохранённым исполнителем и временем завершения.',
|
||||||
|
cohort: 'Фильтр обзора',
|
||||||
|
createdWindow: 'Созданы: {{from}} – {{to}}',
|
||||||
|
ACTIVE_ONBOARDING: 'Активный онбординг',
|
||||||
|
REACHED_LIVE: 'Зафиксирован переход в Live',
|
||||||
|
decisionWindow: 'Решения: {{from}} – {{to}}',
|
||||||
|
noActivity: 'Пока нет активности',
|
||||||
|
personal: 'Ваши личные задачи по проверкам',
|
||||||
|
};
|
||||||
@@ -91,3 +91,19 @@ Verification: all 32 integration tests passed against the isolated PostgreSQL se
|
|||||||
Verification: 41 integration tests passed, including a populated legacy-schema migration, correction/resubmission, stale decisions, older approval/check evidence, concurrent writes, authorization bypasses, queue filters and transaction rollback. All 20 unit/contract/localization tests, build, lint, typecheck, formatting and whitespace checks passed. All 24 browser tests passed. Browser verification covers the complete successful journey through Live, rejection, conflict preservation, direct review links, queue filtering, EN/RU and mobile/desktop layouts. Screenshots were visually inspected.
|
Verification: 41 integration tests passed, including a populated legacy-schema migration, correction/resubmission, stale decisions, older approval/check evidence, concurrent writes, authorization bypasses, queue filters and transaction rollback. All 20 unit/contract/localization tests, build, lint, typecheck, formatting and whitespace checks passed. All 24 browser tests passed. Browser verification covers the complete successful journey through Live, rejection, conflict preservation, direct review links, queue filtering, EN/RU and mobile/desktop layouts. Screenshots were visually inspected.
|
||||||
|
|
||||||
Applied migrations `202609240005_gated_onboarding` and `202609240006_kyb_upgrade` to development without a reset or reseed. Before/after checksums confirmed original company data, review decisions/snapshots, collection notes/history, activities, stage events, tasks and password hashes were unchanged for all 45 merchants. Only new missing representative records and unfinished merchant concurrency versions were added. Local health, authentication, detail capabilities and queue authorization passed for all four demo accounts; smoke-test sessions were signed out afterward.
|
Applied migrations `202609240005_gated_onboarding` and `202609240006_kyb_upgrade` to development without a reset or reseed. Before/after checksums confirmed original company data, review decisions/snapshots, collection notes/history, activities, stage events, tasks and password hashes were unchanged for all 45 merchants. Only new missing representative records and unfinished merchant concurrency versions were added. Local health, authentication, detail capabilities and queue authorization passed for all four demo accounts; smoke-test sessions were signed out afterward.
|
||||||
|
|
||||||
|
## Actionable tasks, reminders, and scoped dashboards
|
||||||
|
|
||||||
|
- [x] Shared creation, editing, completion and reopening from Tasks and merchant details, with a scoped merchant picker and server-derived capabilities
|
||||||
|
- [x] Today, Upcoming, Overdue and Completed views, URL filters, UTC persistence, local date/time display and DST-aware day boundaries
|
||||||
|
- [x] Private Compliance tasks and task audits; merchant-scoped reads, counts, selectors, writes, reminders and dashboards
|
||||||
|
- [x] Atomic open-task reassignment; preserved completed attribution; audited inherited-task reopening under the current owner
|
||||||
|
- [x] Database-backed reminder dismissal with revision checks, completed-task suppression, polling, focus/visibility/reconnection refresh and error states
|
||||||
|
- [x] Exact reminder timestamps retained on title-only edits; conflicts preserve form inputs and require explicit version refresh
|
||||||
|
- [x] Distinct Head, Manager and Compliance dashboards with shared scoped query predicates, all-stage distribution, workload and linked filtered records
|
||||||
|
- [x] Activation numerator/denominator and earliest-Live onboarding sample count, honest empty states, decision-history drilldowns and EN/RU explanatory text
|
||||||
|
- [x] Updated product brief, API documentation and additive upgrade instructions
|
||||||
|
|
||||||
|
Verification: **46 integration tests, 34 browser tests, and 21 unit/contract/localization tests passed**. Build, lint, typecheck, formatting and whitespace checks passed. Integration assertions independently calculate seed metrics and cover empty portfolios, first-Live deduplication, date boundaries, both manager isolation directions, private tasks/audits, reminder timing/dismissal/reopening/rescheduling, API restart persistence, assignment races and completed attribution. Browser coverage includes both task entry points, every primary view, polling and focus refresh, reminder errors, exact timestamp preservation, stale form conflicts, EN/RU at 390px/1440px, local New York time, filtered dashboard links, account switching, keyboard focus and reduced motion. Dashboard, task editor and inbox screenshots were visually inspected. The new browser journeys use real database-backed test sessions so repeated setup does not exhaust the unchanged production login limits.
|
||||||
|
|
||||||
|
Applied `202609240007_tasks_dashboards` to development without resetting or reseeding. Before/after checksums confirmed all original rows across 13 business tables were unchanged, preserving **45 merchants and 114 tasks**, histories, reviews and passwords. Health/login/dashboard/tasks/reminders smoke checks passed for all four development accounts; smoke-test sessions were signed out. Development's preserved history correctly yields 5/45 activation and 56 days average onboarding; fresh fixtures independently yield 5/45 and 78.6 days. No historical data was rewritten to force either result.
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ Reviewed company identity, website, country, industry and KYB items remain locke
|
|||||||
|
|
||||||
## Journeys and records
|
## Journeys and records
|
||||||
|
|
||||||
Landing → email/password login → role-scoped dashboard → merchant search/filter → detail, editing, assignment, checklist, reviews, interactions, history and tasks. The directory searches company, contact, email and website and combines stage, country, industry and authorized owner filters with eight-record pagination. Search/filter/page state is stored in the URL. Head and Compliance may filter by manager or Unassigned; Managers remain scoped to their own merchants. Desktop uses tables and pipeline columns; mobile uses directory cards and exactly one selected pipeline stage. Detail has URL-addressable Overview, Activity, Onboarding and Tasks tabs; Activity merges notes, interactions, ownership, stage events and compliance outcomes into one newest-first history. Explicit stage controls display server-derived blocking reasons. Pipeline, Tasks and Compliance Review Queue provide dedicated views. The Compliance-only queue shows total pending and filtered counts, elapsed waiting time, manager/search/24-hour/72-hour filters stored in the URL, and links to individual review cycles. Merchant detail shows the next owner, required action and server-derived blockers; commercial closure remains visibly distinct from Compliance rejection. Tasks can be created, edited and completed from merchant details; reminders stay in the app.
|
Landing → email/password login → role-scoped dashboard → merchant search/filter → detail, editing, assignment, checklist, reviews, interactions, history and tasks. The directory searches company, contact, email and website and combines stage, country, industry and authorized owner filters with eight-record pagination. Search/filter/page state is stored in the URL. Head and Compliance may filter by manager or Unassigned; Managers remain scoped to their own merchants. Desktop uses tables and pipeline columns; mobile uses directory cards and exactly one selected pipeline stage. Detail has URL-addressable Overview, Activity, Onboarding and Tasks tabs; Activity merges notes, interactions, ownership, stage events and compliance outcomes into one newest-first history. Explicit stage controls display server-derived blocking reasons. Pipeline, Tasks and Compliance Review Queue provide dedicated views. The Compliance-only queue shows total pending and filtered counts, elapsed waiting time, manager/search/24-hour/72-hour filters stored in the URL, and links to individual review cycles. Merchant detail shows the next owner, required action and server-derived blockers; commercial closure remains visibly distinct from Compliance rejection. Tasks can be created, edited, completed and reopened from Tasks and merchant details. Sales tasks follow the merchant manager (or the Head for unassigned leads); personal Compliance tasks are private. Reopening an inherited completed sales task assigns it to the current manager and retains the prior completion in audit history. Today uses the viewer’s local calendar day and includes overdue tasks due today; Upcoming begins tomorrow; Overdue means an open task whose due time has passed. Reminder dismissal is database-backed and survives reloads. Completed tasks suppress reminders; reopening preserves dismissal unless the reminder time or assignee changes. The in-app inbox refreshes while visible and on focus/reconnection.
|
||||||
|
|
||||||
Staff creation requires company name, primary-contact name and email; website, country, industry and volume may be completed later. Merchants include company and primary-contact details, website, country, industry, decimal USD volume estimates, source, nullable manager, stage, timestamps and a concurrency version. Related models retain activities, stage events, checklist changes, review snapshots and task attribution. Mutations and audit history commit atomically and reject stale versions.
|
Staff creation requires company name, primary-contact name and email; website, country, industry and volume may be completed later. Merchants include company and primary-contact details, website, country, industry, decimal USD volume estimates, source, nullable manager, stage, timestamps and a concurrency version. Related models retain activities, stage events, checklist changes, review snapshots and task attribution. Mutations and audit history commit atomically and reject stale versions.
|
||||||
|
|
||||||
@@ -49,3 +49,9 @@ No merchant deletion UI, staff registration, merchant self-service, real payment
|
|||||||
Review policy version 2 uses the three current KYB requirements. Legacy beneficial-owner ID and business-activity checklist records and every historical review snapshot/decision remain readable and unchanged. Additive migrations mark old cycles as version 1, leave their risk unset, and add a missing authorized-representative item to unfinished merchants. No previous identification is reinterpreted and no approval or demo result is invented.
|
Review policy version 2 uses the three current KYB requirements. Legacy beneficial-owner ID and business-activity checklist records and every historical review snapshot/decision remain readable and unchanged. Additive migrations mark old cycles as version 1, leave their risk unset, and add a missing authorized-representative item to unfinished merchants. No previous identification is reinterpreted and no approval or demo result is invented.
|
||||||
|
|
||||||
Legacy pending cycles may receive corrections or rejection but cannot be approved under obsolete requirements. Head or the assigned Manager can explicitly return legacy Integration/Testing merchants to KYB for collection and a fresh review. This audited exception preserves prior approvals. Current-policy approvals lock reviewed fields; Live and Rejected remain terminal.
|
Legacy pending cycles may receive corrections or rejection but cannot be approved under obsolete requirements. Head or the assigned Manager can explicitly return legacy Integration/Testing merchants to KYB for collection and a fresh review. This audited exception preserves prior approvals. Current-policy approvals lock reviewed fields; Live and Rejected remain terminal.
|
||||||
|
|
||||||
|
## Operational dashboards and metric definitions
|
||||||
|
|
||||||
|
Head sees total merchants, newly created leads in the last 30 days regardless of current stage, active onboarding, Live merchants, every pipeline stage including Rejected, manager workload, overdue commercial tasks and unassigned New Leads. Active onboarding consists of KYB, Compliance Review, Integration and Testing. Manager dashboards use the same merchant scope as their directory, emphasize next actions and overdue follow-ups, and contain only their own workload. Compliance sees pending cycles, the oldest waiting cycles, decisions in the last 30 days (including corrections), and personal review tasks.
|
||||||
|
|
||||||
|
Activation rate is currently Live merchants divided by all visible merchants, including Rejected. Average onboarding duration is creation to the first recorded Live transition per visible merchant that reached Live. Display the activation numerator/denominator and duration sample count; no merchants or no recorded Live transitions produces an explanatory empty state. Do not infer missing transitions. Dashboard totals, chart counts and filtered record links use shared database predicates and one consistent database snapshot. Any displayed volume is an estimated processing volume, never revenue.
|
||||||
|
|||||||
@@ -26,7 +26,16 @@ export const loginSchema = z.object({
|
|||||||
password: z.string().min(1, 'validation.password').max(128, 'validation.passwordMax'),
|
password: z.string().min(1, 'validation.password').max(128, 'validation.passwordMax'),
|
||||||
});
|
});
|
||||||
export type LoginInput = z.input<typeof loginSchema>;
|
export type LoginInput = z.input<typeof loginSchema>;
|
||||||
|
export const activeOnboardingStages = [
|
||||||
|
'KYB',
|
||||||
|
'COMPLIANCE_REVIEW',
|
||||||
|
'INTEGRATION',
|
||||||
|
'TESTING',
|
||||||
|
] as const;
|
||||||
export const merchantQuerySchema = z.object({
|
export const merchantQuerySchema = z.object({
|
||||||
|
createdFrom: z.iso.datetime().optional(),
|
||||||
|
createdTo: z.iso.datetime().optional(),
|
||||||
|
cohort: z.enum(['ACTIVE_ONBOARDING', 'REACHED_LIVE']).optional(),
|
||||||
search: z.string().trim().max(100).default(''),
|
search: z.string().trim().max(100).default(''),
|
||||||
status: statusSchema.optional(),
|
status: statusSchema.optional(),
|
||||||
country: z
|
country: z
|
||||||
@@ -37,8 +46,27 @@ export const merchantQuerySchema = z.object({
|
|||||||
ownerId: z.string().min(1).max(200).optional(),
|
ownerId: z.string().min(1).max(200).optional(),
|
||||||
page: z.coerce.number().int().min(1).max(10000).default(1),
|
page: z.coerce.number().int().min(1).max(10000).default(1),
|
||||||
});
|
});
|
||||||
export const taskFilters = ['ALL', 'OPEN', 'OVERDUE', 'UPCOMING', 'DONE'] as const;
|
export const taskFilters = ['TODAY', 'UPCOMING', 'OVERDUE', 'DONE', 'ALL', 'OPEN'] as const;
|
||||||
export const taskQuerySchema = z.object({ filter: z.enum(taskFilters).default('ALL') });
|
export const taskQuerySchema = z.object({
|
||||||
|
filter: z.enum(taskFilters).default('ALL'),
|
||||||
|
merchantId: z.string().min(1).max(200).optional(),
|
||||||
|
assigneeId: z.string().min(1).max(200).optional(),
|
||||||
|
timeZone: z
|
||||||
|
.string()
|
||||||
|
.max(100)
|
||||||
|
.refine((value) => {
|
||||||
|
try {
|
||||||
|
new Intl.DateTimeFormat('en', { timeZone: value });
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.default('UTC'),
|
||||||
|
});
|
||||||
|
export const reminderDismissalSchema = z
|
||||||
|
.object({ reminderRevision: z.number().int().nonnegative() })
|
||||||
|
.strict();
|
||||||
export type TaskFilter = (typeof taskFilters)[number];
|
export type TaskFilter = (typeof taskFilters)[number];
|
||||||
export const errorCodes = [
|
export const errorCodes = [
|
||||||
'UNAUTHORIZED',
|
'UNAUTHORIZED',
|
||||||
@@ -123,8 +151,10 @@ export const taskSchema = z.object({
|
|||||||
updatedAt: date,
|
updatedAt: date,
|
||||||
dueAt: date,
|
dueAt: date,
|
||||||
remindAt: date.nullable(),
|
remindAt: date.nullable(),
|
||||||
|
reminderRevision: z.number().int(),
|
||||||
|
capabilities: z.object({ edit: z.boolean(), complete: z.boolean(), reopen: z.boolean() }),
|
||||||
completedAt: date.nullable(),
|
completedAt: date.nullable(),
|
||||||
merchant: z.object({ id: z.string(), name: z.string() }),
|
merchant: z.object({ id: z.string(), name: z.string(), version: z.number().int() }),
|
||||||
assignee: z.object({ id: z.string(), name: z.string() }),
|
assignee: z.object({ id: z.string(), name: z.string() }),
|
||||||
creator: z.object({ name: z.string() }).nullable(),
|
creator: z.object({ name: z.string() }).nullable(),
|
||||||
completedBy: z.object({ name: z.string() }).nullable(),
|
completedBy: z.object({ name: z.string() }).nullable(),
|
||||||
@@ -334,6 +364,40 @@ export const merchantDetailSchema = merchantSchema.extend({
|
|||||||
});
|
});
|
||||||
export type MerchantDetail = z.infer<typeof merchantDetailSchema>;
|
export type MerchantDetail = z.infer<typeof merchantDetailSchema>;
|
||||||
export const dashboardSchema = z.object({
|
export const dashboardSchema = z.object({
|
||||||
|
asOf: date,
|
||||||
|
periodStart: date,
|
||||||
|
newLeads: z.number(),
|
||||||
|
activeOnboarding: z.number(),
|
||||||
|
liveMerchants: z.number(),
|
||||||
|
unassignedLeads: z.number(),
|
||||||
|
activation: z.object({
|
||||||
|
numerator: z.number(),
|
||||||
|
denominator: z.number(),
|
||||||
|
rate: z.number().nullable(),
|
||||||
|
}),
|
||||||
|
onboardingDuration: z.object({ averageDays: z.number().nullable(), sampleCount: z.number() }),
|
||||||
|
workload: z.array(
|
||||||
|
z.object({
|
||||||
|
id: z.string(),
|
||||||
|
name: z.string(),
|
||||||
|
merchants: z.number(),
|
||||||
|
activeOnboarding: z.number(),
|
||||||
|
openTasks: z.number(),
|
||||||
|
overdueTasks: z.number(),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
oldestReviews: z.array(
|
||||||
|
z.object({
|
||||||
|
id: z.string(),
|
||||||
|
cycle: z.number(),
|
||||||
|
submittedAt: date,
|
||||||
|
merchant: z.object({ id: z.string(), name: z.string() }),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
decisions: z.array(
|
||||||
|
z.object({ decision: z.enum(['APPROVED', 'CORRECTIONS', 'REJECTED']), count: z.number() }),
|
||||||
|
),
|
||||||
|
decisionsLast30Days: z.number(),
|
||||||
merchantCount: z.number(),
|
merchantCount: z.number(),
|
||||||
reviewCount: z.number(),
|
reviewCount: z.number(),
|
||||||
overdueTasks: z.number(),
|
overdueTasks: z.number(),
|
||||||
@@ -349,6 +413,10 @@ export const reviewQueueQuerySchema = z
|
|||||||
search: merchantQuerySchema.shape.search,
|
search: merchantQuerySchema.shape.search,
|
||||||
ownerId: merchantQuerySchema.shape.ownerId,
|
ownerId: merchantQuerySchema.shape.ownerId,
|
||||||
waiting: z.enum(['ALL', '24', '72']).default('ALL'),
|
waiting: z.enum(['ALL', '24', '72']).default('ALL'),
|
||||||
|
view: z.enum(['PENDING', 'DECISIONS']).default('PENDING'),
|
||||||
|
decision: z.enum(['APPROVED', 'CORRECTIONS', 'REJECTED']).optional(),
|
||||||
|
decidedFrom: z.iso.datetime().optional(),
|
||||||
|
decidedTo: z.iso.datetime().optional(),
|
||||||
})
|
})
|
||||||
.strict();
|
.strict();
|
||||||
export const reviewQueueSchema = z.object({
|
export const reviewQueueSchema = z.object({
|
||||||
@@ -360,6 +428,8 @@ export const reviewQueueSchema = z.object({
|
|||||||
id: z.string(),
|
id: z.string(),
|
||||||
cycle: z.number(),
|
cycle: z.number(),
|
||||||
policyVersion: z.number(),
|
policyVersion: z.number(),
|
||||||
|
decision: z.enum(['PENDING', 'APPROVED', 'CORRECTIONS', 'REJECTED']),
|
||||||
|
decidedAt: date.nullable(),
|
||||||
submittedAt: date,
|
submittedAt: date,
|
||||||
merchant: merchantSchema,
|
merchant: merchantSchema,
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
ALTER TABLE "Task" ADD COLUMN "reminderDismissedAt" TIMESTAMP(3),
|
||||||
|
ADD COLUMN "reminderRevision" INTEGER NOT NULL DEFAULT 0;
|
||||||
|
CREATE INDEX "Task_assigneeId_status_remindAt_idx" ON "Task"("assigneeId", "status", "remindAt");
|
||||||
@@ -184,6 +184,8 @@ model Task {
|
|||||||
updatedAt DateTime @default(now()) @updatedAt
|
updatedAt DateTime @default(now()) @updatedAt
|
||||||
dueAt DateTime
|
dueAt DateTime
|
||||||
remindAt DateTime?
|
remindAt DateTime?
|
||||||
|
reminderDismissedAt DateTime?
|
||||||
|
reminderRevision Int @default(0)
|
||||||
completedAt DateTime?
|
completedAt DateTime?
|
||||||
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
|
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
|
||||||
assignee User @relation("TaskAssignee", fields: [assigneeId], references: [id])
|
assignee User @relation("TaskAssignee", fields: [assigneeId], references: [id])
|
||||||
@@ -191,6 +193,7 @@ model Task {
|
|||||||
completedBy User? @relation("TaskCompleter", fields: [completedById], references: [id])
|
completedBy User? @relation("TaskCompleter", fields: [completedById], references: [id])
|
||||||
@@index([merchantId, status, dueAt])
|
@@index([merchantId, status, dueAt])
|
||||||
@@index([assigneeId, kind, status, dueAt])
|
@@index([assigneeId, kind, status, dueAt])
|
||||||
|
@@index([assigneeId, status, remindAt])
|
||||||
}
|
}
|
||||||
model Activity {
|
model Activity {
|
||||||
id String @id @default(uuid())
|
id String @id @default(uuid())
|
||||||
|
|||||||
@@ -29,5 +29,6 @@ if (mode === 'integration')
|
|||||||
'apps/api/test/public-leads.test.mjs',
|
'apps/api/test/public-leads.test.mjs',
|
||||||
'apps/api/test/sales-workspace.test.mjs',
|
'apps/api/test/sales-workspace.test.mjs',
|
||||||
'apps/api/test/gated-onboarding.test.mjs',
|
'apps/api/test/gated-onboarding.test.mjs',
|
||||||
|
'apps/api/test/tasks-dashboards.test.mjs',
|
||||||
]);
|
]);
|
||||||
else run('pnpm', ['exec', 'playwright', 'test']);
|
else run('pnpm', ['exec', 'playwright', 'test']);
|
||||||
|
|||||||
@@ -0,0 +1,360 @@
|
|||||||
|
import { createHash, randomBytes } from 'node:crypto';
|
||||||
|
import { test, expect, type Page } from '@playwright/test';
|
||||||
|
import { createDatabase } from '../packages/database/dist/index.js';
|
||||||
|
if (!process.env.DATABASE_URL?.endsWith('/merchantflow_test'))
|
||||||
|
throw new Error('Isolated database required');
|
||||||
|
const db = createDatabase(process.env.DATABASE_URL);
|
||||||
|
const ids: string[] = [];
|
||||||
|
const sessions: string[] = [];
|
||||||
|
test.afterEach(async () => {
|
||||||
|
await db.merchant.deleteMany({ where: { id: { in: ids } } });
|
||||||
|
ids.length = 0;
|
||||||
|
await db.session.deleteMany({ where: { id: { in: sessions } } });
|
||||||
|
sessions.length = 0;
|
||||||
|
});
|
||||||
|
test.afterAll(() => db.$disconnect());
|
||||||
|
// These journeys exercise SessionGuard using real isolated-database sessions.
|
||||||
|
// Login and throttling already have dedicated coverage; repeated setup must not exhaust them.
|
||||||
|
async function login(page: Page, account = 'head') {
|
||||||
|
const user = await db.user.findUniqueOrThrow({
|
||||||
|
where: { email: `${account}@merchantflow.test` },
|
||||||
|
});
|
||||||
|
const token = randomBytes(32).toString('hex');
|
||||||
|
const id = createHash('sha256').update(token).digest('hex');
|
||||||
|
sessions.push(id);
|
||||||
|
await db.session.create({
|
||||||
|
data: { id, userId: user.id, expiresAt: new Date(Date.now() + 8 * 3600000) },
|
||||||
|
});
|
||||||
|
await page.context().addCookies([
|
||||||
|
{
|
||||||
|
name: 'mf_session',
|
||||||
|
value: token,
|
||||||
|
domain: '127.0.0.1',
|
||||||
|
path: '/api',
|
||||||
|
httpOnly: true,
|
||||||
|
sameSite: 'Lax',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
await page.goto('/app');
|
||||||
|
await expect(page).toHaveURL(/\/app$/);
|
||||||
|
await expect(page.locator('h1')).toBeVisible();
|
||||||
|
}
|
||||||
|
async function save(page: Page) {
|
||||||
|
await page
|
||||||
|
.getByRole('dialog')
|
||||||
|
.getByRole('button', { name: /^(Save changes|Сохранить изменения)$/ })
|
||||||
|
.click();
|
||||||
|
await expect(page.getByRole('dialog')).not.toBeVisible();
|
||||||
|
}
|
||||||
|
async function localInput(page: Page, ms: number) {
|
||||||
|
return page.evaluate((time) => {
|
||||||
|
const date = new Date(time);
|
||||||
|
return new Date(time - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
|
||||||
|
}, ms);
|
||||||
|
}
|
||||||
|
async function inbox(page: Page) {
|
||||||
|
await page.getByRole('button', { name: /^(Reminders|Напоминания)( \(\d+\))?$/ }).click();
|
||||||
|
await expect(page.getByRole('dialog')).toBeVisible();
|
||||||
|
await expect(page.getByRole('dialog')).toHaveCSS('opacity', '1');
|
||||||
|
return page.getByRole('dialog');
|
||||||
|
}
|
||||||
|
for (const language of ['en', 'ru'])
|
||||||
|
for (const width of [390, 1440])
|
||||||
|
test.describe(`tasks and dashboards ${language} ${width}`, () => {
|
||||||
|
test.use({ viewport: { width, height: 1000 }, timezoneId: 'America/New_York' });
|
||||||
|
test('tasks work from both entry points and reminder dismissal survives reload', async ({
|
||||||
|
page,
|
||||||
|
}, info) => {
|
||||||
|
await page.addInitScript(
|
||||||
|
(lang) => localStorage.setItem('merchantflow.language', lang),
|
||||||
|
language,
|
||||||
|
);
|
||||||
|
const id = `browser-tasks-${language}-${width}`;
|
||||||
|
ids.push(id);
|
||||||
|
await db.merchant.create({
|
||||||
|
data: {
|
||||||
|
id,
|
||||||
|
name: `Task merchant ${language} ${width}`,
|
||||||
|
contactName: 'Contact',
|
||||||
|
contactEmail: '[email protected]',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await login(page);
|
||||||
|
await page.goto('/app/tasks');
|
||||||
|
await page.getByRole('button', { name: /^(Add task|Добавить задачу)$/ }).click();
|
||||||
|
await page
|
||||||
|
.getByRole('dialog')
|
||||||
|
.getByLabel(/Search merchants|Поиск мерчантов/)
|
||||||
|
.fill(`Task merchant ${language} ${width}`);
|
||||||
|
await page
|
||||||
|
.getByRole('dialog')
|
||||||
|
.getByRole('button', { name: `Task merchant ${language} ${width}`, exact: true })
|
||||||
|
.click();
|
||||||
|
const title = `Follow up ${language} ${width}`,
|
||||||
|
edited = title + ' edited';
|
||||||
|
await page
|
||||||
|
.getByRole('dialog')
|
||||||
|
.getByLabel(/^(Task title|Название задачи)$/)
|
||||||
|
.fill(title);
|
||||||
|
const due = await localInput(page, Date.now() + 2 * 86400000),
|
||||||
|
reminder = await localInput(page, Date.now() - 3600000);
|
||||||
|
await page
|
||||||
|
.getByRole('dialog')
|
||||||
|
.getByLabel(/^(Due date and time|Дата и время выполнения)$/)
|
||||||
|
.fill(due);
|
||||||
|
await page
|
||||||
|
.getByRole('dialog')
|
||||||
|
.getByLabel(/^(Reminder date and time|Дата и время напоминания)$/)
|
||||||
|
.fill(reminder);
|
||||||
|
await page.screenshot({ path: info.outputPath('task-editor.png'), fullPage: true });
|
||||||
|
await save(page);
|
||||||
|
const task = await db.task.findFirstOrThrow({ where: { merchantId: id } });
|
||||||
|
const utc = await page.evaluate((value) => new Date(value).toISOString(), due);
|
||||||
|
expect(task.dueAt.toISOString()).toBe(utc);
|
||||||
|
await page.getByRole('button', { name: /^(Upcoming|Предстоящие)$/ }).click();
|
||||||
|
const row = page.locator(`#task-${task.id}`);
|
||||||
|
await expect(row).toBeVisible();
|
||||||
|
await row.getByRole('button', { name: /^(Edit task|Изменить задачу)$/ }).click();
|
||||||
|
await page
|
||||||
|
.getByRole('dialog')
|
||||||
|
.getByLabel(/^(Task title|Название задачи)$/)
|
||||||
|
.fill(edited);
|
||||||
|
await save(page);
|
||||||
|
await expect(row).toContainText(edited);
|
||||||
|
let dialog = await inbox(page);
|
||||||
|
await expect(dialog.getByText(edited, { exact: true })).toBeVisible();
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
await page.goto(`/app/merchants/${id}?tab=tasks`);
|
||||||
|
await row.getByRole('button', { name: /^(Complete task|Выполнить задачу)$/ }).click();
|
||||||
|
await expect(
|
||||||
|
row.getByRole('button', { name: /Reopen task|Открыть задачу снова/ }),
|
||||||
|
).toBeVisible();
|
||||||
|
dialog = await inbox(page);
|
||||||
|
await expect(dialog.getByText(edited, { exact: true })).toHaveCount(0);
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
await row.getByRole('button', { name: /Reopen task|Открыть задачу снова/ }).click();
|
||||||
|
await expect(
|
||||||
|
row.getByRole('button', { name: /^(Complete task|Выполнить задачу)$/ }),
|
||||||
|
).toBeVisible();
|
||||||
|
dialog = await inbox(page);
|
||||||
|
await expect(dialog.getByText(edited, { exact: true })).toBeVisible();
|
||||||
|
await dialog
|
||||||
|
.locator('div.border-b')
|
||||||
|
.filter({ has: page.getByText(edited, { exact: true }) })
|
||||||
|
.getByRole('button', { name: /Dismiss reminder|Скрыть напоминание/ })
|
||||||
|
.click();
|
||||||
|
await expect(dialog.getByText(edited, { exact: true })).toHaveCount(0);
|
||||||
|
await page.reload();
|
||||||
|
dialog = await inbox(page);
|
||||||
|
await expect(dialog.getByText(edited, { exact: true })).toHaveCount(0);
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
await row.getByRole('button', { name: /^(Edit task|Изменить задачу)$/ }).click();
|
||||||
|
await page
|
||||||
|
.getByRole('dialog')
|
||||||
|
.getByLabel(/^(Due date and time|Дата и время выполнения)$/)
|
||||||
|
.fill(await localInput(page, Date.now() - 1800000));
|
||||||
|
await page
|
||||||
|
.getByRole('dialog')
|
||||||
|
.getByLabel(/^(Reminder date and time|Дата и время напоминания)$/)
|
||||||
|
.fill(await localInput(page, Date.now() - 7200000));
|
||||||
|
await save(page);
|
||||||
|
dialog = await inbox(page);
|
||||||
|
await expect(dialog.getByText(edited, { exact: true })).toBeVisible();
|
||||||
|
await page.screenshot({ path: info.outputPath('reminder-inbox.png'), fullPage: true });
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
await page.getByRole('button', { name: /^(Add task|Добавить задачу)$/ }).click();
|
||||||
|
await page
|
||||||
|
.getByRole('dialog')
|
||||||
|
.getByLabel(/^(Task title|Название задачи)$/)
|
||||||
|
.fill('Created from merchant');
|
||||||
|
await save(page);
|
||||||
|
await page.goto(`/app/tasks?merchantId=${id}&filter=TODAY`);
|
||||||
|
await expect(row).toBeVisible();
|
||||||
|
await page.getByRole('button', { name: /^(Overdue|Просроченные)$/ }).click();
|
||||||
|
await expect(row).toBeVisible();
|
||||||
|
await row.getByRole('button', { name: /^(Complete task|Выполнить задачу)$/ }).click();
|
||||||
|
await expect(row).toHaveCount(0);
|
||||||
|
await page.getByRole('button', { name: /^(Completed|Выполненные)$/ }).click();
|
||||||
|
await expect(row).toBeVisible();
|
||||||
|
await row.getByRole('button', { name: /Reopen task|Открыть задачу снова/ }).click();
|
||||||
|
await expect(row).toHaveCount(0);
|
||||||
|
await page.goBack();
|
||||||
|
await expect(page).toHaveURL(/filter=OVERDUE/);
|
||||||
|
await expect(row).toBeVisible();
|
||||||
|
await page.reload();
|
||||||
|
await expect(row).toBeVisible();
|
||||||
|
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
await page.screenshot({ path: info.outputPath('tasks.png'), fullPage: true });
|
||||||
|
});
|
||||||
|
test('role dashboards have scoped metrics and working filtered links', async ({
|
||||||
|
page,
|
||||||
|
}, info) => {
|
||||||
|
await page.addInitScript(
|
||||||
|
(lang) => localStorage.setItem('merchantflow.language', lang),
|
||||||
|
language,
|
||||||
|
);
|
||||||
|
for (const account of ['head', 'alex', 'compliance']) {
|
||||||
|
await login(page, account);
|
||||||
|
await expect(page.locator('h1')).toHaveText(
|
||||||
|
account === 'head'
|
||||||
|
? /Portfolio overview|Обзор портфеля/
|
||||||
|
: account === 'alex'
|
||||||
|
? /My merchant workspace|Мои мерчанты/
|
||||||
|
: /Review workspace|Проверки комплаенса/,
|
||||||
|
);
|
||||||
|
await expect(
|
||||||
|
page.getByRole('heading', { name: /Activation rate|Доля активации/ }),
|
||||||
|
).toBeVisible();
|
||||||
|
expect(
|
||||||
|
await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth),
|
||||||
|
).toBe(true);
|
||||||
|
await page.screenshot({
|
||||||
|
path: info.outputPath(`${account}-dashboard.png`),
|
||||||
|
fullPage: true,
|
||||||
|
animations: 'disabled',
|
||||||
|
});
|
||||||
|
if (account === 'compliance') {
|
||||||
|
await page
|
||||||
|
.getByRole('link')
|
||||||
|
.filter({
|
||||||
|
has: page.getByRole('heading', { name: /Decisions · 30 days|Решения · 30 дней/ }),
|
||||||
|
})
|
||||||
|
.click();
|
||||||
|
await expect(page).toHaveURL(/view=DECISIONS/);
|
||||||
|
await expect(page.locator('h1')).toHaveText(/Decision history|История решений/);
|
||||||
|
} else {
|
||||||
|
await page
|
||||||
|
.getByRole('link')
|
||||||
|
.filter({
|
||||||
|
has: page.getByRole('heading', {
|
||||||
|
name: /Active onboarding|Активный онбординг/,
|
||||||
|
exact: true,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.click();
|
||||||
|
await expect(page).toHaveURL(/cohort=ACTIVE_ONBOARDING/);
|
||||||
|
}
|
||||||
|
await page.reload();
|
||||||
|
await expect(page.getByRole('alert')).toHaveCount(0);
|
||||||
|
if (width < 1024)
|
||||||
|
await page.getByRole('button', { name: /Open navigation|Открыть навигацию/ }).click();
|
||||||
|
await page.getByRole('button', { name: /Sign out|Выйти/, exact: true }).click();
|
||||||
|
await expect(page).toHaveURL(/login/);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('reminders arrive through polling and focus, survive failures, and respect revision changes', async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const id = 'browser-tasks-refresh';
|
||||||
|
ids.push(id);
|
||||||
|
await db.merchant.create({
|
||||||
|
data: {
|
||||||
|
id,
|
||||||
|
name: 'Refresh task merchant',
|
||||||
|
contactName: 'Test',
|
||||||
|
contactEmail: '[email protected]',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await login(page);
|
||||||
|
const now = Date.now();
|
||||||
|
const task = await db.task.create({
|
||||||
|
data: {
|
||||||
|
merchantId: id,
|
||||||
|
assigneeId: 'user-head',
|
||||||
|
title: 'Focus reminder',
|
||||||
|
dueAt: new Date(now + 3600000),
|
||||||
|
remindAt: new Date(now + 1800000),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
let dialog = await inbox(page);
|
||||||
|
await expect(dialog.getByText(task.title, { exact: true })).toHaveCount(0);
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
await page.clock.install();
|
||||||
|
await db.task.update({
|
||||||
|
where: { id: task.id },
|
||||||
|
data: { remindAt: new Date(now - 1000), reminderRevision: { increment: 1 } },
|
||||||
|
});
|
||||||
|
await page.clock.fastForward(31000);
|
||||||
|
await expect(page.getByRole('button', { name: /^Reminders \([1-9]\d*\)$/ })).toBeVisible();
|
||||||
|
dialog = await inbox(page);
|
||||||
|
await expect(dialog.getByText(task.title, { exact: true })).toBeVisible();
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
await db.task.update({ where: { id: task.id }, data: { status: 'DONE' } });
|
||||||
|
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
|
||||||
|
dialog = await inbox(page);
|
||||||
|
await expect(dialog.getByText(task.title, { exact: true })).toHaveCount(0);
|
||||||
|
await page.route('**/api/reminders', (route) =>
|
||||||
|
route.fulfill({ status: 503, json: { code: 'DATABASE_UNAVAILABLE' } }),
|
||||||
|
);
|
||||||
|
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
|
||||||
|
await page.clock.fastForward(3000);
|
||||||
|
await expect(
|
||||||
|
dialog.getByText('The workspace database is unavailable. Please try again.'),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(dialog.getByText('You’re all caught up', { exact: true })).toHaveCount(0);
|
||||||
|
await page.unroute('**/api/reminders');
|
||||||
|
await dialog.getByRole('button', { name: 'Try again' }).click();
|
||||||
|
await expect(
|
||||||
|
dialog.getByText('The workspace database is unavailable. Please try again.'),
|
||||||
|
).toHaveCount(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('title-only edits preserve precise reminder instants, and conflicts retain unsaved values', async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const id = 'browser-tasks-conflict';
|
||||||
|
ids.push(id);
|
||||||
|
await db.merchant.create({
|
||||||
|
data: {
|
||||||
|
id,
|
||||||
|
name: 'Task conflict merchant',
|
||||||
|
contactName: 'Test',
|
||||||
|
contactEmail: '[email protected]',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const remindAt = new Date(Date.now() - 3600123),
|
||||||
|
dueAt = new Date(Date.now() + 8640456);
|
||||||
|
const task = await db.task.create({
|
||||||
|
data: {
|
||||||
|
merchantId: id,
|
||||||
|
assigneeId: 'user-head',
|
||||||
|
title: 'Keep exact reminder',
|
||||||
|
dueAt,
|
||||||
|
remindAt,
|
||||||
|
reminderDismissedAt: new Date(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await login(page);
|
||||||
|
await page.goto(`/app/merchants/${id}?tab=tasks`);
|
||||||
|
const row = page.locator(`#task-${task.id}`);
|
||||||
|
await row.getByRole('button', { name: 'Edit task', exact: true }).click();
|
||||||
|
await page
|
||||||
|
.getByRole('dialog')
|
||||||
|
.getByLabel('Task title', { exact: true })
|
||||||
|
.fill('Keep unsaved title');
|
||||||
|
await db.merchant.update({ where: { id }, data: { version: { increment: 1 } } });
|
||||||
|
await page.getByRole('dialog').getByRole('button', { name: 'Save changes', exact: true }).click();
|
||||||
|
await expect(page.getByRole('dialog').getByRole('alert')).toBeVisible();
|
||||||
|
await expect(page.getByRole('dialog').getByLabel('Task title', { exact: true })).toHaveValue(
|
||||||
|
'Keep unsaved title',
|
||||||
|
);
|
||||||
|
expect((await db.task.findUniqueOrThrow({ where: { id: task.id } })).title).toBe(
|
||||||
|
'Keep exact reminder',
|
||||||
|
);
|
||||||
|
await page.getByRole('dialog').getByRole('button', { name: 'Load current version' }).click();
|
||||||
|
await expect(
|
||||||
|
page.getByText('Current version loaded. Review your changes before saving.'),
|
||||||
|
).toBeVisible();
|
||||||
|
await save(page);
|
||||||
|
const updated = await db.task.findUniqueOrThrow({ where: { id: task.id } });
|
||||||
|
expect(updated.remindAt!.toISOString()).toBe(remindAt.toISOString());
|
||||||
|
expect(updated.dueAt.toISOString()).toBe(dueAt.toISOString());
|
||||||
|
expect(updated.reminderDismissedAt).not.toBeNull();
|
||||||
|
expect(updated.reminderRevision).toBe(0);
|
||||||
|
const dialog = await inbox(page);
|
||||||
|
await expect(dialog.getByText('Keep unsaved title', { exact: true })).toHaveCount(0);
|
||||||
|
});
|
||||||
+19
-5
@@ -7,9 +7,20 @@ async function signIn(page: Page, account = 'head') {
|
|||||||
.getByRole('button', { name: /^Sign in to workspace$|^Войти в рабочее пространство$/ })
|
.getByRole('button', { name: /^Sign in to workspace$|^Войти в рабочее пространство$/ })
|
||||||
.click();
|
.click();
|
||||||
await expect(page).toHaveURL(/\/app$/);
|
await expect(page).toHaveURL(/\/app$/);
|
||||||
await expect(page.getByRole('heading', { name: /^Overview$|^Обзор$/ })).toBeVisible();
|
await expect(page.locator('h1')).toHaveText(
|
||||||
|
account === 'head'
|
||||||
|
? /Portfolio overview|Обзор портфеля/
|
||||||
|
: account === 'compliance'
|
||||||
|
? /Review workspace|Проверки комплаенса/
|
||||||
|
: /My merchant workspace|Мои мерчанты/,
|
||||||
|
);
|
||||||
await expect(
|
await expect(
|
||||||
page.getByRole('heading', { name: /Pipeline at a glance|Воронка с первого взгляда/ }),
|
page.getByRole('heading', {
|
||||||
|
name:
|
||||||
|
account === 'compliance'
|
||||||
|
? /Oldest waiting reviews|Дольше всего ожидают/
|
||||||
|
: /Pipeline at a glance|Воронка с первого взгляда/,
|
||||||
|
}),
|
||||||
).toBeVisible();
|
).toBeVisible();
|
||||||
}
|
}
|
||||||
async function noOverflow(page: Page) {
|
async function noOverflow(page: Page) {
|
||||||
@@ -128,7 +139,10 @@ test('account switching removes old data, manager isolation and Compliance navig
|
|||||||
await page.getByRole('button', { name: 'Sign out' }).click();
|
await page.getByRole('button', { name: 'Sign out' }).click();
|
||||||
await signIn(page, 'compliance');
|
await signIn(page, 'compliance');
|
||||||
expect((await (await page.request.get('/api/dashboard')).json()).merchantCount).toBe(45);
|
expect((await (await page.request.get('/api/dashboard')).json()).merchantCount).toBe(45);
|
||||||
await page.getByRole('link', { name: 'Review queue', exact: true }).click();
|
await page
|
||||||
|
.getByRole('navigation', { name: 'Workspace', exact: true })
|
||||||
|
.getByRole('link', { name: 'Review queue', exact: true })
|
||||||
|
.click();
|
||||||
await expect(page.getByRole('heading', { name: '6 merchants awaiting review' })).toBeVisible();
|
await expect(page.getByRole('heading', { name: '6 merchants awaiting review' })).toBeVisible();
|
||||||
await page.getByRole('link', { name: 'Open review' }).first().click();
|
await page.getByRole('link', { name: 'Open review' }).first().click();
|
||||||
await expect(page.getByRole('heading', { name: 'KYB checklist' })).toBeVisible();
|
await expect(page.getByRole('heading', { name: 'KYB checklist' })).toBeVisible();
|
||||||
@@ -183,7 +197,7 @@ test('loading, retryable errors, empty states, session expiry and reduced motion
|
|||||||
await expect(page.getByRole('heading', { name: 'Rejected', exact: true })).toBeVisible();
|
await expect(page.getByRole('heading', { name: 'Rejected', exact: true })).toBeVisible();
|
||||||
await page.route('**/api/tasks?**', (route) => route.fulfill({ json: [] }));
|
await page.route('**/api/tasks?**', (route) => route.fulfill({ json: [] }));
|
||||||
await page.goto('/app/tasks');
|
await page.goto('/app/tasks');
|
||||||
await expect(page.getByText('You’re all caught up here')).toBeVisible();
|
await expect(page.getByText('No tasks in this view')).toBeVisible();
|
||||||
await page.emulateMedia({ reducedMotion: 'reduce' });
|
await page.emulateMedia({ reducedMotion: 'reduce' });
|
||||||
expect(
|
expect(
|
||||||
await page
|
await page
|
||||||
@@ -259,7 +273,7 @@ test('Head assignment, manager editing, Compliance decisions and manager activat
|
|||||||
await save();
|
await save();
|
||||||
const taskRow = page.locator('#tasks > div').filter({ hasText: 'Send the integration guide' });
|
const taskRow = page.locator('#tasks > div').filter({ hasText: 'Send the integration guide' });
|
||||||
await taskRow.getByRole('button', { name: 'Complete task', exact: true }).click();
|
await taskRow.getByRole('button', { name: 'Complete task', exact: true }).click();
|
||||||
await expect(taskRow.getByText('Completed', { exact: true }).first()).toBeVisible();
|
await expect(taskRow.getByText(/^Completed ·/).first()).toBeVisible();
|
||||||
await advance('Contacted');
|
await advance('Contacted');
|
||||||
await advance('Qualified');
|
await advance('Qualified');
|
||||||
await advance('KYB');
|
await advance('KYB');
|
||||||
|
|||||||
Reference in New Issue
Block a user