Built merchant management, activity history, and the pipeline

This commit is contained in:
Oleksandr Prokhorenko
2026-09-24 20:50:15 +03:00
parent 5de240fda3
commit 382f6e8841
43 changed files with 4679 additions and 812 deletions
+10
View File
@@ -0,0 +1,10 @@
// ISO 3166-1 alpha-2 codes. Display names come from the selected locale's Intl data.
export const countryCodes = (
'AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ ' +
'CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR ' +
'GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP ' +
'KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ ' +
'NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW ' +
'SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ ' +
'UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW'
).split(' ');
+110
View File
@@ -5,6 +5,9 @@ import {
successfulStages,
statuses,
canSeeReviewQueue,
publicLeadSchema,
publicLeadKeySchema,
countryCodes,
} from './index.js';
describe('browser-safe contracts', () => {
it('keeps rejection outside the successful sequence', () => {
@@ -29,3 +32,110 @@ describe('browser-safe contracts', () => {
expect(canSeeReviewQueue('COMPLIANCE_OFFICER')).toBe(true);
});
});
const lead = {
name: ' Example Company ',
contactName: ' Alex ',
contactEmail: ' [email protected] ',
website: 'example.com',
country: 'gb',
industry: 'OTHER',
estimatedMonthlyVolumeUsd: '25000,5',
};
describe('public lead contracts', () => {
it('normalizes a lead without floating-point amounts', () => {
expect(publicLeadSchema.parse(lead)).toEqual({
name: 'Example Company',
contactName: 'Alex',
contactEmail: '[email protected]',
website: 'https://example.com/',
country: 'GB',
industry: 'OTHER',
estimatedMonthlyVolumeUsd: '25000.50',
companyFax: '',
});
expect(countryCodes).toHaveLength(249);
expect(new Set(countryCodes).size).toBe(249);
});
it('requires every business field and rejects privilege injection', () => {
for (const field of Object.keys(lead)) {
expect(publicLeadSchema.safeParse({ ...lead, [field]: '' }).success, field).toBe(false);
expect(publicLeadSchema.safeParse({ ...lead, [field]: undefined }).success, field).toBe(
false,
);
}
for (const field of ['ownerId', 'status', 'source', 'actorId', 'publicSubmissionKey'])
expect(publicLeadSchema.safeParse({ ...lead, [field]: 'injected' }).success).toBe(false);
});
it('validates websites, countries, names and addresses with translation keys', () => {
for (const website of [
'invalid website',
'https://',
'javascript:alert(1)',
'ftp://example.com',
'https://user:[email protected]',
'x'.repeat(2050),
])
expect(publicLeadSchema.safeParse({ ...lead, website }).success, website).toBe(false);
for (const input of [
{ country: 'ZZ' },
{ industry: 'UNSUPPORTED' },
{ name: ' '.repeat(20) },
{ contactName: 'x'.repeat(201) },
{ contactEmail: 'not an email' },
]) {
const result = publicLeadSchema.safeParse({ ...lead, ...input });
expect(result.success).toBe(false);
if (!result.success)
expect(result.error.issues.every((issue) => issue.message.startsWith('validation.'))).toBe(
true,
);
}
expect(publicLeadKeySchema.safeParse({ idempotencyKey: 'arbitrary' }).success).toBe(false);
});
it('keeps exact decimal limits and supports a zero estimate', () => {
for (const value of ['0', '0.00', '999999999999.99', '1,25'])
expect(
publicLeadSchema.safeParse({ ...lead, estimatedMonthlyVolumeUsd: value }).success,
).toBe(true);
for (const value of ['-1', '1e3', '1.001', '1000000000000', '25,000', 'NaN', 'Infinity', '01'])
expect(
publicLeadSchema.safeParse({ ...lead, estimatedMonthlyVolumeUsd: value }).success,
value,
).toBe(false);
});
});
describe('daily sales contracts', () => {
it('allows incomplete staff leads while enforcing core contact fields and strict ownership boundaries', async () => {
const { merchantCreateSchema, merchantEditSchema } = await import('./index.js');
const basic = { name: 'Acme', contactName: 'Jo', contactEmail: '[email protected]' };
expect(merchantCreateSchema.safeParse(basic).success).toBe(true);
expect(
merchantCreateSchema.parse({ ...basic, estimatedMonthlyVolumeUsd: '0' })
.estimatedMonthlyVolumeUsd,
).toBe('0.00');
for (const field of ['name', 'contactName', 'contactEmail'])
expect(merchantCreateSchema.safeParse({ ...basic, [field]: '' }).success).toBe(false);
for (const field of ['status', 'actorId', 'publicSubmissionKey', 'version'])
expect(merchantCreateSchema.safeParse({ ...basic, [field]: 'injected' }).success).toBe(false);
expect(merchantEditSchema.safeParse({ version: 1, status: 'LIVE' }).success).toBe(false);
expect(merchantEditSchema.safeParse({ version: 1, ownerId: 'manager' }).success).toBe(false);
});
it('requires a nonblank rejection reason and validates directory filters', async () => {
const { transitionSchema } = await import('./index.js');
for (const reason of ['', ' ', undefined])
expect(transitionSchema.safeParse({ version: 1, toStatus: 'REJECTED', reason }).success).toBe(
false,
);
expect(
transitionSchema.parse({ version: 1, toStatus: 'REJECTED', reason: ' Closed ' }).reason,
).toBe('Closed');
for (const query of [{ country: 'ZZ' }, { industry: 'bad' }, { ownerId: '' }, { page: 1.5 }])
expect(merchantQuerySchema.safeParse(query).success).toBe(false);
expect(
merchantQuerySchema.parse({ country: 'GB', industry: 'OTHER', ownerId: 'unassigned' })
.ownerId,
).toBe('unassigned');
});
});
+181 -21
View File
@@ -1,4 +1,6 @@
import { z } from 'zod';
import { countryCodes } from './countries.js';
export { countryCodes } from './countries.js';
export const roles = ['HEAD_OF_SALES', 'COMPLIANCE_OFFICER', 'ACCOUNT_MANAGER'] as const;
export const successfulStages = [
@@ -27,6 +29,12 @@ export type LoginInput = z.input<typeof loginSchema>;
export const merchantQuerySchema = z.object({
search: z.string().trim().max(100).default(''),
status: statusSchema.optional(),
country: z
.string()
.refine((value) => countryCodes.includes(value))
.optional(),
industry: z.enum(['ECOMMERCE', 'SOFTWARE', 'TRAVEL', 'SERVICES', 'OTHER']).optional(),
ownerId: z.string().min(1).max(200).optional(),
page: z.coerce.number().int().min(1).max(10000).default(1),
});
export const taskFilters = ['ALL', 'OPEN', 'OVERDUE', 'UPCOMING', 'DONE'] as const;
@@ -44,10 +52,14 @@ export const errorCodes = [
'CONFLICT',
'WORKFLOW_INVALID',
'REVIEW_LOCKED',
'IDEMPOTENCY_CONFLICT',
] as const;
export const apiErrorSchema = z.object({
code: z.enum(errorCodes),
issues: z.array(z.object({ path: z.string(), code: z.string() })).optional(),
blockingReasons: z
.array(z.object({ code: z.string(), fields: z.array(z.string()).optional() }))
.optional(),
});
export const userSchema = z.object({
id: z.string(),
@@ -60,9 +72,9 @@ const date = z.iso.datetime();
export const merchantSchema = z.object({
id: z.string(),
name: z.string(),
website: z.string(),
industry: z.string(),
country: z.string(),
website: z.string().nullable(),
industry: z.string().nullable(),
country: z.string().nullable(),
contactName: z.string(),
contactEmail: z.string(),
legalName: z.string().nullable(),
@@ -93,7 +105,7 @@ export const eventSchema = z.object({
occurredAt: date,
note: z.string().nullable(),
merchant: z.object({ id: z.string(), name: z.string() }),
actor: z.object({ name: z.string() }),
actor: z.object({ name: z.string() }).nullable(),
});
export type StageEvent = z.infer<typeof eventSchema>;
export const taskSchema = z.object({
@@ -126,7 +138,7 @@ export const activitySchema = z.object({
text: z.string(),
occurredAt: date,
updatedAt: date,
actor: z.object({ id: z.string(), name: z.string() }),
actor: z.object({ id: z.string(), name: z.string() }).nullable(),
merchant: z.object({ id: z.string(), name: z.string() }),
});
export const reviewSchema = z.object({
@@ -139,6 +151,28 @@ export const reviewSchema = z.object({
submittedBy: z.object({ name: z.string() }),
reviewer: z.object({ name: z.string() }).nullable(),
});
export const blockingReasonSchema = z.object({
code: z.enum([
'ASSIGNMENT_REQUIRED',
'CONTACT_REQUIRED',
'QUALIFICATION_INCOMPLETE',
'DOCUMENTS_REQUIRED',
'REVIEW_PENDING',
'APPROVAL_REQUIRED',
'COMPLIANCE_ONLY',
'SALES_ONLY',
]),
fields: z.array(z.string()).optional(),
});
export const workflowActionSchema = z.object({
kind: z.enum(['ADVANCE', 'REJECT', 'REVIEW']),
toStatus: statusSchema.nullable(),
enabled: z.boolean(),
reasonRequired: z.boolean(),
blockingReasons: z.array(blockingReasonSchema),
});
export type WorkflowAction = z.infer<typeof workflowActionSchema>;
export type BlockingReason = z.infer<typeof blockingReasonSchema>;
export const capabilitiesSchema = z.object({
editCommercial: z.boolean(),
editIdentity: z.boolean(),
@@ -148,7 +182,42 @@ export const capabilitiesSchema = z.object({
activityKinds: z.array(z.enum(activityKinds)),
manageTaskKind: z.enum(['COMMERCIAL', 'COMPLIANCE']),
nextStage: statusSchema.nullable(),
actions: z.array(workflowActionSchema),
});
export type Capabilities = z.infer<typeof capabilitiesSchema>;
const historyBase = z.object({
id: z.string(),
occurredAt: date,
actor: z.object({ name: z.string() }).nullable(),
});
export const historyEntrySchema = z.discriminatedUnion('kind', [
historyBase.extend({
kind: z.literal('INTERACTION'),
activityId: z.string().nullable(),
activityKind: z.enum(activityKinds),
text: z.string(),
updatedAt: date,
}),
historyBase.extend({
kind: z.literal('STAGE'),
fromStatus: statusSchema.nullable(),
toStatus: statusSchema,
reason: z.string().nullable(),
}),
historyBase.extend({
kind: z.literal('OWNERSHIP'),
previousOwner: z.object({ id: z.string(), name: z.string() }).nullable(),
owner: z.object({ id: z.string(), name: z.string() }).nullable(),
}),
historyBase.extend({
kind: z.literal('REVIEW'),
decision: z.enum(['APPROVED', 'CORRECTIONS', 'REJECTED']),
cycle: z.number(),
reason: z.string().nullable(),
}),
historyBase.extend({ kind: z.literal('AUDIT'), text: z.string() }),
]);
export type HistoryEntry = z.infer<typeof historyEntrySchema>;
export const merchantDetailSchema = merchantSchema.extend({
checklist: z.array(
z.object({
@@ -181,6 +250,7 @@ export const merchantDetailSchema = merchantSchema.extend({
activities: z.array(activitySchema),
reviews: z.array(reviewSchema),
capabilities: capabilitiesSchema,
history: z.array(historyEntrySchema),
});
export type MerchantDetail = z.infer<typeof merchantDetailSchema>;
export const dashboardSchema = z.object({
@@ -194,10 +264,98 @@ export const dashboardSchema = z.object({
recentActivities: z.array(activitySchema),
});
export const pipelineSchema = z.array(merchantSchema);
export const pipelineBoardSchema = z.array(
merchantSchema.extend({ capabilities: capabilitiesSchema }),
);
export const merchantFiltersSchema = z.object({
countries: z.array(z.string()),
industries: z.array(z.string()),
owners: z.array(z.object({ id: z.string(), name: z.string() })),
canCreate: z.boolean(),
canFilterOwner: z.boolean(),
});
export const healthSchema = z.object({ status: z.literal('ok'), database: z.literal('connected') });
export const sources = ['INBOUND', 'OUTBOUND', 'REFERRAL', 'PARTNER', 'EVENT'] as const;
export const industries = ['ECOMMERCE', 'SOFTWARE', 'TRAVEL', 'SERVICES'] as const;
export const sources = [
'INBOUND',
'OUTBOUND',
'REFERRAL',
'PARTNER',
'EVENT',
'LANDING_PAGE',
] as const;
export const industries = ['ECOMMERCE', 'SOFTWARE', 'TRAVEL', 'SERVICES', 'OTHER'] as const;
const leadName = z
.string({ error: 'validation.required' })
.trim()
.min(1, 'validation.required')
.max(200, 'validation.nameMax');
const leadWebsite = z
.string({ error: 'validation.website' })
.trim()
.min(1, 'validation.required')
.max(2048, 'validation.website')
.transform((value) => (/^[a-z][a-z\d+.-]*:/i.test(value) ? value : `https://${value}`))
.pipe(z.url({ error: 'validation.website' }).max(2048, 'validation.website'))
.refine((value) => {
try {
const url = new URL(value);
return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password;
} catch {
return false;
}
}, 'validation.website')
.transform((value) => new URL(value).href);
export const publicLeadSchema = z
.object({
name: leadName,
contactName: leadName,
contactEmail: z
.string({ error: 'validation.email' })
.trim()
.pipe(z.email({ error: 'validation.email' }).max(254, 'validation.email'))
.transform((value) => value.toLowerCase()),
website: leadWebsite,
country: z
.string({ error: 'validation.country' })
.trim()
.toUpperCase()
.refine((value) => countryCodes.includes(value), 'validation.country'),
industry: z
.string({ error: 'validation.industry' })
.pipe(z.enum(industries, { error: 'validation.industry' })),
estimatedMonthlyVolumeUsd: z
.string({ error: 'validation.volume' })
.trim()
.transform((value) => value.replace(',', '.'))
.pipe(z.string().regex(/^(?:0|[1-9]\d{0,11})(?:\.\d{1,2})?$/, 'validation.volume'))
.transform((value) => {
const [whole, fraction = ''] = value.split('.');
return `${whole}.${fraction.padEnd(2, '0')}`;
}),
companyFax: z.string().max(512).default(''),
})
.strict();
export type PublicLeadInput = z.input<typeof publicLeadSchema>;
export type PublicLead = z.output<typeof publicLeadSchema>;
export const merchantCreateSchema = publicLeadSchema
.omit({ companyFax: true })
.extend({
website: leadWebsite.nullable().optional(),
country: publicLeadSchema.shape.country.nullable().optional(),
industry: publicLeadSchema.shape.industry.nullable().optional(),
estimatedMonthlyVolumeUsd: publicLeadSchema.shape.estimatedMonthlyVolumeUsd
.nullable()
.optional(),
ownerId: z.string().min(1).max(200).nullable().optional(),
source: z.enum(sources).nullable().optional(),
})
.strict();
export const merchantCreatedSchema = z.object({ id: z.string(), version: z.number().int() });
export const publicLeadAcceptedSchema = z.object({ ok: z.literal(true) });
export const publicLeadKeySchema = z.object({
idempotencyKey: z.uuid({ error: 'validation.submissionKey' }),
});
const text = z
.string()
.min(1)
@@ -211,28 +369,30 @@ export const merchantEditSchema = versionSchema
legalName: text.optional(),
registrationNumber: optionalText.optional(),
address: optionalText.optional(),
website: z
.url()
.refine((v) => /^https?:\/\//.test(v))
.optional(),
country: z
.string()
.regex(/^[A-Z]{2}$/)
.optional(),
industry: z.enum(industries).optional(),
website: leadWebsite.nullable().optional(),
country: publicLeadSchema.shape.country.nullable().optional(),
industry: z.enum(industries).nullable().optional(),
contactName: text.optional(),
contactEmail: z.email().max(254).optional(),
contactPhone: optionalText.optional(),
contactTitle: optionalText.optional(),
estimatedMonthlyVolumeUsd: z
.string()
.regex(/^(?:0|[1-9]\d{0,11})(?:\.\d{1,2})?$/)
estimatedMonthlyVolumeUsd: publicLeadSchema.shape.estimatedMonthlyVolumeUsd
.nullable()
.optional(),
source: z.enum(sources).optional(),
source: z.enum(sources).nullable().optional(),
})
.strict();
export const assignmentSchema = versionSchema.extend({ ownerId: text }).strict();
export const transitionSchema = versionSchema.extend({ toStatus: statusSchema }).strict();
export const transitionSchema = versionSchema
.extend({
toStatus: statusSchema,
reason: z.string().trim().max(2000).optional(),
})
.strict()
.superRefine((value, ctx) => {
if (value.toStatus === 'REJECTED' && !value.reason)
ctx.addIssue({ code: 'custom', path: ['reason'], message: 'validation.required' });
});
export const checklistEditSchema = versionSchema
.extend({
state: z.enum(['MISSING', 'RECEIVED']),
@@ -0,0 +1,5 @@
ALTER TABLE "Merchant" ADD COLUMN "publicSubmissionKey" TEXT,
ADD COLUMN "publicSubmissionHash" TEXT;
CREATE UNIQUE INDEX "Merchant_publicSubmissionKey_key" ON "Merchant"("publicSubmissionKey");
ALTER TABLE "Activity" ALTER COLUMN "actorId" DROP NOT NULL;
ALTER TABLE "StatusEvent" ALTER COLUMN "actorId" DROP NOT NULL;
@@ -0,0 +1,3 @@
ALTER TABLE "Merchant" ALTER COLUMN "website" DROP NOT NULL;
ALTER TABLE "Merchant" ALTER COLUMN "country" DROP NOT NULL;
ALTER TABLE "Merchant" ALTER COLUMN "industry" DROP NOT NULL;
+9 -7
View File
@@ -86,9 +86,9 @@ model Session {
model Merchant {
id String @id @default(uuid())
name String
website String
industry String
country String
website String?
industry String?
country String?
contactName String
contactEmail String
legalName String?
@@ -98,6 +98,8 @@ model Merchant {
contactTitle String?
estimatedMonthlyVolumeUsd Decimal? @db.Decimal(18, 2)
source String?
publicSubmissionKey String? @unique
publicSubmissionHash String?
status MerchantStatus @default(NEW_LEAD)
ownerId String?
createdAt DateTime @default(now())
@@ -118,13 +120,13 @@ model Merchant {
model StatusEvent {
id String @id @default(uuid())
merchantId String
actorId String
actorId String?
fromStatus MerchantStatus?
toStatus MerchantStatus
occurredAt DateTime @default(now())
note String?
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
actor User @relation(fields: [actorId], references: [id])
actor User? @relation(fields: [actorId], references: [id], onDelete: Restrict)
@@index([merchantId, occurredAt])
@@index([occurredAt])
}
@@ -173,14 +175,14 @@ model Task {
model Activity {
id String @id @default(uuid())
merchantId String
actorId String
actorId String?
kind ActivityKind
text String
occurredAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
metadata Json?
merchant Merchant @relation(fields: [merchantId], references: [id], onDelete: Cascade)
actor User @relation(fields: [actorId], references: [id])
actor User? @relation(fields: [actorId], references: [id], onDelete: Restrict)
@@index([merchantId, occurredAt])
@@index([occurredAt])
}