Implemented the database, authentication, access rules, and seed data

This commit is contained in:
Oleksandr Prokhorenko
2026-09-24 19:08:55 +03:00
parent 3aa47d825f
commit 5de240fda3
27 changed files with 3793 additions and 277 deletions
+174
View File
@@ -0,0 +1,174 @@
// Frozen foundation fixtures for upgrade compatibility tests.
if (!process.env.DATABASE_URL?.endsWith('/merchantflow_test'))
throw new Error('Legacy fixture requires isolated test database');
import { statuses, successfulStages, documentCodes } from '../../packages/contracts/dist/index.js';
import { createDatabase } from '../../packages/database/dist/index.js';
import { hashPassword } from '../../packages/database/dist/password.js';
const db = createDatabase(
process.env.DATABASE_URL ??
'postgresql://merchantflow:merchantflow_local@localhost:55440/merchantflow',
);
const users = [
{
id: 'user-head',
email: '[email protected]',
name: 'Elena Carter',
role: 'HEAD_OF_SALES',
},
{
id: 'user-compliance',
email: '[email protected]',
name: 'Pavel Sokolov',
role: 'COMPLIANCE_OFFICER',
},
{
id: 'user-manager1',
email: '[email protected]',
name: 'Alex Morgan',
role: 'ACCOUNT_MANAGER',
},
{
id: 'user-manager2',
email: '[email protected]',
name: 'Maria Chen',
role: 'ACCOUNT_MANAGER',
},
];
const names = [
'Orbit Goods',
'Northstar Studio',
'Forma Market',
'Sora Travel',
'Atlas Commerce',
'Mellow Living',
'Luma Labs',
'Nomad Supply',
'Aster Digital',
'Fieldwork',
'Contour Studio',
'Evergreen Shop',
'Nova Collective',
'Plain Goods',
'Sunday Market',
'Kinfolk Supply',
'Peak Ventures',
'Amber Exchange',
];
const industries = ['ECOMMERCE', 'SOFTWARE', 'TRAVEL', 'SERVICES'];
const countries = ['GB', 'DE', 'NL', 'EE', 'FR', 'CA'];
const now = Date.now();
const day = 86400000;
try {
for (const u of users)
await db.user.upsert({
where: { id: u.id },
create: { ...u, passwordHash: hashPassword('MerchantFlow123!') },
update: {},
});
for (let index = 0; index < names.length; index++) {
const id = `merchant-${String(index + 1).padStart(2, '0')}`;
// A second seed never rewrites the user's existing records, dates or history.
if (await db.merchant.findUnique({ where: { id } })) continue;
const status = statuses[Math.floor(index / 2)];
const ownerId = index % 2 === 0 ? 'user-manager1' : 'user-manager2';
const name = names[index];
let journey =
status === 'REJECTED'
? [...successfulStages.slice(0, 5), 'REJECTED']
: successfulStages.slice(0, successfulStages.indexOf(status) + 1);
if (status === 'KYB' && index % 2 === 0) journey = [...successfulStages.slice(0, 5), 'KYB'];
const stageEnteredAt = new Date(now - ((index % 4) + 1) * day);
const createdAt = new Date(stageEnteredAt.getTime() - (journey.length - 1) * 3 * day);
const domain = name.toLowerCase().replaceAll(' ', '') + '.example';
await db.merchant.create({
data: {
id,
name,
website: `https://${domain}`,
industry: industries[index % 4],
country: countries[index % 6],
contactName: index % 2 ? 'Jamie Wilson' : 'Sam Taylor',
contactEmail: `hello@${domain}`,
status,
ownerId,
createdAt,
stageEnteredAt,
events: {
create: journey.map((toStatus, i) => ({
id: `${id}-event-${i}`,
fromStatus: journey[i - 1] ?? null,
toStatus,
actorId:
toStatus === 'COMPLIANCE_REVIEW' || (i > 0 && toStatus === 'KYB')
? 'user-compliance'
: ownerId,
occurredAt: new Date(createdAt.getTime() + i * 3 * day),
note:
journey[i - 1] === 'COMPLIANCE_REVIEW' && toStatus === 'KYB'
? 'Please clarify the beneficial ownership structure before resubmitting.'
: null,
})),
},
checklist: {
create: documentCodes.map((documentCode, j) => ({
id: `${id}-doc-${j}`,
documentCode,
state:
status === 'KYB'
? j === 2
? 'NEEDS_CORRECTION'
: j === 3
? 'MISSING'
: 'RECEIVED'
: ['NEW_LEAD', 'CONTACTED', 'QUALIFIED'].includes(status)
? 'MISSING'
: 'RECEIVED',
note:
status === 'KYB' && j === 2
? 'Ownership declaration needs an updated signature.'
: null,
})),
},
notes: {
create: {
id: `${id}-note`,
authorId: ownerId,
text:
index % 2
? 'Команда заинтересована в подключении. Следующий контакт — после проверки документов.'
: 'Initial discovery complete. The team is interested in a straightforward checkout integration.',
createdAt: new Date(stageEnteredAt.getTime() + 3600000),
},
},
tasks: {
create: [
{
id: `${id}-task-1`,
assigneeId: ownerId,
title:
status === 'KYB'
? 'Follow up on ownership documentation'
: status === 'COMPLIANCE_REVIEW'
? 'Review the merchant document checklist'
: 'Schedule the next merchant check-in',
status: 'OPEN',
dueAt: new Date(now + ((index % 5) - 2) * day),
remindAt: new Date(now + ((index % 5) - 3) * day),
},
{
id: `${id}-task-2`,
assigneeId: ownerId,
title: 'Confirm the primary contact details',
status: 'DONE',
dueAt: stageEnteredAt,
completedAt: stageEnteredAt,
},
],
},
},
});
}
console.log('Seed ready: 4 accounts, 18 merchants. Password: MerchantFlow123!');
} finally {
await db.$disconnect();
}
+157 -8
View File
@@ -64,12 +64,23 @@ for (const language of ['en', 'ru'])
.first()
.click();
await expect(page.locator('h1')).toHaveText('Luma Labs');
await expect(page.getByText(/Please clarify the beneficial ownership/)).toBeVisible();
await expect(
page.getByText(/Please clarify the beneficial ownership/).first(),
).toBeVisible();
await noOverflow(page);
await page.reload();
await expect(page.locator('h1')).toHaveText('Luma Labs');
await expect(page.locator('html')).toHaveAttribute('lang', language);
await page.screenshot({ path: info.outputPath('merchant.png'), fullPage: true });
const editButton = page.getByRole('button', {
name: /^(Edit merchant|Изменить мерчанта)$/,
});
await editButton.click();
await expect(page.getByRole('dialog')).toBeVisible();
await noOverflow(page);
await page.screenshot({ path: info.outputPath('merchant-editor.png'), fullPage: true });
await page.keyboard.press('Escape');
await expect(page.getByRole('dialog')).not.toBeVisible();
await page.goto('/app/merchants');
await page.getByRole('combobox').selectOption('LIVE');
await expect(page.getByRole('link', { name: /Sunday Market/ }).first()).toBeVisible();
@@ -105,24 +116,23 @@ test('account switching removes old data, manager isolation and Compliance navig
await expect(page.locator('h1')).toHaveText('Northstar Studio');
await page.getByRole('button', { name: 'Sign out' }).click();
await expect(page).toHaveURL(/login/);
await signIn(page, 'manager1');
await signIn(page, 'alex');
const dashboard = await page.request.get('/api/dashboard');
expect((await dashboard.json()).merchantCount).toBe(9);
expect((await dashboard.json()).merchantCount).toBe(20);
await page.goto('/app/merchants/merchant-02');
await expect(
page.getByText('This merchant was not found or is outside your portfolio.'),
).toBeVisible();
await page.getByRole('button', { name: 'Sign out' }).click();
await signIn(page, 'compliance');
expect((await (await page.request.get('/api/dashboard')).json()).merchantCount).toBe(4);
expect((await (await page.request.get('/api/dashboard')).json()).merchantCount).toBe(45);
await page.getByRole('link', { name: 'Review queue', exact: true }).click();
await expect(page.getByRole('heading', { name: '2 merchants awaiting review' })).toBeVisible();
await expect(page.getByRole('heading', { name: '6 merchants awaiting review' })).toBeVisible();
await page.getByRole('link', { name: 'View checklist' }).first().click();
await expect(page.getByRole('heading', { name: 'KYB checklist' })).toBeVisible();
await page.goto('/app/merchants/merchant-15');
await expect(
page.getByText('This merchant was not found or is outside your portfolio.'),
).toBeVisible();
await expect(page.locator('h1')).toHaveText('Sunday Market');
await expect(page.getByRole('button', { name: 'Edit merchant', exact: true })).toHaveCount(0);
});
test('translated validation, persistent language changes and accessible form errors', async ({
page,
@@ -182,3 +192,142 @@ test('loading, retryable errors, empty states, session expiry and reduced motion
await page.goto('/app/merchants');
await expect(page).toHaveURL(/\/login\?next=/);
});
test('Head assignment, manager editing, Compliance decisions and manager activation work through the UI', async ({
page,
}, info) => {
const merchantPath = '/app/merchants/merchant-19';
const save = async () => {
await page.getByRole('button', { name: 'Save changes', exact: true }).click();
await expect(page.getByRole('dialog')).not.toBeVisible();
};
const switchAccount = async (account: string) => {
await page.getByRole('button', { name: 'Sign out', exact: true }).click();
await signIn(page, account);
await page.goto(merchantPath);
await expect(page.locator('h1')).toHaveText('Willow Ceramics');
};
const advance = async (stage: string) => {
await page.getByRole('button', { name: `Move to ${stage}`, exact: true }).click();
await expect(
page.getByRole('status').filter({ hasText: 'Changes saved.' }).first(),
).toBeVisible();
await expect
.poll(
async () => (await (await page.request.get('/api/merchants/merchant-19')).json()).status,
)
.toBe(stage.toUpperCase().replaceAll(' ', '_'));
};
await signIn(page);
await page.goto(merchantPath);
await expect(page.getByText('Unassigned', { exact: true })).toBeVisible();
await page.getByRole('button', { name: 'Assign manager', exact: true }).click();
await page.getByRole('dialog').getByLabel('Account manager').selectOption('user-manager1');
await save();
await switchAccount('alex');
await expect(page.getByRole('button', { name: 'Assign manager', exact: true })).toHaveCount(0);
await page.getByRole('button', { name: 'Edit merchant', exact: true }).click();
await page
.getByRole('dialog')
.getByLabel('Contact title', { exact: true })
.fill('Director of Partnerships');
await page
.getByRole('dialog')
.getByLabel('Estimated monthly processing (USD)', { exact: true })
.fill('246000.75');
await save();
await expect(page.getByText('Director of Partnerships', { exact: true })).toBeVisible();
await page.getByRole('button', { name: 'Log interaction', exact: true }).click();
await page.getByRole('dialog').getByLabel('Interaction type').selectOption('CALL');
await page
.getByRole('dialog')
.getByLabel('Details', { exact: true })
.fill('Confirmed the launch requirements in a discovery call.');
await save();
await expect(
page.getByText('Confirmed the launch requirements in a discovery call.', { exact: true }),
).toBeVisible();
await page.getByRole('button', { name: 'Add task', exact: true }).click();
await page
.getByRole('dialog')
.getByLabel('Task title', { exact: true })
.fill('Send the integration guide');
await save();
const taskRow = page.locator('#tasks > div').filter({ hasText: 'Send the integration guide' });
await taskRow.getByRole('button', { name: 'Complete task', exact: true }).click();
await expect(taskRow.getByText('Completed', { exact: true }).first()).toBeVisible();
await advance('Contacted');
await advance('Qualified');
await advance('KYB');
for (let i = 0; i < 4; i++) {
await page.getByRole('button', { name: 'Update document', exact: true }).nth(i).click();
await page
.getByRole('dialog')
.getByLabel('Document status', { exact: true })
.selectOption('RECEIVED');
await save();
}
await advance('Compliance Review');
await expect(page.getByRole('button', { name: 'Record decision', exact: true })).toHaveCount(0);
await switchAccount('compliance');
await page.getByRole('button', { name: 'Record decision', exact: true }).click();
await page
.getByRole('dialog')
.getByLabel('Decision', { exact: true })
.selectOption('CORRECTIONS');
await page
.getByRole('dialog')
.getByLabel('Decision reason', { exact: true })
.fill('The ownership declaration needs a current signature.');
await page
.getByRole('dialog')
.getByLabel('Ownership structure', { exact: true })
.fill('Please sign and date the declaration.');
await save();
await switchAccount('alex');
const ownership = page
.locator('#checklist > div > div')
.filter({ hasText: 'Ownership structure' });
await ownership.getByRole('button', { name: 'Update document', exact: true }).click();
await page
.getByRole('dialog')
.getByLabel('Document status', { exact: true })
.selectOption('RECEIVED');
await page
.getByRole('dialog')
.getByLabel('Note', { exact: true })
.fill('Updated signature received.');
await save();
await advance('Compliance Review');
await switchAccount('compliance');
await page.getByRole('button', { name: 'Record decision', exact: true }).click();
await page
.getByRole('dialog')
.getByLabel('Decision reason', { exact: true })
.fill('All evidence checked and approved.');
await save();
await expect(page.getByRole('button', { name: 'Edit merchant', exact: true })).toHaveCount(0);
await switchAccount('alex');
await page.getByRole('button', { name: 'Edit merchant', exact: true }).click();
await expect(
page.getByRole('dialog').getByLabel('Legal company name', { exact: true }),
).toBeDisabled();
await page.getByRole('button', { name: 'Cancel', exact: true }).click();
await advance('Testing');
await advance('Live');
await noOverflow(page);
await page.screenshot({ path: info.outputPath('approved-live-merchant.png'), fullPage: true });
await switchAccount('head');
await page.getByRole('button', { name: 'Assign manager', exact: true }).click();
await page.getByRole('dialog').getByLabel('Account manager').selectOption('user-manager2');
await save();
await switchAccount('sam');
await expect(page.getByText('Director of Partnerships', { exact: true })).toBeVisible();
const hidden = await page.request.get('/api/merchants/merchant-01');
expect(hidden.status()).toBe(404);
expect(
await page.evaluate(() =>
Object.keys(localStorage).every((key) => key === 'merchantflow.language'),
),
).toBe(true);
});