Added tasks, reminders, and role-specific dashboards
This commit is contained in:
@@ -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) {
|
||||
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.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,
|
||||
});
|
||||
|
||||
@@ -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(
|
||||
(
|
||||
|
||||
@@ -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: '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 },
|
||||
);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user