Added tasks, reminders, and role-specific dashboards

This commit is contained in:
Oleksandr Prokhorenko
2026-09-24 22:18:41 +03:00
parent 1f8721e742
commit 9ccbac4aca
33 changed files with 2583 additions and 511 deletions
+3 -1
View File
@@ -19,7 +19,9 @@ export function merchantScope(user: User): Prisma.MerchantWhereInput {
export function taskScope(user: User): Prisma.TaskWhereInput {
return {
merchant: merchantScope(user),
...(user.role === 'COMPLIANCE_OFFICER' ? { assigneeId: user.id, kind: 'COMPLIANCE' } : {}),
...(user.role === 'COMPLIANCE_OFFICER'
? { assigneeId: user.id, kind: 'COMPLIANCE' }
: { kind: 'COMMERCIAL' }),
};
}
export function requireSales(user: User) {
+2
View File
@@ -11,6 +11,7 @@ import { NestFactory } from '@nestjs/core';
import cookieParser from 'cookie-parser';
import { createDatabase, PrismaClient } from '@merchantflow/database';
import { AuthController, AuthService, SessionGuard } from './auth.js';
import { ReminderController } from './reminders.js';
import { CrmController } from './crm.js';
import { WorkflowController } from './workflow.js';
import { DATABASE, ApiError, ErrorFilter } from './shared.js';
@@ -40,6 +41,7 @@ class DatabaseLifecycle implements OnApplicationShutdown {
HealthController,
AuthController,
CrmController,
ReminderController,
WorkflowController,
PublicLeadController,
],
+58 -158
View File
@@ -1,16 +1,15 @@
import { Controller, Get, Inject, Param, Query, Req, UseGuards } from '@nestjs/common';
import { PrismaClient, type Prisma } from '@merchantflow/database';
import {
statuses,
merchantQuerySchema,
taskQuerySchema,
reviewQueueQuerySchema,
} from '@merchantflow/contracts';
import { PrismaClient } from '@merchantflow/database';
import { merchantQuerySchema, reviewQueueQuerySchema } from '@merchantflow/contracts';
import { SessionGuard } from './auth.js';
import { DATABASE, ApiError, type AuthRequest } from './shared.js';
import { capabilities, merchantScope, taskScope } from './access.js';
import { evidenceInclude } from './workflow-policy.js';
import { merchantHistory } from './history.js';
import { taskSelect, taskDto, taskWhere, pendingReviews } from './task-policy.js';
import { merchantWhere } from './merchant-query.js';
import { reviewWhere } from './review-query.js';
import { dashboardData } from './dashboard.js';
const merchantSelect = {
id: true,
name: true,
@@ -43,21 +42,6 @@ const eventSelect = {
merchant: { select: { id: true, name: true } },
actor: { select: { name: true } },
} as const;
const taskSelect = {
id: true,
title: true,
status: true,
kind: true,
createdAt: true,
updatedAt: true,
dueAt: true,
remindAt: true,
completedAt: true,
merchant: { select: { id: true, name: true } },
assignee: { select: { id: true, name: true } },
creator: { select: { name: true } },
completedBy: { select: { name: true } },
} as const;
const activitySelect = {
id: true,
kind: true,
@@ -80,37 +64,8 @@ export class CrmController {
});
}
@Get('merchants') async merchants(@Req() req: AuthRequest, @Query() query: unknown) {
const {
page: requestedPage,
search,
status,
country,
industry,
ownerId,
} = merchantQuerySchema.parse(query);
if (ownerId && req.user.role === 'ACCOUNT_MANAGER') throw new ApiError('FORBIDDEN', 403);
const where: Prisma.MerchantWhereInput = {
AND: [
merchantScope(req.user),
...(status ? [{ status }] : []),
...(country ? [{ country }] : []),
...(industry ? [{ industry }] : []),
...(ownerId ? [{ ownerId: ownerId === 'unassigned' ? null : ownerId }] : []),
...(search
? [
{
OR: [
{ name: { contains: search, mode: 'insensitive' as const } },
{ contactEmail: { contains: search, mode: 'insensitive' as const } },
{ legalName: { contains: search, mode: 'insensitive' as const } },
{ contactName: { contains: search, mode: 'insensitive' as const } },
{ website: { contains: search, mode: 'insensitive' as const } },
],
},
]
: []),
],
};
const { page: requestedPage } = merchantQuerySchema.parse(query);
const where = merchantWhere(req.user, query);
return this.db.$transaction(
async (tx) => {
const total = await tx.merchant.count({ where });
@@ -181,7 +136,11 @@ export class CrmController {
events: { select: eventSelect, orderBy: { occurredAt: 'desc' } },
tasks: { where: taskScope(req.user), select: taskSelect, orderBy: { dueAt: 'asc' } },
activities: {
select: { ...activitySelect, metadata: true },
select: {
...activitySelect,
metadata: true,
actor: { select: { id: true, name: true, role: true } },
},
orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }],
},
reviews: {
@@ -208,11 +167,37 @@ export class CrmController {
where: { AND: [merchantScope(req.user), { id }] },
include: evidenceInclude,
});
const history = await merchantHistory(merchant, tx);
// Personal task audit entries follow the same privacy boundary as the task itself.
// Old creation audits lack taskKind; their authenticated actor role supplies the kind.
const activities = merchant.activities.filter((activity) => {
if (
activity.kind !== 'AUDIT' ||
!['Task created', 'Task updated'].includes(activity.text)
)
return true;
const meta =
activity.metadata &&
typeof activity.metadata === 'object' &&
!Array.isArray(activity.metadata)
? activity.metadata
: {};
const complianceTask =
meta.taskKind === 'COMPLIANCE' ||
(!meta.taskKind && activity.actor?.role === 'COMPLIANCE_OFFICER');
return req.user.role === 'COMPLIANCE_OFFICER'
? complianceTask &&
(meta.assigneeId === req.user.id || activity.actor?.id === req.user.id)
: !complianceTask;
});
const history = await merchantHistory({ ...merchant, activities }, tx);
return {
...merchant,
tasks: merchant.tasks.map((task) => taskDto(task, req.user)),
activationChecks: evidence.reviews.flatMap((review) => review.activationChecks),
activities: merchant.activities.map(({ metadata: _metadata, ...activity }) => activity),
activities: activities.map(({ metadata: _metadata, actor, ...activity }) => ({
...activity,
actor: actor ? { id: actor.id, name: actor.name } : null,
})),
capabilities: capabilities(req.user, evidence),
history,
};
@@ -241,63 +226,41 @@ export class CrmController {
{ isolationLevel: 'RepeatableRead' },
);
}
@Get('tasks') tasks(@Req() req: AuthRequest, @Query() query: unknown) {
const { filter } = taskQuerySchema.parse(query);
const where: Prisma.TaskWhereInput = taskScope(req.user);
if (filter === 'DONE') where.status = 'DONE';
if (['OPEN', 'OVERDUE', 'UPCOMING'].includes(filter)) where.status = 'OPEN';
if (filter === 'OVERDUE') where.dueAt = { lt: new Date() };
if (filter === 'UPCOMING') where.dueAt = { gte: new Date() };
return this.db.task.findMany({
where,
@Get('tasks') async tasks(@Req() req: AuthRequest, @Query() query: unknown) {
const rows = await this.db.task.findMany({
where: taskWhere(req.user, query),
select: taskSelect,
orderBy: [{ status: 'asc' }, { dueAt: 'asc' }],
orderBy: [{ status: 'asc' }, { dueAt: 'asc' }, { id: 'asc' }],
});
return rows.map((task) => taskDto(task, req.user));
}
@Get('review-queue') async reviewQueue(@Req() req: AuthRequest, @Query() query: unknown) {
if (req.user.role !== 'COMPLIANCE_OFFICER') throw new ApiError('FORBIDDEN', 403);
const { search, ownerId, waiting } = reviewQueueQuerySchema.parse(query);
const base: Prisma.ComplianceReviewWhereInput = {
decision: 'PENDING',
merchant: { AND: [merchantScope(req.user), { status: 'COMPLIANCE_REVIEW' }] },
};
const { view } = reviewQueueQuerySchema.parse(query);
const pending = pendingReviews(req.user);
return this.db.$transaction(
async (tx) => {
const pendingCount = await tx.complianceReview.count({ where: base });
const pendingCount = await tx.complianceReview.count({ where: pending });
const owners = await tx.user.findMany({
where: { role: 'ACCOUNT_MANAGER' },
select: { id: true, name: true },
orderBy: { name: 'asc' },
});
const items = await tx.complianceReview.findMany({
where: {
AND: [
base,
{
...(waiting !== 'ALL'
? { submittedAt: { lte: new Date(Date.now() - Number(waiting) * 3600000) } }
: {}),
merchant: {
...(ownerId ? { ownerId: ownerId === 'unassigned' ? null : ownerId } : {}),
...(search
? {
OR: ['name', 'legalName', 'contactName', 'contactEmail', 'website'].map(
(field) => ({ [field]: { contains: search, mode: 'insensitive' } }),
),
}
: {}),
},
},
],
},
where: reviewWhere(req.user, query),
select: {
id: true,
cycle: true,
policyVersion: true,
decision: true,
decidedAt: true,
submittedAt: true,
merchant: { select: merchantSelect },
},
orderBy: [{ submittedAt: 'asc' }, { id: 'asc' }],
orderBy:
view === 'PENDING'
? [{ submittedAt: 'asc' }, { id: 'asc' }]
: [{ decidedAt: 'desc' }, { id: 'asc' }],
});
return {
items,
@@ -309,70 +272,7 @@ export class CrmController {
{ isolationLevel: 'RepeatableRead' },
);
}
@Get('dashboard') async dashboard(@Req() req: AuthRequest) {
const scope = merchantScope(req.user);
const distributionQuery = this.db.merchant.groupBy({
by: ['status'],
orderBy: { status: 'asc' },
where: scope,
_count: { _all: true },
});
const [
merchantCount,
reviewCount,
overdueTasks,
transitionsLast30Days,
distribution,
recentEvents,
upcomingTasks,
recentActivities,
] = await this.db.$transaction([
this.db.merchant.count({ where: scope }),
this.db.complianceReview.count({
where: { decision: 'PENDING', merchant: { AND: [scope, { status: 'COMPLIANCE_REVIEW' }] } },
}),
this.db.task.count({
where: { ...taskScope(req.user), status: 'OPEN', dueAt: { lt: new Date() } },
}),
this.db.statusEvent.count({
where: {
merchant: scope,
fromStatus: { not: null },
occurredAt: { gte: new Date(Date.now() - 30 * 86400000) },
},
}),
distributionQuery,
this.db.statusEvent.findMany({
where: { merchant: scope },
select: eventSelect,
orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }],
take: 6,
}),
this.db.task.findMany({
where: { ...taskScope(req.user), status: 'OPEN' },
select: taskSelect,
orderBy: { dueAt: 'asc' },
take: 4,
}),
this.db.activity.findMany({
where: { merchant: scope },
select: activitySelect,
orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }],
take: 8,
}),
]);
return {
merchantCount,
reviewCount,
overdueTasks,
transitionsLast30Days,
distribution: statuses.map((status) => ({
status,
count: distribution.find((d) => d.status === status)?._count._all ?? 0,
})),
recentEvents,
upcomingTasks,
recentActivities,
};
@Get('dashboard') dashboard(@Req() req: AuthRequest) {
return dashboardData(this.db, req.user);
}
}
+193
View File
@@ -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' },
);
}
+37
View File
@@ -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] } }] : []),
],
};
}
+61
View File
@@ -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 };
});
}
}
+42
View File
@@ -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' } }),
),
}
: {}),
},
},
],
};
}
+94
View File
@@ -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',
},
};
}
+40 -5
View File
@@ -206,7 +206,11 @@ export class WorkflowController {
await tx.merchant.updateMany({ where: { id }, data: { ownerId } });
await tx.task.updateMany({
where: { merchantId: id, kind: 'COMMERCIAL', status: 'OPEN' },
data: { assigneeId: ownerId },
data: {
assigneeId: ownerId,
reminderDismissedAt: null,
reminderRevision: { increment: 1 },
},
});
await this.audit(tx, req, id, 'Manager assignment updated', {
previousOwnerId: merchant.ownerId,
@@ -498,6 +502,24 @@ export class WorkflowController {
: null;
if (taskId && !existing) throw new ApiError('NOT_FOUND', 404);
if (existing && existing.kind !== kind) throw new ApiError('FORBIDDEN', 403);
if (
existing &&
req.user.role === 'ACCOUNT_MANAGER' &&
existing.assigneeId !== req.user.id &&
!(existing.status === 'DONE' && status === 'OPEN')
)
throw new ApiError('FORBIDDEN', 403);
const assigneeId =
kind === 'COMPLIANCE'
? req.user.id
: status === 'DONE' && existing
? existing.assigneeId
: (merchant.ownerId ?? existing?.assigneeId ?? req.user.id);
const reminderChanged =
existing &&
(existing.assigneeId !== assigneeId ||
(existing.remindAt?.getTime() ?? null) !==
(remindAt ? new Date(remindAt).getTime() : null));
const completion =
status === 'DONE'
? {
@@ -506,6 +528,10 @@ export class WorkflowController {
}
: { completedAt: null, completedById: null };
const data = {
assigneeId,
...(reminderChanged
? { reminderDismissedAt: null, reminderRevision: { increment: 1 } }
: {}),
title,
dueAt: new Date(dueAt),
remindAt: remindAt ? new Date(remindAt) : null,
@@ -517,18 +543,27 @@ export class WorkflowController {
where: { AND: [taskScope(req.user), { id: existing.id, merchantId: id }] },
data,
});
else
await tx.task.create({
else {
const created = await tx.task.create({
data: {
...data,
reminderRevision: 0,
kind,
creatorId: req.user.id,
merchantId: id,
assigneeId: kind === 'COMPLIANCE' ? req.user.id : (merchant.ownerId ?? req.user.id),
assigneeId,
},
});
taskId = created.id;
}
await this.audit(tx, req, id, existing ? 'Task updated' : 'Task created', {
taskId: taskId ?? null,
taskId: taskId!,
taskKind: kind,
assigneeId,
previousStatus: existing?.status ?? null,
previousAssigneeId: existing?.assigneeId ?? null,
previousCompletedAt: existing?.completedAt?.toISOString() ?? null,
previousCompletedById: existing?.completedById ?? null,
title,
status,
});
+8 -5
View File
@@ -125,7 +125,7 @@ for (const [account, total] of [
merchantId: { in: ids },
...(account === 'compliance'
? { kind: 'COMPLIANCE', assigneeId: 'user-compliance' }
: {}),
: { kind: 'COMMERCIAL' }),
},
}),
);
@@ -151,7 +151,7 @@ for (const [account, total] of [
merchantId: { in: ids },
...(account === 'compliance'
? { kind: 'COMPLIANCE', assigneeId: 'user-compliance' }
: {}),
: { kind: 'COMMERCIAL' }),
status: 'OPEN',
dueAt: { lt: new Date() },
},
@@ -775,7 +775,7 @@ test('reassignment transfers open commercial tasks; concurrent writes and former
);
const before = await get();
assert.equal((await get(comp)).tasks.length, 1);
const personal = before.tasks.find((t) => t.kind === 'COMPLIANCE');
const personal = (await get(comp)).tasks.find((t) => t.kind === 'COMPLIANCE');
assert.equal(
(
await mutate(`/merchants/${id}/tasks/${personal.id}`, head, {
@@ -783,7 +783,7 @@ test('reassignment transfers open commercial tasks; concurrent writes and former
version: before.version,
})
).status,
403,
404,
);
const commercial = before.tasks.find((t) => t.kind === 'COMMERCIAL');
assert.equal(
@@ -828,7 +828,10 @@ test('reassignment transfers open commercial tasks; concurrent writes and former
.filter((t) => t.status === 'DONE')
.every((t) => t.assignee.id === 'user-manager1'),
);
assert.equal(after.tasks.find((t) => t.kind === 'COMPLIANCE').assignee.id, 'user-compliance');
assert.equal(
(await get(comp)).tasks.find((t) => t.kind === 'COMPLIANCE').assignee.id,
'user-compliance',
);
assert.equal((await request(`/merchants/${id}`, alex)).status, 404);
assert.equal(
(
+441
View File
@@ -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' } });
});
+24
View File
@@ -34,3 +34,27 @@ test('every role receives its exact merchant scope', () => {
assert.deepEqual(merchantScope({ role: 'COMPLIANCE_OFFICER' }), {});
assert.deepEqual(merchantScope({ role: 'unexpected' }), { id: '__no_access__' });
});
test('task day boundaries use the viewer time zone through DST and include exact due instants', async () => {
const { localDayBounds, taskWhere } = await import('../dist/task-policy.js');
for (const [date, hours] of [
['2026-03-08T12:00:00Z', 23],
['2026-11-01T12:00:00Z', 25],
]) {
const { start, end } = localDayBounds(new Date(date), 'America/New_York');
assert.equal((end - start) / 3600000, hours);
}
const now = new Date('2026-09-24T22:00:00Z');
const { start, end } = localDayBounds(now, 'Europe/Kyiv');
assert.equal(start.toISOString(), '2026-09-24T21:00:00.000Z');
assert.equal(end.toISOString(), '2026-09-25T21:00:00.000Z');
const user = { id: 'manager', role: 'ACCOUNT_MANAGER' };
assert.deepEqual(
taskWhere(user, { filter: 'TODAY', timeZone: 'Europe/Kyiv' }, now).AND[1].dueAt,
{ gte: start, lt: end },
);
assert.deepEqual(
taskWhere(user, { filter: 'UPCOMING', timeZone: 'Europe/Kyiv' }, now).AND[1].dueAt,
{ gte: end },
);
});
+342
View File
@@ -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>
</>
);
}
+2 -108
View File
@@ -12,15 +12,13 @@ import {
isRequiredDocument,
sources,
statuses,
taskInputSchema,
type MerchantDetail,
type Task,
} from '@merchantflow/contracts';
import { api } from '../lib/api';
import { Editor, useAction, type Field } from './workflow-form';
import { StageActions } from './sales-workspace';
import { useFormat } from '../lib/format';
import { Button, SectionHeader, TaskRow } from './shared';
import { Button, SectionHeader } from './shared';
const identityFields = [
'name',
@@ -431,111 +429,7 @@ export function InteractionHistory({ merchant: m }: { merchant: MerchantDetail }
</section>
);
}
const localDate = (value: string) => {
const date = new Date(value);
return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
};
const isoDate = (value: string) => {
const date = new Date(value);
return Number.isFinite(date.getTime()) ? date.toISOString() : '';
};
export function MerchantTasks({ merchant: m }: { merchant: MerchantDetail }) {
const { t } = useTranslation();
const [edit, setEdit] = useState<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 { MerchantTasks } from './tasks';
export function RecentInteractions({ activities }: { activities: MerchantDetail['activities'] }) {
const { t } = useTranslation();
const f = useFormat();
+97
View File
@@ -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>
</>
);
}
+19 -5
View File
@@ -248,7 +248,15 @@ export function MerchantCard({ merchant, className }: { merchant: Merchant; clas
</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 f = useFormat();
const done = task.status === 'DONE';
@@ -272,14 +280,20 @@ export function TaskRow({ task, compact = false }: { task: Task; compact?: boole
{task.title}
</p>
<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}
</Link>
<span className="text-muted-foreground" aria-hidden="true">
·
</span>
<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')}`}
</span>
</div>
@@ -290,8 +304,8 @@ export function TaskRow({ task, compact = false }: { task: Task; compact?: boole
<span className="inline-flex items-center gap-1">
<Bell className="size-3" aria-hidden="true" />
{new Date(task.remindAt).getTime() <= Date.now()
? t('tasks.reminderDue')
: `${t('tasks.reminder')}: ${f.date(task.remindAt)}`}
? `${t('tasks.reminderDue')} · ${f.dateTime(task.remindAt)}`
: `${t('tasks.reminder')}: ${f.dateTime(task.remindAt)}`}
</span>
)}
</div>
+2
View File
@@ -1,3 +1,4 @@
import { ReminderInbox } from './reminders';
import { useState, useEffect } from 'react';
import { NavLink, Navigate, Outlet, useLocation, useNavigate } from 'react-router';
import { useQuery, useMutation } from '@tanstack/react-query';
@@ -171,6 +172,7 @@ function AuthenticatedShell({ user }: { user: User }) {
<span className="hidden text-xs text-muted-foreground xl:block">
{f.date(new Date())}
</span>
<ReminderInbox />
<LanguageSwitch />
</div>
</header>
+361
View File
@@ -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)} />}
</>
);
}
+10 -1
View File
@@ -5,7 +5,16 @@ export function directoryParams(input: URLSearchParams, role: Role) {
const search = input.get('search')?.slice(0, 100);
// Preserve typing whitespace; the server normalizes the search term.
if (search) result.set('search', search);
for (const key of ['status', 'country', 'industry', 'ownerId', 'page'] as const) {
for (const key of [
'status',
'country',
'industry',
'ownerId',
'page',
'createdFrom',
'createdTo',
'cohort',
] as const) {
if (key === 'ownerId' && role === 'ACCOUNT_MANAGER') continue;
const raw = input.get(key);
if (!raw) continue;
+19
View File
@@ -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;
+10 -2
View File
@@ -3,9 +3,17 @@ export function reviewParams(input: URLSearchParams) {
const result = new URLSearchParams();
const search = input.get('search')?.slice(0, 100);
if (search) result.set('search', search);
for (const key of ['ownerId', 'waiting'] as const) {
for (const key of [
'ownerId',
'waiting',
'view',
'decision',
'decidedFrom',
'decidedTo',
] as const) {
const parsed = reviewQueueQuerySchema.shape[key].safeParse(input.get(key) ?? undefined);
if (parsed.success && parsed.data && parsed.data !== 'ALL') result.set(key, parsed.data);
if (parsed.success && parsed.data && parsed.data !== 'ALL' && parsed.data !== 'PENDING')
result.set(key, parsed.data);
}
return result;
}
+5
View File
@@ -1,8 +1,10 @@
import { operationsEn, operationsRu } from './task-dashboard-locales';
import { onboardingEn, onboardingRu } from './onboarding-locales';
import { salesEn, salesRu } from './sales-locales';
import { workflowEn, workflowRu } from './workflow-locales';
import { landingEn, landingRu } from './landing-locales';
export const en = {
operations: operationsEn,
onboarding: onboardingEn,
workflow: workflowEn,
workspace: salesEn,
@@ -204,6 +206,7 @@ export const en = {
stageCount: '{{number}} of 8 stages',
},
tasks: {
TODAY: 'Today',
title: 'Tasks',
description: 'A little structure for the next right step.',
ALL: 'All tasks',
@@ -236,6 +239,7 @@ export const en = {
},
};
export const ru = {
operations: operationsRu,
onboarding: onboardingRu,
workflow: workflowRu,
workspace: salesRu,
@@ -440,6 +444,7 @@ export const ru = {
stageCount: '{{number}} из 8 этапов',
},
tasks: {
TODAY: 'Сегодня',
title: 'Задачи',
description: 'Немного порядка для следующего верного шага.',
ALL: 'Все задачи',
+70 -213
View File
@@ -6,7 +6,6 @@ import {
ReviewHistory,
InteractionHistory,
MerchantTasks,
RecentInteractions,
} from '../components/merchant-workflow';
import { useEffect, useState } from 'react';
import { Link, useLocation, useOutletContext, useParams, useSearchParams } from 'react-router';
@@ -14,12 +13,8 @@ import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import {
ArrowRight,
ArrowUpRight,
ArrowLeft,
Building2,
ShieldCheck,
Clock3,
Activity,
Search,
ChevronLeft,
ChevronRight,
@@ -31,19 +26,15 @@ import {
LoaderCircle,
} from 'lucide-react';
import {
dashboardSchema,
merchantListSchema,
merchantDetailSchema,
reviewQueueSchema,
pipelineBoardSchema,
merchantFiltersSchema,
taskListSchema,
statuses,
statusSchema,
taskFilters,
canSeeReviewQueue,
type User,
type TaskFilter,
type Merchant,
} from '@merchantflow/contracts';
import { Input } from '@merchantflow/ui/components/input';
@@ -70,154 +61,11 @@ import {
Button,
StatusBadge,
Avatar,
TaskRow,
MerchantCard,
EmptyState,
stageColors,
} from '../components/shared';
export function Dashboard() {
const { t } = useTranslation();
const f = useFormat();
const user = useOutletContext<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>
</>
);
}
export { Dashboard } from '../components/dashboard';
function useDebounced(value: string) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
@@ -469,6 +317,23 @@ export function Merchants() {
)}
</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 && (
<div role="alert" className="px-5 py-3 text-sm">
{t('common.errorTitle')}{' '}
@@ -880,54 +745,7 @@ export function Pipeline() {
</>
);
}
export function Tasks() {
const { t } = useTranslation();
const [params, setParams] = useSearchParams();
const raw = params.get('filter');
const filter: TaskFilter = taskFilters.includes(raw as TaskFilter) ? (raw as TaskFilter) : 'ALL';
const query = useQuery({
queryKey: ['tasks', filter],
queryFn: ({ signal }) => api(`/tasks?filter=${filter}`, taskListSchema, { signal }),
refetchInterval: 60000,
});
return (
<>
<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 { Tasks } from '../components/tasks';
export function ReviewQueue() {
const user = useOutletContext<User>();
const { t } = useTranslation();
@@ -935,6 +753,7 @@ export function ReviewQueue() {
const [params, setParams] = useSearchParams();
const filters = reviewParams(params);
const serialized = filters.toString();
const decided = filters.get('view') === 'DECISIONS';
const allowed = canSeeReviewQueue(user.role);
const query = useQuery({
queryKey: ['review-queue', serialized],
@@ -951,10 +770,38 @@ export function ReviewQueue() {
return (
<>
<PageHeader
title={t('review.title')}
title={t(decided ? 'operations.decisionHistory' : 'review.title')}
description={t('review.description')}
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">
<label className="space-y-2 text-xs text-muted-foreground">
<span>{t('onboarding.search')}</span>
@@ -981,17 +828,23 @@ export function ReviewQueue() {
</NativeSelect>
</label>
<label className="space-y-2 text-xs text-muted-foreground">
<span>{t('onboarding.waitingTime')}</span>
<span>{t(decided ? 'workflow.decision' : 'onboarding.waitingTime')}</span>
<NativeSelect
className="w-full"
value={filters.get('waiting') ?? 'ALL'}
onChange={(event) => update('waiting', event.target.value)}
value={filters.get(decided ? 'decision' : 'waiting') ?? 'ALL'}
onChange={(event) => update(decided ? 'decision' : 'waiting', event.target.value)}
>
{['ALL', '24', '72'].map((value) => (
<option key={value} value={value}>
{t(`onboarding.waiting.${value}`)}
</option>
))}
{(decided ? ['ALL', 'APPROVED', 'CORRECTIONS', 'REJECTED'] : ['ALL', '24', '72']).map(
(value) => (
<option key={value} value={value}>
{t(
decided && value !== 'ALL'
? `workflow.${value}`
: `onboarding.waiting.${value}`,
)}
</option>
),
)}
</NativeSelect>
</label>
</section>
@@ -1009,7 +862,7 @@ export function ReviewQueue() {
</div>
<span className="inline-flex items-center gap-2 text-xs text-muted-foreground">
<Clock3 className="size-4" />
{t('review.order')}
{t(decided ? 'operations.decisionHistory' : 'review.order')}
</span>
{serialized && (
<Button variant="ghost" onClick={() => setParams({})}>
@@ -1042,10 +895,14 @@ export function ReviewQueue() {
<div className="flex flex-wrap items-center justify-between gap-4">
<div>
<p className="text-sm">
<StageAge since={review.submittedAt} waiting />
{decided ? (
t(`workflow.${review.decision}`)
) : (
<StageAge since={review.submittedAt} waiting />
)}
</p>
<p className="mt-1 text-xs text-muted-foreground">
{f.dateTime(review.submittedAt)}
{f.dateTime(review.decidedAt ?? review.submittedAt)}
</p>
</div>
<LinkButton
+135
View File
@@ -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: 'Ваши личные задачи по проверкам',
};