import { randomUUID } from 'node:crypto'; import { identityApp, type IdentityApp } from './helpers/identity-app'; import { secondActor, seedProduct } from './helpers/commerce'; describe('B2B partner purchase orders', () => { let ctx: IdentityApp; const auth = { type: 'bearer' as const }; const url = '/api/v1/b2b/partner-orders'; async function verifiedAccount() { const created = await ctx .api() .post('/api/v1/b2b/accounts') .auth(ctx.token, auth) .send({ code: `PO-${randomUUID().slice(0, 8)}`, legalName: 'Order Partner Limited', tradingName: null, registrationNumber: randomUUID(), taxIdentifier: null, countryCode: 'IN', contactEmail: 'partner-orders@example.com', contactPhone: null, billingLine1: '10 Market Lane', billingCity: 'Pune', billingRegion: 'Maharashtra', billingPostalCode: '411001', }) .expect(201); const id = created.body.id as string; 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; } async function quote(accepted = true) { const accountId = await verifiedAccount(); const { variant } = await seedProduct(ctx, true); const list = await ctx .api() .post(`/api/v1/b2b/accounts/${accountId}/price-lists`) .auth(ctx.token, auth) .send({ name: 'Partner wholesale', currency: 'INR' }) .expect(201); await ctx .api() .put(`/api/v1/b2b/price-lists/${list.body.id}/items/${variant.id}`) .auth(ctx.token, auth) .send({ unitPrice: '275.25', minQuantity: 12 }) .expect(200); await ctx .api() .post(`/api/v1/b2b/price-lists/${list.body.id}/activate`) .auth(ctx.token, auth) .expect(201); const issued = await ctx .api() .post('/api/v1/b2b/quotes') .auth(ctx.token, auth) .send({ accountId, priceListId: list.body.id, expiresAt: new Date(Date.now() + 7 * 86400000).toISOString(), customerReference: 'Customer inquiry', lines: [{ variantId: variant.id, quantity: 12 }], idempotencyKey: randomUUID(), }) .expect(201); if (accepted) await ctx .api() .post(`/api/v1/b2b/quotes/${issued.body.id}/response`) .auth(ctx.token, auth) .send({ kind: 'ACCEPTED', note: 'Partner approved price', idempotencyKey: randomUUID(), }) .expect(201); return { accountId, quoteId: issued.body.id as string, variantId: variant.id as string, priceListId: list.body.id as string, }; } const input = (quoteId: string) => ({ quoteId, partnerReference: `PO-${randomUUID()}`, note: 'Requested by purchasing team', idempotencyKey: randomUUID(), }); beforeAll(async () => { ctx = await identityApp(); }, 60000); afterAll(async () => { await ctx?.close(); }); beforeEach(async () => { await ctx.clearLimits(); }); it('requires accepted quote and freezes its account, quantities, and prices', async () => { const pending = await quote(false); expect( ( await ctx .api() .post(url) .auth(ctx.token, auth) .send(input(pending.quoteId)) .expect(409) ).body.code, ).toBe('B2B_ORDER_QUOTE_NOT_ACCEPTED'); const source = await quote(); const request = input(source.quoteId); const created = await ctx .api() .post(url) .auth(ctx.token, auth) .send(request) .expect(201); expect(created.body).toMatchObject({ status: 'RECEIVED', accountId: source.accountId, quoteId: source.quoteId, merchandiseTotal: '3303.00', partnerReference: request.partnerReference, accountSnapshot: { legalName: 'Order Partner Limited' }, lines: [ { variantId: source.variantId, quantity: 12, minQuantity: 12, unitPrice: '275.25', lineTotal: '3303.00', }, ], }); expect(created.body.number).toMatch(/^BO-[A-F0-9]{20}$/); const replay = await ctx .api() .post(url) .auth(ctx.token, auth) .send(request) .expect(201); expect(replay.body.id).toBe(created.body.id); expect( ( await ctx .api() .post(url) .auth(ctx.token, auth) .send({ ...request, partnerReference: 'CHANGED' }) .expect(409) ).body.code, ).toBe('B2B_ORDER_REPLAY_CONFLICT'); expect( ( await ctx .api() .post(url) .auth(ctx.token, auth) .send(input(source.quoteId)) .expect(409) ).body.code, ).toBe('B2B_ORDER_QUOTE_USED'); const listed = await ctx .api() .get(`${url}?accountId=${source.accountId}`) .auth(ctx.token, auth) .expect(200); expect(listed.body.map((order: { id: string }) => order.id)).toContain( created.body.id, ); }); it('prevents duplicate partner references and records one immutable cancellation', async () => { const source = await quote(); const request = input(source.quoteId); const created = await ctx .api() .post(url) .auth(ctx.token, auth) .send(request) .expect(201); const secondQuote = await ctx .api() .post('/api/v1/b2b/quotes') .auth(ctx.token, auth) .send({ accountId: source.accountId, priceListId: source.priceListId, expiresAt: new Date(Date.now() + 7 * 86400000).toISOString(), customerReference: 'Second inquiry', lines: [{ variantId: source.variantId, quantity: 12 }], idempotencyKey: randomUUID(), }) .expect(201); await ctx .api() .post(`/api/v1/b2b/quotes/${secondQuote.body.id}/response`) .auth(ctx.token, auth) .send({ kind: 'ACCEPTED', note: 'Second quote accepted', idempotencyKey: randomUUID(), }) .expect(201); expect( ( await ctx .api() .post(url) .auth(ctx.token, auth) .send({ ...input(secondQuote.body.id), partnerReference: request.partnerReference, }) .expect(409) ).body.code, ).toBe('B2B_ORDER_REFERENCE_USED'); const cancel = { reason: 'Partner withdrew purchase order', idempotencyKey: randomUUID(), }; const path = `${url}/${created.body.id}/cancel`; const cancelled = await ctx .api() .post(path) .auth(ctx.token, auth) .send(cancel) .expect(201); expect(cancelled.body).toMatchObject({ status: 'CANCELLED', cancellation: { reason: cancel.reason, actorId: ctx.owner.userId, }, }); expect( ( await ctx .api() .post(path) .auth(ctx.token, auth) .send(cancel) .expect(201) ).body.status, ).toBe('CANCELLED'); expect( ( await ctx .api() .post(path) .auth(ctx.token, auth) .send({ ...cancel, reason: 'Different reason' }) .expect(409) ).body.code, ).toBe('B2B_ORDER_CANCEL_REPLAY_CONFLICT'); expect( ( await ctx .api() .post(path) .auth(ctx.token, auth) .send({ reason: 'Another cancellation', idempotencyKey: randomUUID(), }) .expect(409) ).body.code, ).toBe('B2B_ORDER_ALREADY_CANCELLED'); }); it('scopes reads and commands to organization and permissions', async () => { const source = await quote(); const created = await ctx .api() .post(url) .auth(ctx.token, auth) .send(input(source.quoteId)) .expect(201); const outsider = await secondActor(ctx, false, [ 'b2b.order.read', 'b2b.order.manage', ]); expect( ( await ctx .api() .get(`${url}/${created.body.id}`) .auth(outsider.token, auth) .expect(404) ).body.code, ).toBe('B2B_ORDER_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(input(source.quoteId)) .expect(403); }); });