manicanldes-backend/test/b2b-credit-policies.spec.ts

245 lines
7.1 KiB
TypeScript

import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { secondActor } from './helpers/commerce';
describe('B2B credit policies', () => {
let ctx: IdentityApp;
const auth = { type: 'bearer' as const };
const url = '/api/v1/b2b/credit-policies';
async function account(verified = true) {
const created = await ctx
.api()
.post('/api/v1/b2b/accounts')
.auth(ctx.token, auth)
.send({
code: `CR-${randomUUID().slice(0, 8)}`,
legalName: 'Trade Credit Partner',
tradingName: null,
registrationNumber: randomUUID(),
taxIdentifier: null,
countryCode: 'IN',
contactEmail: 'credit@example.com',
contactPhone: null,
billingLine1: '10 Market Lane',
billingCity: 'Pune',
billingRegion: 'Maharashtra',
billingPostalCode: '411001',
})
.expect(201);
const id = created.body.id as string;
if (verified) {
await ctx
.api()
.post(`/api/v1/b2b/accounts/${id}/submit`)
.auth(ctx.token, auth)
.send({ idempotencyKey: randomUUID() })
.expect(201);
const reviewer = await secondActor(ctx, true, ['b2b.verify']);
await ctx
.api()
.post(`/api/v1/b2b/accounts/${id}/decision`)
.auth(reviewer.token, auth)
.send({
decision: 'APPROVED',
note: 'Registration checked',
idempotencyKey: randomUUID(),
})
.expect(201);
}
return id;
}
const proposal = (accountId: string) => ({
accountId,
currency: 'INR',
creditLimit: '10000.00',
netDays: 30,
rationale: 'Established wholesale customer',
idempotencyKey: randomUUID(),
});
const decision = (kind: 'APPROVED' | 'REJECTED') => ({
decision: kind,
note: 'Reviewed account documents',
idempotencyKey: randomUUID(),
});
beforeAll(async () => {
ctx = await identityApp();
}, 60000);
afterAll(async () => {
await ctx?.close();
});
beforeEach(async () => {
await ctx.clearLimits();
});
it('requires verification, preserves proposals, and detects altered retries', async () => {
const unverified = await account(false);
const invalid = await ctx
.api()
.post(url)
.auth(ctx.token, auth)
.send(proposal(unverified))
.expect(409);
expect(invalid.body.code).toBe('B2B_CREDIT_ACCOUNT_UNVERIFIED');
const accountId = await account();
const input = proposal(accountId);
const created = await ctx
.api()
.post(url)
.auth(ctx.token, auth)
.send(input)
.expect(201);
expect(created.body).toMatchObject({
accountId,
status: 'PROPOSED',
creditLimit: '10000.00',
events: [],
});
const replay = await ctx
.api()
.post(url)
.auth(ctx.token, auth)
.send(input)
.expect(201);
expect(replay.body.id).toBe(created.body.id);
const changed = await ctx
.api()
.post(url)
.auth(ctx.token, auth)
.send({ ...input, netDays: 45 })
.expect(409);
expect(changed.body.code).toBe('B2B_CREDIT_PROPOSAL_REPLAY_CONFLICT');
const listed = await ctx
.api()
.get(`${url}?accountId=${accountId}&status=PROPOSED`)
.auth(ctx.token, auth)
.expect(200);
expect(listed.body.map((item: { id: string }) => item.id)).toContain(
created.body.id,
);
});
it('requires independent approval, prevents overlap, and permits replacement after suspension', async () => {
const accountId = await account();
const first = await ctx
.api()
.post(url)
.auth(ctx.token, auth)
.send(proposal(accountId))
.expect(201);
const firstId = first.body.id as string;
const approve = decision('APPROVED');
const self = await ctx
.api()
.post(`${url}/${firstId}/decision`)
.auth(ctx.token, auth)
.send(approve)
.expect(403);
expect(self.body.code).toBe('B2B_CREDIT_SELF_REVIEW');
const reviewer = await secondActor(ctx, true, ['b2b.credit.review']);
const approved = await ctx
.api()
.post(`${url}/${firstId}/decision`)
.auth(reviewer.token, auth)
.send(approve)
.expect(201);
expect(approved.body).toMatchObject({
status: 'ACTIVE',
activeSlot: true,
events: [{ sequence: 1, kind: 'APPROVED', actorId: reviewer.userId }],
});
const replay = await ctx
.api()
.post(`${url}/${firstId}/decision`)
.auth(reviewer.token, auth)
.send(approve)
.expect(201);
expect(replay.body.events).toHaveLength(1);
const second = await ctx
.api()
.post(url)
.auth(ctx.token, auth)
.send(proposal(accountId))
.expect(201);
const overlap = await ctx
.api()
.post(`${url}/${second.body.id}/decision`)
.auth(reviewer.token, auth)
.send(decision('APPROVED'))
.expect(409);
expect(overlap.body.code).toBe('B2B_CREDIT_ACTIVE_EXISTS');
const suspended = await ctx
.api()
.post(`${url}/${firstId}/suspend`)
.auth(reviewer.token, auth)
.send({ note: 'Temporary credit hold', idempotencyKey: randomUUID() })
.expect(201);
expect(suspended.body).toMatchObject({
status: 'SUSPENDED',
activeSlot: null,
events: [{ kind: 'APPROVED' }, { sequence: 2, kind: 'SUSPENDED' }],
});
const replacement = await ctx
.api()
.post(`${url}/${second.body.id}/decision`)
.auth(reviewer.token, auth)
.send(decision('APPROVED'))
.expect(201);
expect(replacement.body.status).toBe('ACTIVE');
});
it('rejects proposals, scopes access by tenant, and enforces permissions', async () => {
const accountId = await account();
const created = await ctx
.api()
.post(url)
.auth(ctx.token, auth)
.send(proposal(accountId))
.expect(201);
const id = created.body.id as string;
const outsider = await secondActor(ctx, false, [
'b2b.credit.read',
'b2b.credit.review',
]);
expect(
(
await ctx
.api()
.get(`${url}/${id}`)
.auth(outsider.token, auth)
.expect(404)
).body.code,
).toBe('B2B_CREDIT_POLICY_NOT_FOUND');
const noPermission = await secondActor(ctx);
await ctx.api().get(url).auth(noPermission.token, auth).expect(403);
await ctx
.api()
.post(url)
.auth(noPermission.token, auth)
.send(proposal(accountId))
.expect(403);
const reviewer = await secondActor(ctx, true, ['b2b.credit.review']);
const rejected = await ctx
.api()
.post(`${url}/${id}/decision`)
.auth(reviewer.token, auth)
.send(decision('REJECTED'))
.expect(201);
expect(rejected.body).toMatchObject({
status: 'REJECTED',
events: [{ kind: 'REJECTED' }],
});
expect(
(
await ctx
.api()
.post(`${url}/${id}/suspend`)
.auth(reviewer.token, auth)
.send({ note: 'No active terms', idempotencyKey: randomUUID() })
.expect(409)
).body.code,
).toBe('B2B_CREDIT_SUSPEND_STATE');
});
});