manicanldes-backend/test/b2b-custom-candles.spec.ts

244 lines
7.9 KiB
TypeScript

import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { secondActor } from './helpers/commerce';
import { seedPartnerQuote } from './helpers/b2b-partner-order';
import { businessProfileSchema } from '../src/b2b/business.schemas';
describe('B2B custom candle requests', () => {
let ctx: IdentityApp;
let accountId: string;
const auth = { type: 'bearer' as const };
const url = '/api/v1/b2b/custom-candles';
const input = () => ({
accountId,
quantity: 500,
waxType: 'Soy',
fragrance: 'Rose',
container: 'Glass jar',
color: 'Ivory',
brandingRequirements: 'Logo label',
specifications: '200g fill and cotton wick',
idempotencyKey: randomUUID(),
});
const decision = (kind = 'APPROVED') => ({
decision: kind,
note: 'Feasibility reviewed',
idempotencyKey: randomUUID(),
});
beforeAll(async () => {
ctx = await identityApp(true);
accountId = (await seedPartnerQuote(ctx)).accountId;
}, 60000);
afterAll(async () => {
await ctx?.close();
});
beforeEach(async () => {
await ctx.clearLimits();
});
const create = (body = input()) =>
ctx.api().post(url).auth(ctx.token, auth).send(body);
it('creates immutable terms, filters requests and detects conflicting retries', async () => {
const body = input();
const created = await create(body).expect(201);
expect(created.body).toMatchObject({
...body,
status: 'REQUESTED',
decision: null,
});
expect((await create(body).expect(201)).body.id).toBe(created.body.id);
expect(
(await create({ ...body, quantity: 501 }).expect(409)).body.code,
).toBe('B2B_CUSTOM_CANDLE_REQUEST_REPLAY_CONFLICT');
const listed = await ctx
.api()
.get(`${url}?accountId=${accountId}&status=REQUESTED`)
.auth(ctx.token, auth)
.expect(200);
expect(listed.body.map((row: { id: string }) => row.id)).toContain(
created.body.id,
);
await expect(
ctx.db.b2bCustomCandleRequest.update({
where: { id: created.body.id },
data: { fragrance: 'Lavender' },
}),
).rejects.toThrow();
await expect(
ctx.db.b2bCustomCandleRequest.delete({ where: { id: created.body.id } }),
).rejects.toThrow();
});
it('requires an independent reviewer and permits exactly one auditable decision', async () => {
const id = (await create().expect(201)).body.id as string;
const approve = decision();
expect(
(
await ctx
.api()
.post(`${url}/${id}/decision`)
.auth(ctx.token, auth)
.send(approve)
.expect(403)
).body.code,
).toBe('B2B_CUSTOM_CANDLE_SELF_REVIEW');
const reviewer = await secondActor(ctx, true, ['b2b.custom.review']);
const review = (body = approve) =>
ctx
.api()
.post(`${url}/${id}/decision`)
.auth(reviewer.token, auth)
.send(body);
const result = await review().expect(201);
expect(result.body).toMatchObject({
status: 'APPROVED',
decision: {
kind: 'APPROVED',
actorId: reviewer.userId,
note: approve.note,
},
});
expect((await review().expect(201)).body.decision.id).toBe(
result.body.decision.id,
);
expect(
(await review({ ...approve, note: 'Different note' }).expect(409)).body
.code,
).toBe('B2B_CUSTOM_CANDLE_DECISION_REPLAY_CONFLICT');
expect((await review(decision('REJECTED')).expect(409)).body.code).toBe(
'B2B_CUSTOM_CANDLE_REVIEW_STATE',
);
const listed = await ctx
.api()
.get(`${url}?status=APPROVED`)
.auth(ctx.token, auth)
.expect(200);
expect(listed.body.map((row: { id: string }) => row.id)).toContain(id);
await expect(
ctx.db.b2bCustomCandleDecision.update({
where: { id: result.body.decision.id },
data: { note: 'Changed note' },
}),
).rejects.toThrow();
await expect(
ctx.db.b2bCustomCandleDecision.delete({
where: { id: result.body.decision.id },
}),
).rejects.toThrow();
expect(
await ctx.db.auditEvent.count({
where: { targetId: id, action: { startsWith: 'b2b_custom_candle.' } },
}),
).toBe(2);
});
it('records rejection and returns the current representation on request retry', async () => {
const body = input();
const id = (await create(body).expect(201)).body.id as string;
const reviewer = await secondActor(ctx, true, ['b2b.custom.review']);
await ctx
.api()
.post(`${url}/${id}/decision`)
.auth(reviewer.token, auth)
.send(decision('REJECTED'))
.expect(201);
expect((await create(body).expect(201)).body.status).toBe('REJECTED');
});
it('rejects unverified accounts and blocks self-review at the database boundary', async () => {
const profile = await ctx.db.businessAccount.findUniqueOrThrow({
where: { id: accountId },
});
const unverified = await ctx
.api()
.post('/api/v1/b2b/accounts')
.auth(ctx.token, auth)
.send({
...businessProfileSchema.strip().parse(profile),
code: 'CC-' + randomUUID().slice(0, 8),
registrationNumber: randomUUID(),
})
.expect(201);
expect(
(await create({ ...input(), accountId: unverified.body.id }).expect(409))
.body.code,
).toBe('B2B_CUSTOM_CANDLE_ACCOUNT_UNVERIFIED');
const id = (await create().expect(201)).body.id as string;
await expect(
ctx.executeSql(`INSERT INTO b2b_custom_candle_decisions
(id, organization_id, request_id, actor_id, kind, note, idempotency_key, request_hash)
VALUES ('${randomUUID()}', '${ctx.owner.organizationId}', '${id}', '${ctx.owner.userId}',
'APPROVED', 'Self approval', '${randomUUID()}', '${'a'.repeat(64)}')`),
).rejects.toThrow('independent reviewer');
});
it('serializes concurrent retries without duplicate requests or decisions', async () => {
const body = input();
const requests = await Promise.all([
create(body).expect(201),
create(body).expect(201),
]);
expect(requests[0].body.id).toBe(requests[1].body.id);
const reviewer = await secondActor(ctx, true, ['b2b.custom.review']);
const approve = decision();
const review = () =>
ctx
.api()
.post(`${url}/${requests[0].body.id}/decision`)
.auth(reviewer.token, auth)
.send(approve)
.expect(201);
const decisions = await Promise.all([review(), review()]);
expect(decisions[0].body.decision.id).toBe(decisions[1].body.decision.id);
const otherId = (await create().expect(201)).body.id as string;
expect(
(
await ctx
.api()
.post(`${url}/${otherId}/decision`)
.auth(reviewer.token, auth)
.send(approve)
.expect(409)
).body.code,
).toBe('B2B_CUSTOM_CANDLE_DECISION_REPLAY_CONFLICT');
});
it('enforces permission, organization scope and request validation', async () => {
await ctx.api().get(url).expect(401);
const denied = await secondActor(ctx, true);
await ctx.api().get(url).auth(denied.token, auth).expect(403);
await ctx
.api()
.post(url)
.auth(denied.token, auth)
.send(input())
.expect(403);
const foreign = await identityApp();
try {
const id = (await create().expect(201)).body.id as string;
await foreign
.api()
.get(`${url}/${id}`)
.auth(foreign.token, auth)
.expect(404);
await foreign
.api()
.post(`${url}/${id}/decision`)
.auth(foreign.token, auth)
.send(decision())
.expect(404);
await foreign
.api()
.post(url)
.auth(foreign.token, auth)
.send(input())
.expect(404);
} finally {
await foreign.close();
}
await create({ ...input(), quantity: 0 }).expect(400);
const docs = await ctx.api().get('/api/docs-json').expect(200);
expect(docs.body.paths[url]).toBeDefined();
});
});