Built merchant management, activity history, and the pipeline
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import type { User } from '@merchantflow/contracts';
|
||||
import type { Prisma } from '@merchantflow/database';
|
||||
import { successfulStages, type Status } from '@merchantflow/contracts';
|
||||
import type { Capabilities } from '@merchantflow/contracts';
|
||||
import { workflowActions, type Evidence } from './workflow-policy.js';
|
||||
import { ApiError } from './shared.js';
|
||||
export function merchantScope(user: User): Prisma.MerchantWhereInput {
|
||||
switch (user.role) {
|
||||
@@ -24,17 +25,14 @@ export function requireSales(user: User) {
|
||||
if (!['HEAD_OF_SALES', 'ACCOUNT_MANAGER'].includes(user.role))
|
||||
throw new ApiError('FORBIDDEN', 403);
|
||||
}
|
||||
export function capabilities(
|
||||
user: User,
|
||||
merchant: { status: Status; ownerId: string | null; reviews: { decision: string }[] },
|
||||
) {
|
||||
export function capabilities(user: User, merchant: Evidence): Capabilities {
|
||||
const sales =
|
||||
user.role === 'HEAD_OF_SALES' ||
|
||||
(user.role === 'ACCOUNT_MANAGER' && merchant.ownerId === user.id);
|
||||
const locked = merchant.reviews.some((review) =>
|
||||
['PENDING', 'APPROVED'].includes(review.decision),
|
||||
);
|
||||
const index = successfulStages.findIndex((stage) => stage === merchant.status);
|
||||
const actions = workflowActions(user, merchant);
|
||||
return {
|
||||
editCommercial: sales,
|
||||
editIdentity: sales && !locked,
|
||||
@@ -46,9 +44,8 @@ export function capabilities(
|
||||
? (['KYB_NOTE'] as const)
|
||||
: (['NOTE', 'CALL', 'EMAIL', 'MEETING'] as const),
|
||||
manageTaskKind: user.role === 'COMPLIANCE_OFFICER' ? 'COMPLIANCE' : 'COMMERCIAL',
|
||||
actions,
|
||||
nextStage:
|
||||
sales && merchant.ownerId && index >= 0 && merchant.status !== 'COMPLIANCE_REVIEW'
|
||||
? (successfulStages[index + 1] ?? null)
|
||||
: null,
|
||||
actions.find((action) => action.kind === 'ADVANCE' && action.enabled)?.toStatus ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
+9
-1
@@ -15,6 +15,7 @@ import { CrmController } from './crm.js';
|
||||
import { WorkflowController } from './workflow.js';
|
||||
import { DATABASE, ApiError, ErrorFilter } from './shared.js';
|
||||
import { env } from './env.js';
|
||||
import { PublicLeadController, PublicLeadService } from './public-leads.js';
|
||||
@Controller('health')
|
||||
class HealthController {
|
||||
constructor(@Inject(DATABASE) private readonly db: PrismaClient) {}
|
||||
@@ -35,12 +36,19 @@ class DatabaseLifecycle implements OnApplicationShutdown {
|
||||
}
|
||||
}
|
||||
@Module({
|
||||
controllers: [HealthController, AuthController, CrmController, WorkflowController],
|
||||
controllers: [
|
||||
HealthController,
|
||||
AuthController,
|
||||
CrmController,
|
||||
WorkflowController,
|
||||
PublicLeadController,
|
||||
],
|
||||
providers: [
|
||||
{ provide: DATABASE, useFactory: () => createDatabase(env.DATABASE_URL) },
|
||||
DatabaseLifecycle,
|
||||
AuthService,
|
||||
SessionGuard,
|
||||
PublicLeadService,
|
||||
],
|
||||
})
|
||||
class AppModule {}
|
||||
|
||||
+126
-57
@@ -4,6 +4,8 @@ import { statuses, merchantQuerySchema, taskQuerySchema } from '@merchantflow/co
|
||||
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';
|
||||
const merchantSelect = {
|
||||
id: true,
|
||||
name: true,
|
||||
@@ -73,11 +75,22 @@ export class CrmController {
|
||||
});
|
||||
}
|
||||
@Get('merchants') async merchants(@Req() req: AuthRequest, @Query() query: unknown) {
|
||||
const { page, search, status } = merchantQuerySchema.parse(query);
|
||||
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
|
||||
? [
|
||||
{
|
||||
@@ -93,74 +106,130 @@ export class CrmController {
|
||||
: []),
|
||||
],
|
||||
};
|
||||
const [items, total] = await this.db.$transaction([
|
||||
this.db.merchant.findMany({
|
||||
where,
|
||||
select: merchantSelect,
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'asc' }],
|
||||
take: 8,
|
||||
skip: (page - 1) * 8,
|
||||
}),
|
||||
this.db.merchant.count({ where }),
|
||||
]);
|
||||
return { items, total, page, pageSize: 8 };
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
const total = await tx.merchant.count({ where });
|
||||
const page = Math.min(requestedPage, Math.max(1, Math.ceil(total / 8)));
|
||||
const items = await tx.merchant.findMany({
|
||||
where,
|
||||
select: merchantSelect,
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'asc' }],
|
||||
take: 8,
|
||||
skip: (page - 1) * 8,
|
||||
});
|
||||
return { items, total, page, pageSize: 8 };
|
||||
},
|
||||
{ isolationLevel: 'RepeatableRead' },
|
||||
);
|
||||
}
|
||||
@Get('merchants/filters') async filters(@Req() req: AuthRequest) {
|
||||
const rows = await this.db.merchant.findMany({
|
||||
where: merchantScope(req.user),
|
||||
select: { country: true, industry: true, owner: { select: { id: true, name: true } } },
|
||||
});
|
||||
const canFilterOwner = req.user.role !== 'ACCOUNT_MANAGER';
|
||||
return {
|
||||
countries: [...new Set(rows.flatMap((m) => (m.country ? [m.country] : [])))].sort(),
|
||||
industries: [...new Set(rows.flatMap((m) => (m.industry ? [m.industry] : [])))].sort(),
|
||||
owners: canFilterOwner
|
||||
? [
|
||||
...new Map(
|
||||
rows.flatMap((m) => (m.owner ? [[m.owner.id, m.owner] as const] : [])),
|
||||
).values(),
|
||||
].sort((a, b) => a.name.localeCompare(b.name))
|
||||
: [],
|
||||
canCreate: req.user.role !== 'COMPLIANCE_OFFICER',
|
||||
canFilterOwner,
|
||||
};
|
||||
}
|
||||
@Get('merchants/:id') async detail(@Req() req: AuthRequest, @Param('id') id: string) {
|
||||
const merchant = await this.db.merchant.findFirst({
|
||||
where: { AND: [merchantScope(req.user), { id }] },
|
||||
select: {
|
||||
...merchantSelect,
|
||||
checklist: {
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
const merchant = await tx.merchant.findFirst({
|
||||
where: { AND: [merchantScope(req.user), { id }] },
|
||||
select: {
|
||||
id: true,
|
||||
documentCode: true,
|
||||
state: true,
|
||||
note: true,
|
||||
changes: {
|
||||
...merchantSelect,
|
||||
checklist: {
|
||||
select: {
|
||||
id: true,
|
||||
fromState: true,
|
||||
toState: true,
|
||||
documentCode: true,
|
||||
state: true,
|
||||
note: true,
|
||||
occurredAt: true,
|
||||
actor: { select: { name: true } },
|
||||
changes: {
|
||||
select: {
|
||||
id: true,
|
||||
fromState: true,
|
||||
toState: true,
|
||||
note: true,
|
||||
occurredAt: true,
|
||||
actor: { select: { name: true } },
|
||||
},
|
||||
orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }],
|
||||
},
|
||||
},
|
||||
orderBy: { documentCode: 'asc' },
|
||||
},
|
||||
notes: {
|
||||
select: { id: true, text: true, createdAt: true, author: { select: { name: true } } },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
},
|
||||
events: { select: eventSelect, orderBy: { occurredAt: 'desc' } },
|
||||
tasks: { where: taskScope(req.user), select: taskSelect, orderBy: { dueAt: 'asc' } },
|
||||
activities: {
|
||||
select: { ...activitySelect, metadata: true },
|
||||
orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }],
|
||||
},
|
||||
reviews: {
|
||||
select: {
|
||||
id: true,
|
||||
cycle: true,
|
||||
decision: true,
|
||||
reason: true,
|
||||
submittedAt: true,
|
||||
decidedAt: true,
|
||||
submittedBy: { select: { name: true } },
|
||||
reviewer: { select: { name: true } },
|
||||
},
|
||||
orderBy: { cycle: 'desc' },
|
||||
},
|
||||
},
|
||||
orderBy: { documentCode: 'asc' },
|
||||
},
|
||||
notes: {
|
||||
select: { id: true, text: true, createdAt: true, author: { select: { name: true } } },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
},
|
||||
events: { select: eventSelect, orderBy: { occurredAt: 'desc' } },
|
||||
tasks: { where: taskScope(req.user), select: taskSelect, orderBy: { dueAt: 'asc' } },
|
||||
activities: { select: activitySelect, orderBy: [{ occurredAt: 'desc' }, { id: 'asc' }] },
|
||||
reviews: {
|
||||
select: {
|
||||
id: true,
|
||||
cycle: true,
|
||||
decision: true,
|
||||
reason: true,
|
||||
submittedAt: true,
|
||||
decidedAt: true,
|
||||
submittedBy: { select: { name: true } },
|
||||
reviewer: { select: { name: true } },
|
||||
},
|
||||
orderBy: { cycle: 'desc' },
|
||||
},
|
||||
});
|
||||
if (!merchant) throw new ApiError('NOT_FOUND', 404);
|
||||
const evidence = await tx.merchant.findFirstOrThrow({
|
||||
where: { AND: [merchantScope(req.user), { id }] },
|
||||
include: evidenceInclude,
|
||||
});
|
||||
const history = await merchantHistory(merchant, tx);
|
||||
return {
|
||||
...merchant,
|
||||
activities: merchant.activities.map(({ metadata: _metadata, ...activity }) => activity),
|
||||
capabilities: capabilities(req.user, evidence),
|
||||
history,
|
||||
};
|
||||
},
|
||||
});
|
||||
if (!merchant) throw new ApiError('NOT_FOUND', 404);
|
||||
return { ...merchant, capabilities: capabilities(req.user, merchant) };
|
||||
{ isolationLevel: 'RepeatableRead' },
|
||||
);
|
||||
}
|
||||
@Get('pipeline') pipeline(@Req() req: AuthRequest) {
|
||||
return this.db.merchant.findMany({
|
||||
where: merchantScope(req.user),
|
||||
select: merchantSelect,
|
||||
orderBy: { stageEnteredAt: 'asc' },
|
||||
});
|
||||
@Get('pipeline') async pipeline(@Req() req: AuthRequest) {
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
const merchants = await tx.merchant.findMany({
|
||||
where: merchantScope(req.user),
|
||||
select: merchantSelect,
|
||||
orderBy: [{ stageEnteredAt: 'asc' }, { id: 'asc' }],
|
||||
});
|
||||
const evidence = await tx.merchant.findMany({
|
||||
where: merchantScope(req.user),
|
||||
include: evidenceInclude,
|
||||
});
|
||||
const byId = new Map(evidence.map((merchant) => [merchant.id, merchant]));
|
||||
return merchants.map((merchant) => ({
|
||||
...merchant,
|
||||
capabilities: capabilities(req.user, byId.get(merchant.id)!),
|
||||
}));
|
||||
},
|
||||
{ isolationLevel: 'RepeatableRead' },
|
||||
);
|
||||
}
|
||||
@Get('tasks') tasks(@Req() req: AuthRequest, @Query() query: unknown) {
|
||||
const { filter } = taskQuerySchema.parse(query);
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import type { HistoryEntry, Status } from '@merchantflow/contracts';
|
||||
import type { Prisma } from '@merchantflow/database';
|
||||
|
||||
type Actor = { name: string } | null;
|
||||
type Sources = {
|
||||
notes: { id: string; text: string; createdAt: Date; author: { name: string } }[];
|
||||
events: {
|
||||
id: string;
|
||||
fromStatus: Status | null;
|
||||
toStatus: Status;
|
||||
occurredAt: Date;
|
||||
note: string | null;
|
||||
actor: Actor;
|
||||
}[];
|
||||
activities: {
|
||||
id: string;
|
||||
kind: 'NOTE' | 'CALL' | 'EMAIL' | 'MEETING' | 'KYB_NOTE' | 'AUDIT';
|
||||
text: string;
|
||||
occurredAt: Date;
|
||||
updatedAt: Date;
|
||||
actor: Actor;
|
||||
metadata: unknown;
|
||||
}[];
|
||||
reviews: {
|
||||
id: string;
|
||||
cycle: number;
|
||||
decision: 'PENDING' | 'APPROVED' | 'REJECTED' | 'CORRECTIONS';
|
||||
decidedAt: Date | null;
|
||||
reason: string | null;
|
||||
reviewer: Actor;
|
||||
}[];
|
||||
};
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === 'object' && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
export async function merchantHistory(
|
||||
m: Sources,
|
||||
db: Prisma.TransactionClient,
|
||||
): Promise<HistoryEntry[]> {
|
||||
const ownerIds = new Set<string>();
|
||||
for (const activity of m.activities) {
|
||||
const meta = record(activity.metadata);
|
||||
if (activity.text === 'Manager assignment updated')
|
||||
for (const key of ['previousOwnerId', 'ownerId'])
|
||||
if (typeof meta[key] === 'string') ownerIds.add(meta[key]);
|
||||
}
|
||||
const users = ownerIds.size
|
||||
? await db.user.findMany({
|
||||
where: { id: { in: [...ownerIds] } },
|
||||
select: { id: true, name: true },
|
||||
})
|
||||
: [];
|
||||
const owner = (snapshot: unknown, id: unknown) => {
|
||||
const value = record(snapshot);
|
||||
if (typeof value.id === 'string' && typeof value.name === 'string')
|
||||
return { id: value.id, name: value.name };
|
||||
return users.find((user) => user.id === id) ?? null;
|
||||
};
|
||||
const history: HistoryEntry[] = [
|
||||
...m.notes.map(
|
||||
(note): HistoryEntry => ({
|
||||
id: `note:${note.id}`,
|
||||
kind: 'INTERACTION',
|
||||
occurredAt: note.createdAt.toISOString(),
|
||||
updatedAt: note.createdAt.toISOString(),
|
||||
actor: note.author,
|
||||
activityId: null,
|
||||
activityKind: 'NOTE',
|
||||
text: note.text,
|
||||
}),
|
||||
),
|
||||
...m.events.map(
|
||||
(event): HistoryEntry => ({
|
||||
id: `stage:${event.id}`,
|
||||
kind: 'STAGE',
|
||||
occurredAt: event.occurredAt.toISOString(),
|
||||
actor: event.actor,
|
||||
fromStatus: event.fromStatus,
|
||||
toStatus: event.toStatus,
|
||||
reason: event.note,
|
||||
}),
|
||||
),
|
||||
];
|
||||
for (const review of m.reviews) {
|
||||
if (!review.decidedAt || review.decision === 'PENDING') continue;
|
||||
history.push({
|
||||
id: `review:${review.id}`,
|
||||
kind: 'REVIEW',
|
||||
occurredAt: review.decidedAt.toISOString(),
|
||||
actor: review.reviewer,
|
||||
cycle: review.cycle,
|
||||
decision: review.decision,
|
||||
reason: review.reason,
|
||||
});
|
||||
}
|
||||
for (const activity of m.activities) {
|
||||
const base = {
|
||||
id: `activity:${activity.id}`,
|
||||
occurredAt: activity.occurredAt.toISOString(),
|
||||
actor: activity.actor,
|
||||
};
|
||||
const meta = record(activity.metadata);
|
||||
if (activity.kind !== 'AUDIT') {
|
||||
history.push({
|
||||
...base,
|
||||
kind: 'INTERACTION',
|
||||
activityId: activity.id,
|
||||
activityKind: activity.kind,
|
||||
text: activity.text,
|
||||
updatedAt: activity.updatedAt.toISOString(),
|
||||
});
|
||||
} else if (activity.text === 'Manager assignment updated') {
|
||||
history.push({
|
||||
...base,
|
||||
kind: 'OWNERSHIP',
|
||||
previousOwner: owner(meta.previousOwner, meta.previousOwnerId),
|
||||
owner: owner(meta.owner, meta.ownerId),
|
||||
});
|
||||
} else if (
|
||||
!meta.toStatus &&
|
||||
!meta.reviewId &&
|
||||
!(
|
||||
activity.text === 'Merchant created' &&
|
||||
m.events.some(
|
||||
(event) =>
|
||||
event.fromStatus === null &&
|
||||
event.occurredAt.getTime() === activity.occurredAt.getTime(),
|
||||
)
|
||||
)
|
||||
) {
|
||||
history.push({ ...base, kind: 'AUDIT', text: activity.text });
|
||||
}
|
||||
}
|
||||
return history.sort(
|
||||
(a, b) => b.occurredAt.localeCompare(a.occurredAt) || a.id.localeCompare(b.id),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import { Body, Controller, HttpCode, Inject, Injectable, Post, Req, Res } from '@nestjs/common';
|
||||
import { createHash } from 'node:crypto';
|
||||
import type { Request, Response } from 'express';
|
||||
import { z } from 'zod';
|
||||
import { PrismaClient } from '@merchantflow/database';
|
||||
import {
|
||||
documentCodes,
|
||||
publicLeadKeySchema,
|
||||
publicLeadSchema,
|
||||
type PublicLead,
|
||||
} from '@merchantflow/contracts';
|
||||
import { AuthService } from './auth.js';
|
||||
import { ApiError, DATABASE } from './shared.js';
|
||||
|
||||
const accepted = { ok: true } as const;
|
||||
const envelope = z.object({ companyFax: z.string().max(512).default('') }).passthrough();
|
||||
const windowMs = 15 * 60 * 1000;
|
||||
type Bucket = { until: number; count: number; keys: Set<string> };
|
||||
class LeadLimitError extends ApiError {
|
||||
constructor(readonly retryAfter: number) {
|
||||
super('TOO_MANY_REQUESTS', 429);
|
||||
}
|
||||
}
|
||||
|
||||
// Intentionally process-local, matching this application's single-process deployment.
|
||||
export class LeadRateLimiter {
|
||||
private buckets = new Map<string, Bucket>();
|
||||
constructor(
|
||||
private now = Date.now,
|
||||
private capacity = 10000,
|
||||
) {}
|
||||
private take(key: string, limit: number, submissionKey?: string) {
|
||||
const now = this.now();
|
||||
for (const [id, bucket] of this.buckets) if (bucket.until <= now) this.buckets.delete(id);
|
||||
let bucket = this.buckets.get(key);
|
||||
if (!bucket && this.buckets.size >= this.capacity) {
|
||||
const earliest = Math.min(...[...this.buckets.values()].map((item) => item.until));
|
||||
return Math.max(1, Math.ceil((earliest - now) / 1000));
|
||||
}
|
||||
bucket ??= { until: now + windowMs, count: 0, keys: new Set() };
|
||||
if (submissionKey && bucket.keys.has(submissionKey)) return 0;
|
||||
if (bucket.count >= limit) return Math.max(1, Math.ceil((bucket.until - now) / 1000));
|
||||
bucket.count++;
|
||||
if (submissionKey) bucket.keys.add(submissionKey);
|
||||
this.buckets.set(key, bucket);
|
||||
return 0;
|
||||
}
|
||||
attemptIp(ip: string) {
|
||||
return this.take(`ip:${ip}`, 10);
|
||||
}
|
||||
reserveEmail(email: string, key: string) {
|
||||
return this.take(`email:${email}`, 3, key);
|
||||
}
|
||||
releaseEmail(email: string, key: string) {
|
||||
const bucket = this.buckets.get(`email:${email}`);
|
||||
if (bucket?.keys.delete(key)) bucket.count--;
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class PublicLeadService {
|
||||
private limits = new LeadRateLimiter();
|
||||
private inFlight = new Map<string, { hash: string; promise: Promise<typeof accepted> }>();
|
||||
constructor(
|
||||
@Inject(DATABASE) private db: PrismaClient,
|
||||
private auth: AuthService,
|
||||
) {}
|
||||
|
||||
async submit(body: unknown, req: Request, res: Response) {
|
||||
this.auth.checkOrigin(req);
|
||||
// Honeypots count toward IP pressure but never disclose rejection to the submitter.
|
||||
const retryAfter = this.limits.attemptIp(req.ip ?? 'local');
|
||||
const { companyFax } = envelope.parse(body);
|
||||
const { idempotencyKey } = publicLeadKeySchema.parse({
|
||||
idempotencyKey: req.get('Idempotency-Key'),
|
||||
});
|
||||
if (companyFax.length > 0) return accepted;
|
||||
if (retryAfter) {
|
||||
res.setHeader('Retry-After', retryAfter);
|
||||
throw new LeadLimitError(retryAfter);
|
||||
}
|
||||
const input = publicLeadSchema.parse(body);
|
||||
// Schema output fixes property order; locale and honeypot are not business data.
|
||||
const { companyFax: _trap, ...business } = input;
|
||||
const hash = createHash('sha256').update(JSON.stringify(business)).digest('hex');
|
||||
const pending = this.inFlight.get(idempotencyKey);
|
||||
if (pending && pending.hash !== hash) throw new ApiError('IDEMPOTENCY_CONFLICT', 409);
|
||||
const operation = pending ?? { hash, promise: this.persist(idempotencyKey, hash, input) };
|
||||
if (!pending) this.inFlight.set(idempotencyKey, operation);
|
||||
try {
|
||||
return await operation.promise;
|
||||
} catch (error) {
|
||||
if (error instanceof LeadLimitError) res.setHeader('Retry-After', error.retryAfter);
|
||||
throw error;
|
||||
} finally {
|
||||
if (this.inFlight.get(idempotencyKey) === operation) this.inFlight.delete(idempotencyKey);
|
||||
}
|
||||
}
|
||||
|
||||
private async replay(key: string, hash: string) {
|
||||
const existing = await this.db.merchant.findUnique({
|
||||
where: { publicSubmissionKey: key },
|
||||
select: { publicSubmissionHash: true },
|
||||
});
|
||||
if (!existing) return false;
|
||||
if (existing.publicSubmissionHash !== hash) throw new ApiError('IDEMPOTENCY_CONFLICT', 409);
|
||||
return true;
|
||||
}
|
||||
|
||||
private async persist(key: string, hash: string, input: PublicLead) {
|
||||
if (await this.replay(key, hash)) return accepted;
|
||||
const retryAfter = this.limits.reserveEmail(input.contactEmail, key);
|
||||
if (retryAfter) throw new LeadLimitError(retryAfter);
|
||||
try {
|
||||
const { companyFax: _trap, ...business } = input;
|
||||
const now = new Date();
|
||||
await this.db.$transaction(async (tx) => {
|
||||
await tx.merchant.create({
|
||||
data: {
|
||||
...business,
|
||||
status: 'NEW_LEAD',
|
||||
source: 'LANDING_PAGE',
|
||||
ownerId: null,
|
||||
version: 0,
|
||||
publicSubmissionKey: key,
|
||||
publicSubmissionHash: hash,
|
||||
createdAt: now,
|
||||
stageEnteredAt: now,
|
||||
checklist: {
|
||||
create: documentCodes.map((documentCode) => ({ documentCode, state: 'MISSING' })),
|
||||
},
|
||||
events: { create: { fromStatus: null, toStatus: 'NEW_LEAD', occurredAt: now } },
|
||||
activities: {
|
||||
create: {
|
||||
kind: 'AUDIT',
|
||||
text: 'Lead received from landing page',
|
||||
occurredAt: now,
|
||||
metadata: { source: 'LANDING_PAGE' },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
return accepted;
|
||||
} catch (error) {
|
||||
this.limits.releaseEmail(input.contactEmail, key);
|
||||
// Another process may have won the unique-key race. The failed transaction is over.
|
||||
if (
|
||||
typeof error === 'object' &&
|
||||
error !== null &&
|
||||
'code' in error &&
|
||||
error.code === 'P2002'
|
||||
) {
|
||||
if (await this.replay(key, hash)) return accepted;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Controller('public/leads')
|
||||
export class PublicLeadController {
|
||||
constructor(private leads: PublicLeadService) {}
|
||||
@Post()
|
||||
@HttpCode(202)
|
||||
create(@Body() body: unknown, @Req() req: Request, @Res({ passthrough: true }) res: Response) {
|
||||
return this.leads.submit(body, req, res);
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,12 @@ export interface AuthRequest extends Request {
|
||||
user: User;
|
||||
}
|
||||
export class ApiError extends HttpException {
|
||||
constructor(code: string, status: number) {
|
||||
super({ code }, status);
|
||||
constructor(
|
||||
code: string,
|
||||
status: number,
|
||||
details?: { blockingReasons: import('@merchantflow/contracts').BlockingReason[] },
|
||||
) {
|
||||
super({ code, ...details }, status);
|
||||
}
|
||||
}
|
||||
@Catch()
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import {
|
||||
checklistComplete,
|
||||
reviewSnapshot,
|
||||
snapshotsEqual,
|
||||
type Prisma,
|
||||
} from '@merchantflow/database';
|
||||
import {
|
||||
countryCodes,
|
||||
industries,
|
||||
successfulStages,
|
||||
type BlockingReason,
|
||||
type User,
|
||||
type WorkflowAction,
|
||||
} from '@merchantflow/contracts';
|
||||
|
||||
export const evidenceInclude = {
|
||||
checklist: {
|
||||
include: { changes: { orderBy: [{ occurredAt: 'asc' as const }, { id: 'asc' as const }] } },
|
||||
},
|
||||
reviews: {
|
||||
include: { reviewer: { select: { role: true } } },
|
||||
orderBy: { cycle: 'desc' as const },
|
||||
},
|
||||
activities: { select: { kind: true } },
|
||||
} satisfies Prisma.MerchantInclude;
|
||||
export type Evidence = Prisma.MerchantGetPayload<{ include: typeof evidenceInclude }>;
|
||||
|
||||
export function receivedHistory(merchant: Evidence, at: Date) {
|
||||
return (
|
||||
checklistComplete(merchant.checklist) &&
|
||||
merchant.checklist.every(
|
||||
(item) =>
|
||||
item.changes.filter((change) => change.occurredAt <= at).at(-1)?.toState === 'RECEIVED',
|
||||
)
|
||||
);
|
||||
}
|
||||
export function validApproval(merchant: Evidence) {
|
||||
const review = merchant.reviews[0];
|
||||
return !!(
|
||||
review?.decision === 'APPROVED' &&
|
||||
review.reviewer?.role === 'COMPLIANCE_OFFICER' &&
|
||||
review.decidedAt &&
|
||||
review.decidedAt >= review.submittedAt &&
|
||||
receivedHistory(merchant, review.submittedAt) &&
|
||||
snapshotsEqual(review.snapshot, reviewSnapshot(merchant))
|
||||
);
|
||||
}
|
||||
export function qualificationFields(merchant: Evidence) {
|
||||
const fields: string[] = [];
|
||||
for (const field of ['name', 'website', 'contactName', 'contactEmail'] as const)
|
||||
if (!merchant[field]?.trim()) fields.push(field);
|
||||
if (!merchant.country || !countryCodes.includes(merchant.country)) fields.push('country');
|
||||
if (!merchant.industry || !industries.some((value) => value === merchant.industry))
|
||||
fields.push('industry');
|
||||
if (merchant.estimatedMonthlyVolumeUsd === null) fields.push('estimatedMonthlyVolumeUsd');
|
||||
return fields;
|
||||
}
|
||||
export function workflowActions(user: User, merchant: Evidence): WorkflowAction[] {
|
||||
if (['LIVE', 'REJECTED'].includes(merchant.status)) return [];
|
||||
const sales =
|
||||
user.role === 'HEAD_OF_SALES' ||
|
||||
(user.role === 'ACCOUNT_MANAGER' && merchant.ownerId === user.id);
|
||||
if (merchant.status === 'COMPLIANCE_REVIEW') {
|
||||
const blockers: BlockingReason[] =
|
||||
user.role === 'COMPLIANCE_OFFICER' ? [] : [{ code: 'COMPLIANCE_ONLY' }];
|
||||
if (!merchant.reviews.some((review) => review.decision === 'PENDING'))
|
||||
blockers.push({ code: 'REVIEW_PENDING' });
|
||||
return [
|
||||
{
|
||||
kind: 'REVIEW',
|
||||
toStatus: null,
|
||||
enabled: !blockers.length,
|
||||
reasonRequired: false,
|
||||
blockingReasons: blockers,
|
||||
},
|
||||
];
|
||||
}
|
||||
const toStatus =
|
||||
successfulStages[successfulStages.findIndex((stage) => stage === merchant.status) + 1]!;
|
||||
const blockingReasons: BlockingReason[] = [];
|
||||
if (!sales) blockingReasons.push({ code: 'SALES_ONLY' });
|
||||
if (!merchant.ownerId) blockingReasons.push({ code: 'ASSIGNMENT_REQUIRED' });
|
||||
if (
|
||||
toStatus === 'CONTACTED' &&
|
||||
!merchant.activities.some((a) => a.kind === 'CALL' || a.kind === 'EMAIL')
|
||||
)
|
||||
blockingReasons.push({ code: 'CONTACT_REQUIRED' });
|
||||
if (toStatus === 'QUALIFIED') {
|
||||
const fields = qualificationFields(merchant);
|
||||
if (fields.length) blockingReasons.push({ code: 'QUALIFICATION_INCOMPLETE', fields });
|
||||
}
|
||||
if (toStatus === 'COMPLIANCE_REVIEW') {
|
||||
if (!receivedHistory(merchant, new Date()))
|
||||
blockingReasons.push({ code: 'DOCUMENTS_REQUIRED' });
|
||||
if (merchant.reviews.some((r) => r.decision === 'PENDING'))
|
||||
blockingReasons.push({ code: 'REVIEW_PENDING' });
|
||||
}
|
||||
if (['TESTING', 'LIVE'].includes(toStatus) && !validApproval(merchant))
|
||||
blockingReasons.push({ code: 'APPROVAL_REQUIRED' });
|
||||
const actions: WorkflowAction[] = [
|
||||
{
|
||||
kind: 'ADVANCE',
|
||||
toStatus,
|
||||
enabled: !blockingReasons.length,
|
||||
reasonRequired: false,
|
||||
blockingReasons,
|
||||
},
|
||||
];
|
||||
if (
|
||||
sales &&
|
||||
(['NEW_LEAD', 'CONTACTED', 'QUALIFIED'].includes(merchant.status) ||
|
||||
user.role === 'HEAD_OF_SALES')
|
||||
)
|
||||
actions.push({
|
||||
kind: 'REJECT',
|
||||
toStatus: 'REJECTED',
|
||||
enabled: true,
|
||||
reasonRequired: true,
|
||||
blockingReasons: [],
|
||||
});
|
||||
return actions;
|
||||
}
|
||||
+106
-60
@@ -2,7 +2,6 @@ import { Body, Controller, Inject, Param, Patch, Post, Req, UseGuards } from '@n
|
||||
import {
|
||||
PrismaClient,
|
||||
type Prisma,
|
||||
checklistComplete,
|
||||
reviewSnapshot,
|
||||
reviewedFields,
|
||||
snapshotsEqual,
|
||||
@@ -15,40 +14,19 @@ import {
|
||||
reviewDecisionSchema,
|
||||
taskInputSchema,
|
||||
transitionSchema,
|
||||
successfulStages,
|
||||
merchantCreateSchema,
|
||||
documentCodes,
|
||||
} from '@merchantflow/contracts';
|
||||
import { SessionGuard } from './auth.js';
|
||||
import { capabilities, merchantScope, requireSales, taskScope } from './access.js';
|
||||
import { ApiError, DATABASE, type AuthRequest } from './shared.js';
|
||||
|
||||
const evidenceInclude = {
|
||||
checklist: { include: { changes: { orderBy: { occurredAt: 'asc' as const } } } },
|
||||
reviews: {
|
||||
include: { reviewer: { select: { role: true } } },
|
||||
orderBy: { cycle: 'desc' as const },
|
||||
},
|
||||
} as const;
|
||||
type Evidence = Prisma.MerchantGetPayload<{ include: typeof evidenceInclude }>;
|
||||
function receivedHistory(merchant: Evidence, at: Date) {
|
||||
return (
|
||||
checklistComplete(merchant.checklist) &&
|
||||
merchant.checklist.every(
|
||||
(item) =>
|
||||
item.changes.filter((change) => change.occurredAt <= at).at(-1)?.toState === 'RECEIVED',
|
||||
)
|
||||
);
|
||||
}
|
||||
function validApproval(merchant: Evidence) {
|
||||
const review = merchant.reviews[0];
|
||||
return (
|
||||
review?.decision === 'APPROVED' &&
|
||||
review.reviewer?.role === 'COMPLIANCE_OFFICER' &&
|
||||
review.decidedAt &&
|
||||
review.decidedAt >= review.submittedAt &&
|
||||
receivedHistory(merchant, review.submittedAt) &&
|
||||
snapshotsEqual(review.snapshot, reviewSnapshot(merchant))
|
||||
);
|
||||
}
|
||||
import {
|
||||
evidenceInclude,
|
||||
receivedHistory,
|
||||
workflowActions,
|
||||
type Evidence,
|
||||
} from './workflow-policy.js';
|
||||
|
||||
@UseGuards(SessionGuard)
|
||||
@Controller('merchants')
|
||||
@@ -63,8 +41,8 @@ export class WorkflowController {
|
||||
) {
|
||||
await this.db.$transaction(async (tx) => {
|
||||
const scope = { AND: [merchantScope(req.user), { id }] };
|
||||
const merchant = await tx.merchant.findFirst({ where: scope, include: evidenceInclude });
|
||||
if (!merchant) throw new ApiError('NOT_FOUND', 404);
|
||||
if (!(await tx.merchant.findFirst({ where: scope, select: { id: true } })))
|
||||
throw new ApiError('NOT_FOUND', 404);
|
||||
// This conditional write locks the parent and rechecks ownership/version after any wait.
|
||||
// Every child mutation and ownership change takes the same lock before writing.
|
||||
const claimed = await tx.merchant.updateMany({
|
||||
@@ -76,6 +54,10 @@ export class WorkflowController {
|
||||
throw new ApiError('NOT_FOUND', 404);
|
||||
throw new ApiError('CONFLICT', 409);
|
||||
}
|
||||
const merchant = await tx.merchant.findFirstOrThrow({
|
||||
where: scope,
|
||||
include: evidenceInclude,
|
||||
});
|
||||
await action(tx, merchant);
|
||||
});
|
||||
return { ok: true };
|
||||
@@ -86,9 +68,10 @@ export class WorkflowController {
|
||||
merchantId: string,
|
||||
text: string,
|
||||
metadata?: Prisma.InputJsonValue,
|
||||
occurredAt = new Date(),
|
||||
) {
|
||||
await tx.activity.create({
|
||||
data: { merchantId, actorId: req.user.id, kind: 'AUDIT', text, metadata },
|
||||
data: { merchantId, actorId: req.user.id, kind: 'AUDIT', text, metadata, occurredAt },
|
||||
});
|
||||
}
|
||||
private async stage(
|
||||
@@ -103,7 +86,7 @@ export class WorkflowController {
|
||||
where: { AND: [merchantScope(req.user), { id: merchant.id }] },
|
||||
data: { status: toStatus, stageEnteredAt: occurredAt },
|
||||
});
|
||||
await tx.statusEvent.create({
|
||||
const event = await tx.statusEvent.create({
|
||||
data: {
|
||||
merchantId: merchant.id,
|
||||
actorId: req.user.id,
|
||||
@@ -113,10 +96,69 @@ export class WorkflowController {
|
||||
note,
|
||||
},
|
||||
});
|
||||
await this.audit(tx, req, merchant.id, `${merchant.status} → ${toStatus}`, {
|
||||
fromStatus: merchant.status,
|
||||
toStatus,
|
||||
note: note ?? null,
|
||||
await this.audit(
|
||||
tx,
|
||||
req,
|
||||
merchant.id,
|
||||
`${merchant.status} → ${toStatus}`,
|
||||
{
|
||||
fromStatus: merchant.status,
|
||||
toStatus,
|
||||
note: note ?? null,
|
||||
eventId: event.id,
|
||||
},
|
||||
occurredAt,
|
||||
);
|
||||
}
|
||||
|
||||
@Post() async create(@Req() req: AuthRequest, @Body() body: unknown) {
|
||||
requireSales(req.user);
|
||||
const { ownerId: requestedOwner, ...data } = merchantCreateSchema.parse(body);
|
||||
if (
|
||||
req.user.role === 'ACCOUNT_MANAGER' &&
|
||||
requestedOwner !== undefined &&
|
||||
requestedOwner !== req.user.id
|
||||
)
|
||||
throw new ApiError('FORBIDDEN', 403);
|
||||
const ownerId = req.user.role === 'ACCOUNT_MANAGER' ? req.user.id : (requestedOwner ?? null);
|
||||
return this.db.$transaction(async (tx) => {
|
||||
if (
|
||||
ownerId &&
|
||||
!(await tx.user.findFirst({
|
||||
where: { id: ownerId, role: 'ACCOUNT_MANAGER' },
|
||||
select: { id: true },
|
||||
}))
|
||||
)
|
||||
throw new ApiError('VALIDATION_ERROR', 400);
|
||||
const now = new Date();
|
||||
return tx.merchant.create({
|
||||
data: {
|
||||
...data,
|
||||
ownerId,
|
||||
status: 'NEW_LEAD',
|
||||
createdAt: now,
|
||||
stageEnteredAt: now,
|
||||
checklist: { create: documentCodes.map((documentCode) => ({ documentCode })) },
|
||||
events: {
|
||||
create: {
|
||||
fromStatus: null,
|
||||
toStatus: 'NEW_LEAD',
|
||||
actorId: req.user.id,
|
||||
occurredAt: now,
|
||||
},
|
||||
},
|
||||
activities: {
|
||||
create: {
|
||||
kind: 'AUDIT',
|
||||
text: 'Merchant created',
|
||||
actorId: req.user.id,
|
||||
occurredAt: now,
|
||||
metadata: { ownerId },
|
||||
},
|
||||
},
|
||||
},
|
||||
select: { id: true, version: true },
|
||||
});
|
||||
});
|
||||
}
|
||||
@Patch(':id') edit(@Req() req: AuthRequest, @Param('id') id: string, @Body() body: unknown) {
|
||||
@@ -141,13 +183,18 @@ export class WorkflowController {
|
||||
const { version, ownerId } = assignmentSchema.parse(body);
|
||||
return this.mutate(req, id, version, async (tx, merchant) => {
|
||||
if (req.user.role !== 'HEAD_OF_SALES') throw new ApiError('FORBIDDEN', 403);
|
||||
if (
|
||||
!(await tx.user.findFirst({
|
||||
where: { id: ownerId, role: 'ACCOUNT_MANAGER' },
|
||||
select: { id: true },
|
||||
}))
|
||||
)
|
||||
throw new ApiError('VALIDATION_ERROR', 400);
|
||||
const owner = await tx.user.findFirst({
|
||||
where: { id: ownerId, role: 'ACCOUNT_MANAGER' },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (!owner) throw new ApiError('VALIDATION_ERROR', 400);
|
||||
if (merchant.ownerId === ownerId) return;
|
||||
const previousOwner = merchant.ownerId
|
||||
? await tx.user.findUnique({
|
||||
where: { id: merchant.ownerId },
|
||||
select: { id: true, name: true },
|
||||
})
|
||||
: null;
|
||||
await tx.merchant.updateMany({ where: { id }, data: { ownerId } });
|
||||
await tx.task.updateMany({
|
||||
where: { merchantId: id, kind: 'COMMERCIAL', status: 'OPEN' },
|
||||
@@ -156,6 +203,8 @@ export class WorkflowController {
|
||||
await this.audit(tx, req, id, 'Manager assignment updated', {
|
||||
previousOwnerId: merchant.ownerId,
|
||||
ownerId,
|
||||
previousOwner,
|
||||
owner,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -164,24 +213,23 @@ export class WorkflowController {
|
||||
@Param('id') id: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
const { version, toStatus } = transitionSchema.parse(body);
|
||||
const { version, toStatus, reason } = transitionSchema.parse(body);
|
||||
return this.mutate(req, id, version, async (tx, merchant) => {
|
||||
requireSales(req.user);
|
||||
const index = successfulStages.findIndex((stage) => stage === merchant.status);
|
||||
const action = workflowActions(req.user, merchant).find(
|
||||
(candidate) => candidate.toStatus === toStatus && candidate.kind !== 'REVIEW',
|
||||
);
|
||||
if (
|
||||
!merchant.ownerId ||
|
||||
index < 0 ||
|
||||
successfulStages[index + 1] !== toStatus ||
|
||||
merchant.status === 'COMPLIANCE_REVIEW'
|
||||
merchant.status === 'COMPLIANCE_REVIEW' ||
|
||||
(toStatus === 'REJECTED' && !action && !['LIVE', 'REJECTED'].includes(merchant.status))
|
||||
)
|
||||
throw new ApiError('WORKFLOW_INVALID', 409);
|
||||
throw new ApiError('FORBIDDEN', 403);
|
||||
if (!action || !action.enabled)
|
||||
throw new ApiError('WORKFLOW_INVALID', 409, {
|
||||
blockingReasons: action?.blockingReasons ?? [],
|
||||
});
|
||||
if (toStatus === 'COMPLIANCE_REVIEW') {
|
||||
const submittedAt = new Date();
|
||||
if (
|
||||
!receivedHistory(merchant, submittedAt) ||
|
||||
merchant.reviews.some((r) => r.decision === 'PENDING')
|
||||
)
|
||||
throw new ApiError('WORKFLOW_INVALID', 409);
|
||||
await tx.complianceReview.create({
|
||||
data: {
|
||||
merchantId: id,
|
||||
@@ -192,9 +240,7 @@ export class WorkflowController {
|
||||
},
|
||||
});
|
||||
}
|
||||
if (['TESTING', 'LIVE'].includes(toStatus) && !validApproval(merchant))
|
||||
throw new ApiError('WORKFLOW_INVALID', 409);
|
||||
await this.stage(tx, req, merchant, toStatus);
|
||||
await this.stage(tx, req, merchant, toStatus, reason);
|
||||
});
|
||||
}
|
||||
@Patch(':id/checklist/:itemId') checklist(
|
||||
|
||||
@@ -262,6 +262,7 @@ async function fixture(id, status = 'NEW_LEAD', ownerId = 'user-manager1') {
|
||||
data: {
|
||||
id,
|
||||
name: 'Workflow Test',
|
||||
estimatedMonthlyVolumeUsd: '10000',
|
||||
legalName: 'Workflow Test Ltd',
|
||||
website: 'https://workflow.example',
|
||||
industry: 'SOFTWARE',
|
||||
@@ -438,11 +439,30 @@ test('corrections, resubmission, approval and activation preserve one merchant a
|
||||
mutate(
|
||||
`/merchants/${id}/transitions`,
|
||||
cookie,
|
||||
{ version: (await detail()).version, toStatus },
|
||||
{
|
||||
version: (await detail()).version,
|
||||
toStatus,
|
||||
...(toStatus === 'REJECTED' ? { reason: 'Attempted terminal transition' } : {}),
|
||||
},
|
||||
'POST',
|
||||
);
|
||||
try {
|
||||
assert.equal((await move('LIVE')).status, 409);
|
||||
assert.equal(
|
||||
(
|
||||
await mutate(
|
||||
`/merchants/${id}/activities`,
|
||||
sales,
|
||||
{
|
||||
version: (await detail()).version,
|
||||
kind: 'CALL',
|
||||
text: 'Confirmed contact before progression',
|
||||
},
|
||||
'POST',
|
||||
)
|
||||
).status,
|
||||
201,
|
||||
);
|
||||
for (const stage of ['CONTACTED', 'QUALIFIED', 'KYB'])
|
||||
assert.equal((await move(stage)).status, 201);
|
||||
assert.equal((await move('COMPLIANCE_REVIEW')).status, 409);
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
import { beforeEach, afterEach, after, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { createDatabase } from '@merchantflow/database';
|
||||
import { merchantDetailSchema, dashboardSchema } from '@merchantflow/contracts';
|
||||
import { createApp } from '../dist/app.js';
|
||||
|
||||
if (!process.env.DATABASE_URL?.endsWith('/merchantflow_test'))
|
||||
throw new Error('Only the isolated test database is allowed');
|
||||
const db = createDatabase(process.env.DATABASE_URL);
|
||||
const keys = new Set();
|
||||
let app, base;
|
||||
const origin = process.env.APP_ORIGIN;
|
||||
const input = () => ({
|
||||
name: 'Public lead integration',
|
||||
contactName: 'Test Contact',
|
||||
contactEmail: `lead-${randomUUID()}@example.test`,
|
||||
website: 'example.test',
|
||||
country: 'GB',
|
||||
industry: 'OTHER',
|
||||
estimatedMonthlyVolumeUsd: '1234,50',
|
||||
companyFax: '',
|
||||
});
|
||||
function key() {
|
||||
const value = randomUUID();
|
||||
keys.add(value);
|
||||
return value;
|
||||
}
|
||||
async function start() {
|
||||
app = await createApp();
|
||||
await app.listen(0, '127.0.0.1');
|
||||
base = `${await app.getUrl()}/api`;
|
||||
}
|
||||
async function request(path, body, headers = {}, method = 'POST', url = base) {
|
||||
const response = await fetch(`${url}${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
origin,
|
||||
...(body !== undefined ? { 'content-type': 'application/json' } : {}),
|
||||
...headers,
|
||||
},
|
||||
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
return { status: response.status, body: await response.json(), headers: response.headers };
|
||||
}
|
||||
const submit = (data, id, headers = {}, url = base) =>
|
||||
request('/public/leads', data, { 'Idempotency-Key': id, ...headers }, 'POST', url);
|
||||
async function cookie(account) {
|
||||
const result = await request('/auth/login', {
|
||||
email: `${account}@merchantflow.test`,
|
||||
password: 'MerchantFlow123!',
|
||||
});
|
||||
assert.equal(result.status, 201);
|
||||
return result.headers.get('set-cookie').split(';')[0];
|
||||
}
|
||||
beforeEach(start);
|
||||
afterEach(async () => {
|
||||
await app?.close();
|
||||
await db.merchant.deleteMany({ where: { publicSubmissionKey: { in: [...keys] } } });
|
||||
keys.clear();
|
||||
});
|
||||
after(() => db.$disconnect());
|
||||
|
||||
test('public submission persists complete onboarding context and respects CRM permissions', async () => {
|
||||
const id = key(),
|
||||
data = input();
|
||||
const result = await submit(data, id);
|
||||
assert.equal(result.status, 202);
|
||||
assert.deepEqual(result.body, { ok: true });
|
||||
const merchant = await db.merchant.findUnique({
|
||||
where: { publicSubmissionKey: id },
|
||||
include: { activities: true, events: true, checklist: { include: { changes: true } } },
|
||||
});
|
||||
assert.equal(merchant.status, 'NEW_LEAD');
|
||||
assert.equal(merchant.ownerId, null);
|
||||
assert.equal(merchant.source, 'LANDING_PAGE');
|
||||
assert.equal(merchant.version, 0);
|
||||
assert.equal(merchant.name, data.name);
|
||||
assert.equal(merchant.contactName, data.contactName);
|
||||
assert.equal(merchant.contactEmail, data.contactEmail);
|
||||
assert.equal(merchant.country, 'GB');
|
||||
assert.equal(merchant.industry, 'OTHER');
|
||||
assert.equal(merchant.website, 'https://example.test/');
|
||||
assert.equal(merchant.estimatedMonthlyVolumeUsd.toFixed(2), '1234.50');
|
||||
assert.equal(merchant.checklist.length, 4);
|
||||
assert.ok(
|
||||
merchant.checklist.every((item) => item.state === 'MISSING' && item.changes.length === 0),
|
||||
);
|
||||
assert.equal(merchant.activities.length, 1);
|
||||
assert.equal(merchant.activities[0].actorId, null);
|
||||
assert.equal(merchant.activities[0].kind, 'AUDIT');
|
||||
assert.equal(merchant.events.length, 1);
|
||||
assert.equal(merchant.events[0].actorId, null);
|
||||
assert.equal(merchant.events[0].fromStatus, null);
|
||||
assert.equal(merchant.events[0].toStatus, 'NEW_LEAD');
|
||||
const head = await cookie('head'),
|
||||
compliance = await cookie('compliance'),
|
||||
alex = await cookie('alex'),
|
||||
sam = await cookie('sam');
|
||||
for (const staff of [head, compliance]) {
|
||||
const detail = await request(`/merchants/${merchant.id}`, undefined, { cookie: staff }, 'GET');
|
||||
assert.equal(detail.status, 200);
|
||||
assert.equal(merchantDetailSchema.safeParse(detail.body).success, true);
|
||||
assert.equal(detail.body.activities[0].actor, null);
|
||||
assert.ok(!JSON.stringify(detail.body).includes('publicSubmission'));
|
||||
const dashboard = await request('/dashboard', undefined, { cookie: staff }, 'GET');
|
||||
assert.equal(dashboardSchema.safeParse(dashboard.body).success, true);
|
||||
}
|
||||
for (const staff of [alex, sam]) {
|
||||
assert.equal(
|
||||
(await request(`/merchants/${merchant.id}`, undefined, { cookie: staff }, 'GET')).status,
|
||||
404,
|
||||
);
|
||||
const list = await request(
|
||||
`/merchants?search=${encodeURIComponent(data.contactEmail)}`,
|
||||
undefined,
|
||||
{ cookie: staff },
|
||||
'GET',
|
||||
);
|
||||
assert.equal(list.body.total, 0);
|
||||
}
|
||||
assert.equal(
|
||||
(
|
||||
await request(
|
||||
`/merchants/${merchant.id}/transitions`,
|
||||
{ version: 0, toStatus: 'CONTACTED' },
|
||||
{ cookie: head },
|
||||
)
|
||||
).status,
|
||||
409,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await request(
|
||||
`/merchants/${merchant.id}/assignment`,
|
||||
{ version: 0, ownerId: 'user-manager1' },
|
||||
{ cookie: head },
|
||||
'PATCH',
|
||||
)
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await request(
|
||||
`/merchants/${merchant.id}/activities`,
|
||||
{ version: 1, kind: 'EMAIL', text: 'Responded to the public enquiry' },
|
||||
{ cookie: alex },
|
||||
)
|
||||
).status,
|
||||
201,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await request(
|
||||
`/merchants/${merchant.id}/transitions`,
|
||||
{ version: 2, toStatus: 'CONTACTED' },
|
||||
{ cookie: alex },
|
||||
)
|
||||
).status,
|
||||
201,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await request(
|
||||
`/merchants/${merchant.id}/activities/${merchant.activities[0].id}`,
|
||||
{ version: 3, kind: 'NOTE', text: 'attempt to edit audit' },
|
||||
{ cookie: head },
|
||||
'PATCH',
|
||||
)
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
});
|
||||
|
||||
test('sequential, concurrent and post-restart retries create exactly one lead', async () => {
|
||||
const id = key(),
|
||||
data = input();
|
||||
const other = await createApp();
|
||||
await other.listen(0, '127.0.0.1');
|
||||
try {
|
||||
const results = await Promise.all([
|
||||
submit(data, id),
|
||||
submit(data, id),
|
||||
submit(data, id, {}, `${await other.getUrl()}/api`),
|
||||
]);
|
||||
assert.ok(results.every((result) => result.status === 202));
|
||||
assert.equal((await submit({ ...data, estimatedMonthlyVolumeUsd: '1234.50' }, id)).status, 202);
|
||||
} finally {
|
||||
await other.close();
|
||||
}
|
||||
await app.close();
|
||||
await start();
|
||||
assert.equal((await submit(data, id)).status, 202);
|
||||
assert.equal((await submit({ ...data, name: 'Changed payload' }, id)).status, 409);
|
||||
const matches = await db.merchant.findMany({
|
||||
where: { publicSubmissionKey: id },
|
||||
include: { activities: true, events: true },
|
||||
});
|
||||
assert.equal(matches.length, 1);
|
||||
assert.equal(matches[0].activities.length, 1);
|
||||
assert.equal(matches[0].events.length, 1);
|
||||
});
|
||||
|
||||
test('honeypots always accept valid envelopes without creating any related records', async () => {
|
||||
const before = [
|
||||
await db.merchant.count(),
|
||||
await db.activity.count(),
|
||||
await db.statusEvent.count(),
|
||||
await db.kybChecklistItem.count(),
|
||||
];
|
||||
for (let i = 0; i < 12; i++) {
|
||||
const result = await submit(
|
||||
i % 2 ? { ...input(), companyFax: 'spam' } : { companyFax: ' ', contactEmail: 'invalid' },
|
||||
key(),
|
||||
);
|
||||
assert.equal(result.status, 202);
|
||||
assert.deepEqual(result.body, { ok: true });
|
||||
}
|
||||
assert.deepEqual(
|
||||
[
|
||||
await db.merchant.count(),
|
||||
await db.activity.count(),
|
||||
await db.statusEvent.count(),
|
||||
await db.kybChecklistItem.count(),
|
||||
],
|
||||
before,
|
||||
);
|
||||
});
|
||||
|
||||
test('origin, key and body checks reject invalid submissions without persisting', async () => {
|
||||
const id = key();
|
||||
for (const headers of [
|
||||
{ origin: 'https://untrusted.example' },
|
||||
{ origin: '' },
|
||||
{ 'sec-fetch-site': 'cross-site' },
|
||||
])
|
||||
assert.equal((await submit(input(), id, headers)).status, 403);
|
||||
assert.equal((await submit(input(), 'invalid')).status, 400);
|
||||
assert.equal((await request('/public/leads', input())).status, 400);
|
||||
for (const data of [
|
||||
{ ...input(), country: 'ZZ' },
|
||||
{ ...input(), ownerId: 'user-head' },
|
||||
{ ...input(), estimatedMonthlyVolumeUsd: '-1' },
|
||||
{ ...input(), companyFax: 42 },
|
||||
])
|
||||
assert.equal((await submit(data, id)).status, 400);
|
||||
assert.equal(await db.merchant.count({ where: { publicSubmissionKey: id } }), 0);
|
||||
});
|
||||
|
||||
test('email quotas allow successful replays and IP quotas include invalid attempts', async () => {
|
||||
const data = input(),
|
||||
first = key();
|
||||
assert.equal((await submit(data, first)).status, 202);
|
||||
for (let i = 0; i < 2; i++) assert.equal((await submit(data, key())).status, 202);
|
||||
assert.equal((await submit(data, first)).status, 202);
|
||||
const result = await submit(data, key());
|
||||
assert.equal(result.status, 429);
|
||||
assert.ok(Number(result.headers.get('retry-after')) > 0);
|
||||
await app.close();
|
||||
await start();
|
||||
for (let i = 0; i < 10; i++) assert.equal((await submit({}, key())).status, 400);
|
||||
const limited = await submit(input(), key(), { 'x-forwarded-for': '1.2.3.4' });
|
||||
assert.equal(limited.status, 429);
|
||||
assert.ok(Number(limited.headers.get('retry-after')) > 0);
|
||||
});
|
||||
|
||||
test('a failed creation activity rolls back the lead and its children; retry remains safe', async () => {
|
||||
const id = key(),
|
||||
data = { ...input(), name: 'Force rollback integration' };
|
||||
await db.$executeRaw`CREATE FUNCTION fail_public_lead_activity() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF EXISTS (SELECT 1 FROM "Merchant" WHERE id = NEW."merchantId" AND name = 'Force rollback integration') THEN RAISE EXCEPTION 'Injected test failure'; END IF; RETURN NEW; END $$`;
|
||||
await db.$executeRaw`CREATE TRIGGER fail_public_lead_activity BEFORE INSERT ON "Activity" FOR EACH ROW EXECUTE FUNCTION fail_public_lead_activity()`;
|
||||
try {
|
||||
assert.equal((await submit(data, id)).status, 500);
|
||||
assert.equal(await db.merchant.count({ where: { publicSubmissionKey: id } }), 0);
|
||||
} finally {
|
||||
await db.$executeRaw`DROP TRIGGER fail_public_lead_activity ON "Activity"`;
|
||||
await db.$executeRaw`DROP FUNCTION fail_public_lead_activity()`;
|
||||
}
|
||||
assert.equal((await submit(data, id)).status, 202);
|
||||
assert.equal(await db.merchant.count({ where: { publicSubmissionKey: id } }), 1);
|
||||
});
|
||||
@@ -0,0 +1,473 @@
|
||||
import { before, after, afterEach, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { createDatabase } from '@merchantflow/database';
|
||||
import {
|
||||
merchantDetailSchema,
|
||||
pipelineBoardSchema,
|
||||
merchantFiltersSchema,
|
||||
statuses,
|
||||
} from '@merchantflow/contracts';
|
||||
import { createApp } from '../dist/app.js';
|
||||
|
||||
if (!process.env.DATABASE_URL?.endsWith('/merchantflow_test'))
|
||||
throw new Error('Only the isolated test database is allowed');
|
||||
const db = createDatabase(process.env.DATABASE_URL);
|
||||
const created = new Set();
|
||||
const cookies = {};
|
||||
let app, base;
|
||||
async function request(
|
||||
path,
|
||||
actor = 'head',
|
||||
body,
|
||||
method = body === undefined ? 'GET' : 'POST',
|
||||
headers = {},
|
||||
) {
|
||||
const response = await fetch(`${base}${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
origin: process.env.APP_ORIGIN,
|
||||
...(cookies[actor] ? { cookie: cookies[actor] } : {}),
|
||||
...(body === undefined ? {} : { 'content-type': 'application/json' }),
|
||||
...headers,
|
||||
},
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
return { status: response.status, body: await response.json(), headers: response.headers };
|
||||
}
|
||||
before(async () => {
|
||||
app = await createApp();
|
||||
await app.listen(0, '127.0.0.1');
|
||||
base = `${await app.getUrl()}/api`;
|
||||
for (const account of ['head', 'alex', 'sam', 'compliance']) {
|
||||
const result = await request('/auth/login', null, {
|
||||
email: `${account}@merchantflow.test`,
|
||||
password: 'MerchantFlow123!',
|
||||
});
|
||||
assert.equal(result.status, 201);
|
||||
cookies[account] = result.headers.get('set-cookie').split(';')[0];
|
||||
}
|
||||
});
|
||||
afterEach(async () => {
|
||||
await db.merchant.deleteMany({ where: { id: { in: [...created] } } });
|
||||
created.clear();
|
||||
});
|
||||
after(async () => {
|
||||
await app?.close();
|
||||
await db.$disconnect();
|
||||
});
|
||||
const input = (extra = {}) => ({
|
||||
name: `Sales ${randomUUID()}`,
|
||||
contactName: 'Unique Contact',
|
||||
contactEmail: '[email protected]',
|
||||
...extra,
|
||||
});
|
||||
async function create(actor = 'head', extra = {}) {
|
||||
const result = await request('/merchants', actor, input(extra));
|
||||
assert.equal(result.status, 201, JSON.stringify(result.body));
|
||||
created.add(result.body.id);
|
||||
return result.body.id;
|
||||
}
|
||||
async function detail(id, actor = 'head') {
|
||||
const result = await request(`/merchants/${id}`, actor);
|
||||
assert.equal(result.status, 200);
|
||||
return merchantDetailSchema.parse(result.body);
|
||||
}
|
||||
async function change(id, path, body, actor = 'head', method = 'PATCH') {
|
||||
const m = await detail(id);
|
||||
return request(`/merchants/${id}${path}`, actor, { version: m.version, ...body }, method);
|
||||
}
|
||||
const move = (id, toStatus, actor = 'head', reason) =>
|
||||
change(
|
||||
id,
|
||||
'/transitions',
|
||||
{ toStatus, ...(reason === undefined ? {} : { reason }) },
|
||||
actor,
|
||||
'POST',
|
||||
);
|
||||
const log = (id, kind = 'CALL', text = 'Contacted the primary contact') =>
|
||||
change(id, '/activities', { kind, text }, 'head', 'POST');
|
||||
|
||||
test('staff creation is atomic, minimally required, role-bound and strict', async () => {
|
||||
const unassigned = await create();
|
||||
let m = await detail(unassigned);
|
||||
assert.equal(m.status, 'NEW_LEAD');
|
||||
assert.equal(m.owner, null);
|
||||
assert.equal(m.website, null);
|
||||
assert.equal(m.country, null);
|
||||
assert.equal(m.industry, null);
|
||||
assert.equal(m.checklist.length, 4);
|
||||
assert.ok(m.checklist.every((item) => item.state === 'MISSING'));
|
||||
assert.equal(m.events.length, 1);
|
||||
assert.equal(m.activities.length, 1);
|
||||
assert.equal(m.activities[0].actor.name, 'Elena Carter');
|
||||
assert.equal(m.history.length, 1); // Initial stage and creation audit represent one event.
|
||||
assert.equal(m.version, 0);
|
||||
assert.ok(!JSON.stringify(m).includes('publicSubmission'));
|
||||
const assigned = await create('head', {
|
||||
ownerId: 'user-manager2',
|
||||
website: 'example.test',
|
||||
country: 'gb',
|
||||
industry: 'SOFTWARE',
|
||||
estimatedMonthlyVolumeUsd: '0',
|
||||
});
|
||||
m = await detail(assigned);
|
||||
assert.equal(m.owner.id, 'user-manager2');
|
||||
assert.equal(m.country, 'GB');
|
||||
assert.equal(m.estimatedMonthlyVolumeUsd, '0');
|
||||
const self = await create('alex');
|
||||
assert.equal((await detail(self)).owner.id, 'user-manager1');
|
||||
for (const ownerId of ['user-manager2', null])
|
||||
assert.equal((await request('/merchants', 'alex', input({ ownerId }))).status, 403);
|
||||
assert.equal((await request('/merchants', 'compliance', input())).status, 403);
|
||||
assert.equal((await request('/merchants', null, input())).status, 401);
|
||||
assert.equal(
|
||||
(await request('/merchants', 'head', input(), 'POST', { origin: 'https://untrusted.test' }))
|
||||
.status,
|
||||
403,
|
||||
);
|
||||
assert.equal((await request('/merchants', 'head', input({ ownerId: 'user-head' }))).status, 400);
|
||||
for (const field of ['status', 'actorId', 'reviewerId', 'publicSubmissionKey', 'version'])
|
||||
assert.equal(
|
||||
(await request('/merchants', 'head', input({ [field]: 'injected' }))).status,
|
||||
400,
|
||||
field,
|
||||
);
|
||||
for (const field of ['name', 'contactName', 'contactEmail'])
|
||||
assert.equal((await request('/merchants', 'head', input({ [field]: '' }))).status, 400, field);
|
||||
assert.equal((await request(`/merchants/${self}`, 'sam')).status, 404);
|
||||
assert.equal((await request(`/merchants/${assigned}`, 'alex')).status, 404);
|
||||
});
|
||||
|
||||
test('search, combined filters, pagination and metadata apply ownership scope before counts', async () => {
|
||||
const prefix = `Directory-${randomUUID()}`;
|
||||
const ids = [];
|
||||
for (let index = 0; index < 10; index++)
|
||||
ids.push(
|
||||
await create('alex', {
|
||||
name: `${prefix} ${index}`,
|
||||
contactName: `${prefix} Contact`,
|
||||
contactEmail: `${prefix.toLowerCase()}@example.test`,
|
||||
country: 'GB',
|
||||
industry: 'SOFTWARE',
|
||||
website: 'search.example.test',
|
||||
}),
|
||||
);
|
||||
const hidden = await create('sam', {
|
||||
name: `${prefix} Hidden`,
|
||||
country: 'JP',
|
||||
industry: 'TRAVEL',
|
||||
});
|
||||
const unassigned = await create('head', { name: `${prefix} Unassigned` });
|
||||
await change(ids[0], '', { legalName: `${prefix} Legal` });
|
||||
for (const search of [
|
||||
`${prefix} 1`,
|
||||
`${prefix} Contact`,
|
||||
`${prefix.toLowerCase()}@example.test`,
|
||||
`${prefix} Legal`,
|
||||
]) {
|
||||
const result = await request(`/merchants?search=${encodeURIComponent(search)}`, 'alex');
|
||||
assert.equal(result.status, 200);
|
||||
assert.ok(result.body.total > 0);
|
||||
assert.ok(result.body.items.every((m) => m.owner.id === 'user-manager1'));
|
||||
}
|
||||
const query = `search=${prefix}&country=GB&industry=SOFTWARE&status=NEW_LEAD`;
|
||||
const page1 = (await request(`/merchants?${query}`, 'alex')).body;
|
||||
const page2 = (await request(`/merchants?${query}&page=2`, 'alex')).body;
|
||||
assert.equal(page1.total, 10);
|
||||
assert.equal(page1.items.length, 8);
|
||||
assert.equal(page2.items.length, 2);
|
||||
assert.equal(new Set([...page1.items, ...page2.items].map((m) => m.id)).size, 10);
|
||||
assert.equal((await request(`/merchants?${query}&page=10000`, 'alex')).body.page, 2);
|
||||
assert.equal((await request(`/merchants?${query}&ownerId=user-manager2`, 'alex')).status, 403);
|
||||
assert.equal(
|
||||
(await request(`/merchants?search=${prefix}&ownerId=user-manager2`, 'head')).body.items[0].id,
|
||||
hidden,
|
||||
);
|
||||
assert.equal(
|
||||
(await request(`/merchants?search=${prefix}&ownerId=unassigned`, 'compliance')).body.items[0]
|
||||
.id,
|
||||
unassigned,
|
||||
);
|
||||
assert.equal((await request(`/merchants?search=${prefix}&country=JP`, 'alex')).body.total, 0);
|
||||
for (const invalid of ['country=ZZ', 'industry=INVALID', 'status=Live', 'page=1.5', 'page=-1'])
|
||||
assert.equal((await request(`/merchants?${invalid}`)).status, 400);
|
||||
const ownFilters = merchantFiltersSchema.parse(
|
||||
(await request('/merchants/filters', 'alex')).body,
|
||||
);
|
||||
assert.equal(ownFilters.canFilterOwner, false);
|
||||
assert.deepEqual(ownFilters.owners, []);
|
||||
assert.equal(ownFilters.canCreate, true);
|
||||
const expectedCountries = [
|
||||
...new Set(
|
||||
(
|
||||
await db.merchant.findMany({ where: { ownerId: 'user-manager1', country: { not: null } } })
|
||||
).map((m) => m.country),
|
||||
),
|
||||
].sort();
|
||||
assert.deepEqual(ownFilters.countries, expectedCountries);
|
||||
const complianceFilters = merchantFiltersSchema.parse(
|
||||
(await request('/merchants/filters', 'compliance')).body,
|
||||
);
|
||||
assert.equal(complianceFilters.canFilterOwner, true);
|
||||
assert.equal(complianceFilters.canCreate, false);
|
||||
assert.equal((await request('/users/assignable-managers', 'compliance')).status, 403);
|
||||
});
|
||||
|
||||
test('commercial gates expose the same blockers as mutations and accept a zero volume', async () => {
|
||||
const id = await create();
|
||||
const action = async () =>
|
||||
(await detail(id)).capabilities.actions.find((a) => a.kind === 'ADVANCE');
|
||||
assert.deepEqual(
|
||||
(await action()).blockingReasons.map((b) => b.code),
|
||||
['ASSIGNMENT_REQUIRED', 'CONTACT_REQUIRED'],
|
||||
);
|
||||
let result = await move(id, 'CONTACTED');
|
||||
assert.equal(result.status, 409);
|
||||
assert.deepEqual(result.body.blockingReasons, (await action()).blockingReasons);
|
||||
assert.equal((await detail(id)).version, 0);
|
||||
await change(id, '/assignment', { ownerId: 'user-manager1' });
|
||||
await log(id, 'MEETING');
|
||||
assert.equal((await move(id, 'CONTACTED', 'alex')).status, 409);
|
||||
await log(id, 'EMAIL');
|
||||
assert.equal((await action()).enabled, true);
|
||||
assert.equal((await move(id, 'CONTACTED', 'alex')).status, 201);
|
||||
assert.equal((await move(id, 'QUALIFIED', 'alex')).status, 409);
|
||||
assert.deepEqual(
|
||||
(await action()).blockingReasons[0].fields.sort(),
|
||||
['website', 'country', 'industry', 'estimatedMonthlyVolumeUsd'].sort(),
|
||||
);
|
||||
await change(
|
||||
id,
|
||||
'',
|
||||
{ website: 'sales.test', country: 'GB', industry: 'OTHER', estimatedMonthlyVolumeUsd: '0' },
|
||||
'alex',
|
||||
);
|
||||
assert.equal((await move(id, 'QUALIFIED', 'alex')).status, 201);
|
||||
assert.equal((await move(id, 'KYB', 'alex')).status, 201);
|
||||
result = await move(id, 'COMPLIANCE_REVIEW', 'alex');
|
||||
assert.equal(result.status, 409);
|
||||
assert.equal(result.body.blockingReasons[0].code, 'DOCUMENTS_REQUIRED');
|
||||
const m = await detail(id);
|
||||
assert.equal(m.events.filter((event) => event.toStatus === 'CONTACTED').length, 1);
|
||||
assert.equal(
|
||||
m.history.filter((entry) => entry.kind === 'STAGE' && entry.toStatus === 'CONTACTED').length,
|
||||
1,
|
||||
);
|
||||
for (const payload of [
|
||||
{ status: 'LIVE' },
|
||||
{ ownerId: 'user-manager2' },
|
||||
{ actorId: 'user-head' },
|
||||
])
|
||||
assert.equal((await change(id, '', payload, 'alex')).status, 400);
|
||||
assert.equal((await move(id, 'LIVE', 'alex')).status, 409);
|
||||
assert.equal((await move(id, 'TESTING', 'compliance')).status, 403);
|
||||
const pipe = pipelineBoardSchema.parse((await request('/pipeline', 'alex')).body);
|
||||
assert.deepEqual(
|
||||
pipe.find((row) => row.id === id).capabilities,
|
||||
(await detail(id, 'alex')).capabilities,
|
||||
);
|
||||
});
|
||||
|
||||
test('every rejection role and stage rule is enforced, with terminal outcomes and preserved compliance records', async () => {
|
||||
for (const stage of statuses) {
|
||||
for (const actor of ['head', 'alex', 'compliance']) {
|
||||
const id = await create('alex');
|
||||
await db.merchant.update({ where: { id }, data: { status: stage } });
|
||||
const allowed =
|
||||
(['NEW_LEAD', 'CONTACTED', 'QUALIFIED'].includes(stage) && actor !== 'compliance') ||
|
||||
(['KYB', 'INTEGRATION', 'TESTING'].includes(stage) && actor === 'head');
|
||||
assert.equal(
|
||||
(await move(id, 'REJECTED', actor, ' Business no longer proceeding ')).status,
|
||||
allowed
|
||||
? 201
|
||||
: actor === 'compliance' ||
|
||||
stage === 'COMPLIANCE_REVIEW' ||
|
||||
!['LIVE', 'REJECTED'].includes(stage)
|
||||
? 403
|
||||
: 409,
|
||||
`${stage}/${actor}`,
|
||||
);
|
||||
const m = await detail(id);
|
||||
assert.equal(m.status, allowed ? 'REJECTED' : stage);
|
||||
if (allowed) {
|
||||
assert.equal(m.events[0].note, 'Business no longer proceeding');
|
||||
assert.equal(m.capabilities.actions.length, 0);
|
||||
assert.equal((await move(id, 'NEW_LEAD', actor)).status, 409);
|
||||
}
|
||||
}
|
||||
}
|
||||
const id = await create('alex');
|
||||
for (const reason of [undefined, '', ' '])
|
||||
assert.equal((await move(id, 'REJECTED', 'alex', reason)).status, 400);
|
||||
assert.equal((await detail(id)).version, 0);
|
||||
// Head closure of an approved merchant must retain the original immutable decision.
|
||||
const approved = await db.merchant.findFirst({
|
||||
where: { status: 'INTEGRATION' },
|
||||
include: { reviews: true },
|
||||
});
|
||||
const clone = await create('alex');
|
||||
await db.merchant.update({ where: { id: clone }, data: { status: 'INTEGRATION' } });
|
||||
const review = await db.complianceReview.create({
|
||||
data: {
|
||||
merchantId: clone,
|
||||
cycle: 1,
|
||||
decision: 'APPROVED',
|
||||
submittedById: 'user-head',
|
||||
reviewerId: 'user-compliance',
|
||||
decidedAt: new Date(),
|
||||
snapshot: approved.reviews[0].snapshot,
|
||||
},
|
||||
});
|
||||
assert.equal((await move(clone, 'REJECTED', 'head', 'Commercial terms declined')).status, 201);
|
||||
assert.deepEqual(await db.complianceReview.findUnique({ where: { id: review.id } }), review);
|
||||
});
|
||||
|
||||
test('qualification and assignment gates cannot be bypassed; approved integration evidence is still required', async () => {
|
||||
for (const stage of ['QUALIFIED', 'INTEGRATION', 'TESTING']) {
|
||||
const id = await create('head', stage === 'QUALIFIED' ? {} : { ownerId: 'user-manager1' });
|
||||
await db.merchant.update({ where: { id }, data: { status: stage } });
|
||||
const target = stage === 'QUALIFIED' ? 'KYB' : stage === 'INTEGRATION' ? 'TESTING' : 'LIVE';
|
||||
const result = await move(id, target);
|
||||
assert.equal(result.status, 409);
|
||||
assert.equal(
|
||||
result.body.blockingReasons[0].code,
|
||||
stage === 'QUALIFIED' ? 'ASSIGNMENT_REQUIRED' : 'APPROVAL_REQUIRED',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('ownership handoff retains attribution and persists typed chronological history', async () => {
|
||||
const id = await create('alex');
|
||||
await log(id, 'NOTE', 'Durable note');
|
||||
await log(id, 'CALL', 'Durable call');
|
||||
const open = await db.task.create({
|
||||
data: {
|
||||
merchantId: id,
|
||||
title: 'Transfer me',
|
||||
assigneeId: 'user-manager1',
|
||||
creatorId: 'user-head',
|
||||
dueAt: new Date(),
|
||||
},
|
||||
});
|
||||
const done = await db.task.create({
|
||||
data: {
|
||||
merchantId: id,
|
||||
title: 'Keep attribution',
|
||||
status: 'DONE',
|
||||
assigneeId: 'user-manager1',
|
||||
creatorId: 'user-manager1',
|
||||
completedById: 'user-head',
|
||||
completedAt: new Date(),
|
||||
dueAt: new Date(),
|
||||
},
|
||||
});
|
||||
const comp = await db.task.create({
|
||||
data: {
|
||||
merchantId: id,
|
||||
title: 'Personal review',
|
||||
kind: 'COMPLIANCE',
|
||||
assigneeId: 'user-compliance',
|
||||
creatorId: 'user-compliance',
|
||||
dueAt: new Date(),
|
||||
},
|
||||
});
|
||||
const original = await detail(id);
|
||||
assert.equal((await change(id, '/assignment', { ownerId: 'user-manager2' })).status, 200);
|
||||
assert.equal((await db.task.findUnique({ where: { id: open.id } })).assigneeId, 'user-manager2');
|
||||
assert.deepEqual(await db.task.findUnique({ where: { id: done.id } }), done);
|
||||
assert.deepEqual(await db.task.findUnique({ where: { id: comp.id } }), comp);
|
||||
assert.equal((await request(`/merchants/${id}`, 'alex')).status, 404);
|
||||
assert.equal(
|
||||
(
|
||||
await request(`/merchants/${id}/activities`, 'alex', {
|
||||
version: original.version,
|
||||
kind: 'NOTE',
|
||||
text: 'Former owner',
|
||||
})
|
||||
).status,
|
||||
404,
|
||||
);
|
||||
const m = await detail(id, 'sam');
|
||||
const ownership = m.history.find((entry) => entry.kind === 'OWNERSHIP');
|
||||
assert.equal(ownership.previousOwner.id, 'user-manager1');
|
||||
assert.equal(ownership.owner.id, 'user-manager2');
|
||||
assert.equal(ownership.actor.name, 'Elena Carter');
|
||||
assert.deepEqual(
|
||||
m.history.map((entry) => entry.occurredAt),
|
||||
[...m.history.map((entry) => entry.occurredAt)].sort().reverse(),
|
||||
);
|
||||
for (const activity of original.activities)
|
||||
assert.deepEqual(m.activities.find((entry) => entry.id === activity.id).actor, activity.actor);
|
||||
assert.ok(!JSON.stringify(m).includes('previousOwnerId'));
|
||||
assert.ok(
|
||||
m.history.some((entry) => entry.kind === 'INTERACTION' && entry.text === 'Durable call'),
|
||||
);
|
||||
assert.deepEqual((await detail(id, 'sam')).history, m.history);
|
||||
});
|
||||
|
||||
test('conflicting transitions, ownership and activity writes commit at most once', async () => {
|
||||
const id = await create('alex');
|
||||
await log(id);
|
||||
let m = await detail(id);
|
||||
const results = await Promise.all([
|
||||
request(`/merchants/${id}/transitions`, 'alex', { version: m.version, toStatus: 'CONTACTED' }),
|
||||
request(
|
||||
`/merchants/${id}/assignment`,
|
||||
'head',
|
||||
{ version: m.version, ownerId: 'user-manager2' },
|
||||
'PATCH',
|
||||
),
|
||||
request(`/merchants/${id}/activities`, 'alex', {
|
||||
version: m.version,
|
||||
kind: 'EMAIL',
|
||||
text: 'Concurrent outreach',
|
||||
}),
|
||||
]);
|
||||
assert.equal(results.filter((r) => r.status < 300).length, 1);
|
||||
assert.ok(results.filter((r) => r.status >= 300).every((r) => [404, 409].includes(r.status)));
|
||||
assert.equal((await detail(id)).version, m.version + 1);
|
||||
assert.equal(
|
||||
(
|
||||
await request(`/merchants/${id}/transitions`, 'head', {
|
||||
version: m.version,
|
||||
toStatus: 'REJECTED',
|
||||
reason: 'Stale closure',
|
||||
})
|
||||
).status,
|
||||
409,
|
||||
);
|
||||
m = await detail(id);
|
||||
const rejection = await Promise.all(
|
||||
[1, 2].map(() =>
|
||||
request(`/merchants/${id}/transitions`, 'head', {
|
||||
version: m.version,
|
||||
toStatus: 'REJECTED',
|
||||
reason: 'Closure',
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.deepEqual(rejection.map((r) => r.status).sort(), [201, 409]);
|
||||
assert.equal(
|
||||
(await detail(id)).events.filter((event) => event.toStatus === 'REJECTED').length,
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
test('failed audit writes roll back merchant creation and stage changes completely', async () => {
|
||||
const id = await create('alex');
|
||||
await log(id);
|
||||
const original = await detail(id);
|
||||
await db.$executeRaw`CREATE FUNCTION fail_sales_audit() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.text = 'NEW_LEAD → CONTACTED' OR NEW.text = 'Merchant created' THEN RAISE EXCEPTION 'Injected sales failure'; END IF; RETURN NEW; END $$`;
|
||||
await db.$executeRaw`CREATE TRIGGER sales_audit_failure BEFORE INSERT ON "Activity" FOR EACH ROW EXECUTE FUNCTION fail_sales_audit()`;
|
||||
try {
|
||||
assert.equal((await move(id, 'CONTACTED', 'alex')).status, 500);
|
||||
assert.deepEqual(await detail(id), original);
|
||||
const name = `Rollback-${randomUUID()}`;
|
||||
assert.equal((await request('/merchants', 'head', input({ name }))).status, 500);
|
||||
assert.equal(await db.merchant.count({ where: { name } }), 0);
|
||||
} finally {
|
||||
await db.$executeRaw`DROP TRIGGER sales_audit_failure ON "Activity"`;
|
||||
await db.$executeRaw`DROP FUNCTION fail_sales_audit()`;
|
||||
}
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { merchantScope } from '../dist/access.js';
|
||||
import { hashPassword, verifyPassword } from '@merchantflow/database';
|
||||
import { LeadRateLimiter } from '../dist/public-leads.js';
|
||||
test('passwords use distinct salts and reject incorrect values', () => {
|
||||
const hash = hashPassword('example-password');
|
||||
assert.notEqual(hash, hashPassword('example-password'));
|
||||
@@ -9,6 +10,22 @@ test('passwords use distinct salts and reject incorrect values', () => {
|
||||
assert.equal(verifyPassword('wrong', hash), false);
|
||||
assert.equal(verifyPassword('wrong', 'broken'), false);
|
||||
});
|
||||
test('public lead limits expire, bound storage and reserve each submission once', () => {
|
||||
let now = 0;
|
||||
const limiter = new LeadRateLimiter(() => now, 3);
|
||||
for (let i = 0; i < 10; i++) assert.equal(limiter.attemptIp('127.0.0.1'), 0);
|
||||
assert.equal(limiter.attemptIp('127.0.0.1'), 900);
|
||||
for (let i = 0; i < 3; i++) assert.equal(limiter.reserveEmail('[email protected]', String(i)), 0);
|
||||
assert.equal(limiter.reserveEmail('[email protected]', '0'), 0);
|
||||
assert.equal(limiter.reserveEmail('[email protected]', 'new'), 900);
|
||||
limiter.releaseEmail('[email protected]', '0');
|
||||
assert.equal(limiter.reserveEmail('[email protected]', 'new'), 0);
|
||||
assert.equal(limiter.attemptIp('another'), 0);
|
||||
assert.equal(limiter.attemptIp('map-full'), 900);
|
||||
now = 900001;
|
||||
assert.equal(limiter.attemptIp('map-full'), 0);
|
||||
assert.equal(limiter.reserveEmail('[email protected]', 'another'), 0);
|
||||
});
|
||||
test('every role receives its exact merchant scope', () => {
|
||||
assert.deepEqual(merchantScope({ role: 'HEAD_OF_SALES' }), {});
|
||||
assert.deepEqual(merchantScope({ role: 'ACCOUNT_MANAGER', id: 'manager-1' }), {
|
||||
|
||||
Reference in New Issue
Block a user