feat(b2b): add partner order and payment reports
This commit is contained in:
parent
16296e5e22
commit
eb02a059b8
|
|
@ -68,3 +68,5 @@ B2B partner purchase orders: see [Phase 3G API guide](docs/b2b-partner-orders-ap
|
|||
B2B partner partial payments: see [Phase 3H API guide](docs/b2b-partner-payments-api.md).
|
||||
|
||||
B2B custom candle requests and staff review: see [Phase 3I API guide](docs/b2b-custom-candles-api.md).
|
||||
|
||||
B2B partner reports: see [Phase 3J API guide](docs/b2b-partner-reporting-api.md).
|
||||
|
|
|
|||
|
|
@ -0,0 +1,23 @@
|
|||
# B2B partner reporting (Phase 3J)
|
||||
|
||||
`GET /api/v1/b2b/accounts/:id/report` requires a bearer session and the dedicated `b2b.report.read` permission. The account must belong to the caller's organization; missing or out-of-scope accounts return 404. A report is available even when an account has no orders or is not verified, so staff can inspect its history.
|
||||
|
||||
The response contains `accountId` and a `currencies` array sorted by currency code. Each currency contains:
|
||||
|
||||
| Field | Meaning |
|
||||
| ------------------------- | --------------------------------------------------------- |
|
||||
| `orderCount` | All partner orders, including cancelled orders |
|
||||
| `activeOrderCount` | Orders without cancellation |
|
||||
| `cancelledOrderCount` | Orders with a recorded cancellation |
|
||||
| `unpaidOrderCount` | Active orders with no unreversed receipts |
|
||||
| `partiallyPaidOrderCount` | Active orders paid above zero but below merchandise total |
|
||||
| `paidOrderCount` | Active orders with merchandise fully paid |
|
||||
| `merchandiseTotal` | Total merchandise value of active orders |
|
||||
| `paidTotal` | Unreversed receipts against active orders |
|
||||
| `outstandingTotal` | Active merchandise value minus unreversed receipts |
|
||||
|
||||
All amounts are exact decimal strings with two fractional digits. Different currencies are never combined or converted. Each order contributes once regardless of how many receipts it has. Reversals restore outstanding balances; cancelled orders retain their counts but contribute no financial totals. An account with no orders returns `{ "accountId": "<uuid>", "currencies": [] }`.
|
||||
|
||||
Reports cover all recorded history. A repeatable-read transaction provides a consistent account lookup and aggregate. Reads create no audit events and change no order/payment records. This is a merchandise-balance report; it does not establish credit utilization, overdue status, tax, shipping, refunds, gateway settlement, or accounting receivables.
|
||||
|
||||
The permission migration grants access to existing system Owner roles. Custom roles need an explicit RBAC grant. No schema, provider, or configuration change is required beyond deploying the append-only permission migration. Removing a custom role's report permission disables access; financial records remain intact.
|
||||
|
|
@ -48,6 +48,8 @@ Business verification, price lists, MOQ, quotations, credit policies, samples, b
|
|||
- 3H (implemented): manual, partial external receipt records for partner orders with exact merchandise-balance checks, idempotent reversals, and cancellation protection. Gateway collection, refunds, tax, shipping, and credit utilization remain separate milestones.
|
||||
- 3I (implemented): verified-account custom candle specifications with immutable request capture, independent one-time staff review, scoped permissions, and idempotent retries. Quotation, artwork approval, BOM, and production linkage remain separate milestones.
|
||||
|
||||
- 3J (implemented): read-only partner order and payment summaries by currency, with exact outstanding merchandise balances, reversal/cancellation handling, and dedicated report permissions. Credit utilization, overdue receivables, and accounting remain separate milestones.
|
||||
|
||||
## Phase 4: Growth channels
|
||||
|
||||
Wishlist, verified reviews/moderation, seasonal campaigns, discounts, cart recovery, consent-aware messaging, Instagram, Etsy, WhatsApp, blogs/SEO and segmentation.
|
||||
|
|
|
|||
|
|
@ -41,5 +41,6 @@
|
|||
"20261003000100_b2b_artwork_approvals": "1359390fc3692bdc2dea8a4cc12223d97c7c15b0cdd2181b082b5e5acbe33677",
|
||||
"20261003151400_b2b_partner_orders": "ffbba39ed98a16c122b0756a97d721adde9268904f9a7d9770407f341ef848ba",
|
||||
"20261003183000_b2b_partner_payments": "bc43c5a713c62aa201affa2f2595156a2fc68882774504cdf12ac4cf0f641452",
|
||||
"20261004003000_b2b_custom_candle_requests": "ab78d0a7e214ab226e042f29b42e961ddbae3a3e338fd65983d5aa87e2c736ac"
|
||||
"20261004003000_b2b_custom_candle_requests": "ab78d0a7e214ab226e042f29b42e961ddbae3a3e338fd65983d5aa87e2c736ac",
|
||||
"20261004010000_b2b_partner_reporting": "44086ecc27278b9499fbcf5fa97ed754f056fcf49f6b155e1ed377527616dc89"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,2 @@
|
|||
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['b2b.report.read']))
|
||||
WHERE is_system = true AND name = 'Owner';
|
||||
|
|
@ -1,4 +1,6 @@
|
|||
import { CustomCandlesController } from './custom-candles.controller';
|
||||
import { PartnerReportsController } from './partner-reports.controller';
|
||||
import { PartnerReportStore } from './partner-report.store';
|
||||
import { CustomCandleStore } from './custom-candle.store';
|
||||
import { CustomCandleReviewStore } from './custom-candle-review.store';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
|
@ -36,6 +38,7 @@ import { PartnerPaymentWriteStore } from './partner-payment-write.store';
|
|||
@Module({
|
||||
imports: [DatabaseModule, IdentityModule],
|
||||
controllers: [
|
||||
PartnerReportsController,
|
||||
CustomCandlesController,
|
||||
BusinessController,
|
||||
PriceListsController,
|
||||
|
|
@ -49,6 +52,7 @@ import { PartnerPaymentWriteStore } from './partner-payment-write.store';
|
|||
PartnerPaymentsController,
|
||||
],
|
||||
providers: [
|
||||
PartnerReportStore,
|
||||
CustomCandleStore,
|
||||
CustomCandleReviewStore,
|
||||
BusinessStore,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,76 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { Prisma } from '../generated/prisma/client';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import { requireBusinessAccount } from './price-list.helpers';
|
||||
|
||||
type CurrencyReport = {
|
||||
currency: string;
|
||||
orderCount: number;
|
||||
activeOrderCount: number;
|
||||
cancelledOrderCount: number;
|
||||
unpaidOrderCount: number;
|
||||
partiallyPaidOrderCount: number;
|
||||
paidOrderCount: number;
|
||||
merchandiseTotal: string;
|
||||
paidTotal: string;
|
||||
outstandingTotal: string;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class PartnerReportStore {
|
||||
constructor(private readonly db: DatabaseService) {}
|
||||
|
||||
report(actor: Principal, accountId: string) {
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
await requireBusinessAccount(tx, actor.organizationId, accountId);
|
||||
const currencies = await tx.$queryRaw<CurrencyReport[]>`
|
||||
WITH order_balances AS (
|
||||
SELECT o.currency, o.merchandise_total, c.order_id IS NOT NULL AS cancelled,
|
||||
COALESCE(p.paid_total, 0) AS paid_total
|
||||
FROM b2b_partner_orders o
|
||||
LEFT JOIN b2b_partner_order_cancellations c
|
||||
ON c.order_id = o.id AND c.organization_id = o.organization_id
|
||||
LEFT JOIN (
|
||||
SELECT p.order_id, p.organization_id, SUM(p.amount) AS paid_total
|
||||
FROM b2b_partner_payments p
|
||||
JOIN b2b_partner_orders target
|
||||
ON target.id = p.order_id AND target.organization_id = p.organization_id
|
||||
LEFT JOIN b2b_partner_payment_reversals r
|
||||
ON r.payment_id = p.id AND r.organization_id = p.organization_id
|
||||
WHERE p.organization_id = ${actor.organizationId}::uuid
|
||||
AND target.account_id = ${accountId}::uuid AND r.payment_id IS NULL
|
||||
GROUP BY p.order_id, p.organization_id
|
||||
) p ON p.order_id = o.id AND p.organization_id = o.organization_id
|
||||
WHERE o.organization_id = ${actor.organizationId}::uuid AND o.account_id = ${accountId}::uuid
|
||||
)
|
||||
SELECT currency, COUNT(*)::int AS "orderCount",
|
||||
COUNT(*) FILTER (WHERE NOT cancelled)::int AS "activeOrderCount",
|
||||
COUNT(*) FILTER (WHERE cancelled)::int AS "cancelledOrderCount",
|
||||
COUNT(*) FILTER (WHERE NOT cancelled AND paid_total = 0)::int AS "unpaidOrderCount",
|
||||
COUNT(*) FILTER (WHERE NOT cancelled AND paid_total > 0 AND paid_total < merchandise_total)::int AS "partiallyPaidOrderCount",
|
||||
COUNT(*) FILTER (WHERE NOT cancelled AND paid_total = merchandise_total)::int AS "paidOrderCount",
|
||||
COALESCE(SUM(merchandise_total) FILTER (WHERE NOT cancelled), 0)::text AS "merchandiseTotal",
|
||||
COALESCE(SUM(paid_total) FILTER (WHERE NOT cancelled), 0)::text AS "paidTotal",
|
||||
COALESCE(SUM(merchandise_total - paid_total) FILTER (WHERE NOT cancelled), 0)::text AS "outstandingTotal"
|
||||
FROM order_balances GROUP BY currency ORDER BY currency
|
||||
`;
|
||||
return {
|
||||
accountId,
|
||||
currencies: currencies.map((row) => ({
|
||||
...row,
|
||||
merchandiseTotal: new Prisma.Decimal(row.merchandiseTotal).toFixed(
|
||||
2,
|
||||
),
|
||||
paidTotal: new Prisma.Decimal(row.paidTotal).toFixed(2),
|
||||
outstandingTotal: new Prisma.Decimal(row.outstandingTotal).toFixed(
|
||||
2,
|
||||
),
|
||||
})),
|
||||
};
|
||||
},
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
import { Controller, Get, Param, ParseUUIDPipe } from '@nestjs/common';
|
||||
import {
|
||||
CurrentPrincipal,
|
||||
RequirePermission,
|
||||
} from '../identity/access.decorator';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import { PartnerReportStore } from './partner-report.store';
|
||||
|
||||
@Controller('b2b/accounts')
|
||||
export class PartnerReportsController {
|
||||
constructor(private readonly reports: PartnerReportStore) {}
|
||||
|
||||
@Get(':id/report')
|
||||
@RequirePermission('b2b.report.read')
|
||||
report(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
) {
|
||||
return this.reports.report(actor, id);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
export const PERMISSIONS = [
|
||||
'b2b.report.read',
|
||||
'b2b.custom.read',
|
||||
'b2b.custom.request',
|
||||
'b2b.custom.review',
|
||||
|
|
|
|||
|
|
@ -0,0 +1,59 @@
|
|||
import { PartnerReportStore } from '../src/b2b/partner-report.store';
|
||||
import type { DatabaseService } from '../src/database/database.service';
|
||||
import type { Principal } from '../src/identity/identity.types';
|
||||
|
||||
describe('Partner report presentation', () => {
|
||||
const actor = { organizationId: 'organization' } as Principal;
|
||||
it('preserves exact large totals and reports an empty account without fabricated currency', async () => {
|
||||
const tx = {
|
||||
businessAccount: {
|
||||
findFirst: jest.fn().mockResolvedValue({ id: 'account' }),
|
||||
},
|
||||
$queryRaw: jest.fn().mockResolvedValue([
|
||||
{
|
||||
currency: 'INR',
|
||||
orderCount: 2,
|
||||
activeOrderCount: 2,
|
||||
cancelledOrderCount: 0,
|
||||
unpaidOrderCount: 1,
|
||||
partiallyPaidOrderCount: 1,
|
||||
paidOrderCount: 0,
|
||||
merchandiseTotal: '999999999999999999999.99',
|
||||
paidTotal: '0.01',
|
||||
outstandingTotal: '999999999999999999999.98',
|
||||
},
|
||||
]),
|
||||
};
|
||||
const db = { $transaction: jest.fn(async (work) => work(tx)) };
|
||||
const store = new PartnerReportStore(db as unknown as DatabaseService);
|
||||
expect((await store.report(actor, 'account')).currencies[0]).toMatchObject({
|
||||
merchandiseTotal: '999999999999999999999.99',
|
||||
paidTotal: '0.01',
|
||||
outstandingTotal: '999999999999999999999.98',
|
||||
});
|
||||
expect(db.$transaction).toHaveBeenCalledWith(expect.any(Function), {
|
||||
isolationLevel: 'RepeatableRead',
|
||||
});
|
||||
tx.$queryRaw.mockResolvedValue([]);
|
||||
expect(await store.report(actor, 'account')).toEqual({
|
||||
accountId: 'account',
|
||||
currencies: [],
|
||||
});
|
||||
});
|
||||
it('rejects missing accounts before querying financial records', async () => {
|
||||
const tx = {
|
||||
businessAccount: { findFirst: jest.fn().mockResolvedValue(null) },
|
||||
$queryRaw: jest.fn(),
|
||||
};
|
||||
const db = {
|
||||
$transaction: async (work: (value: typeof tx) => unknown) => work(tx),
|
||||
};
|
||||
await expect(
|
||||
new PartnerReportStore(db as unknown as DatabaseService).report(
|
||||
actor,
|
||||
'missing',
|
||||
),
|
||||
).rejects.toMatchObject({ code: 'BUSINESS_ACCOUNT_NOT_FOUND' });
|
||||
expect(tx.$queryRaw).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,216 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
||||
import {
|
||||
seedPartnerQuote,
|
||||
seedPartnerOrder,
|
||||
} from './helpers/b2b-partner-order';
|
||||
import { secondActor } from './helpers/commerce';
|
||||
|
||||
describe('B2B partner reporting', () => {
|
||||
let ctx: IdentityApp;
|
||||
let source: Awaited<ReturnType<typeof seedPartnerQuote>>;
|
||||
const auth = { type: 'bearer' as const };
|
||||
const reportUrl = () => `/api/v1/b2b/accounts/${source.accountId}/report`;
|
||||
const report = () =>
|
||||
ctx.api().get(reportUrl()).auth(ctx.token, auth).expect(200);
|
||||
beforeAll(async () => {
|
||||
ctx = await identityApp(true);
|
||||
source = await seedPartnerQuote(ctx);
|
||||
}, 60000);
|
||||
afterAll(async () => {
|
||||
await ctx?.close();
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await ctx.clearLimits();
|
||||
});
|
||||
|
||||
async function order(
|
||||
priceListId = source.priceListId,
|
||||
variantId = source.variantId,
|
||||
) {
|
||||
const quote = await ctx
|
||||
.api()
|
||||
.post('/api/v1/b2b/quotes')
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
accountId: source.accountId,
|
||||
priceListId,
|
||||
expiresAt: new Date(Date.now() + 86400000).toISOString(),
|
||||
customerReference: 'Report fixture',
|
||||
lines: [{ variantId, quantity: 12 }],
|
||||
idempotencyKey: randomUUID(),
|
||||
})
|
||||
.expect(201);
|
||||
await ctx
|
||||
.api()
|
||||
.post(`/api/v1/b2b/quotes/${quote.body.id}/response`)
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
kind: 'ACCEPTED',
|
||||
note: 'Partner accepted',
|
||||
idempotencyKey: randomUUID(),
|
||||
})
|
||||
.expect(201);
|
||||
return (
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/b2b/partner-orders')
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
quoteId: quote.body.id,
|
||||
partnerReference: randomUUID(),
|
||||
idempotencyKey: randomUUID(),
|
||||
})
|
||||
.expect(201)
|
||||
).body.id as string;
|
||||
}
|
||||
async function pay(orderId: string, amount: string) {
|
||||
return (
|
||||
await ctx
|
||||
.api()
|
||||
.post(`/api/v1/b2b/partner-orders/${orderId}/payments`)
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
amount,
|
||||
reference: randomUUID(),
|
||||
method: 'BANK_TRANSFER',
|
||||
receivedOn: '2026-10-04',
|
||||
idempotencyKey: randomUUID(),
|
||||
})
|
||||
.expect(201)
|
||||
).body.id as string;
|
||||
}
|
||||
|
||||
it('reports zero orders as an empty currency list and supports Swagger', async () => {
|
||||
expect((await report()).body).toEqual({
|
||||
accountId: source.accountId,
|
||||
currencies: [],
|
||||
});
|
||||
const docs = await ctx.api().get('/api/docs-json').expect(200);
|
||||
expect(docs.body.paths['/api/v1/b2b/accounts/{id}/report']).toBeDefined();
|
||||
});
|
||||
|
||||
it('aggregates each order once, ignores reversed receipts and excludes cancelled merchandise', async () => {
|
||||
const partial = await order();
|
||||
await pay(partial, '100.25');
|
||||
await pay(partial, '200.25');
|
||||
const paid = await order();
|
||||
await pay(paid, '3303.00');
|
||||
const cancelled = await order();
|
||||
const paymentId = await pay(cancelled, '500.00');
|
||||
await ctx
|
||||
.api()
|
||||
.post(
|
||||
`/api/v1/b2b/partner-orders/${cancelled}/payments/${paymentId}/reverse`,
|
||||
)
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
reason: 'Incorrect receipt',
|
||||
idempotencyKey: randomUUID(),
|
||||
})
|
||||
.expect(201);
|
||||
await ctx
|
||||
.api()
|
||||
.post(`/api/v1/b2b/partner-orders/${cancelled}/cancel`)
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
reason: 'Partner withdrew',
|
||||
idempotencyKey: randomUUID(),
|
||||
})
|
||||
.expect(201);
|
||||
await order();
|
||||
expect((await report()).body.currencies).toEqual([
|
||||
{
|
||||
currency: 'INR',
|
||||
orderCount: 4,
|
||||
activeOrderCount: 3,
|
||||
cancelledOrderCount: 1,
|
||||
unpaidOrderCount: 1,
|
||||
partiallyPaidOrderCount: 1,
|
||||
paidOrderCount: 1,
|
||||
merchandiseTotal: '9909.00',
|
||||
paidTotal: '3603.50',
|
||||
outstandingTotal: '6305.50',
|
||||
},
|
||||
]);
|
||||
const before = await ctx.db.auditEvent.count();
|
||||
await report();
|
||||
expect(await ctx.db.auditEvent.count()).toBe(before);
|
||||
});
|
||||
|
||||
it('keeps currencies separate and excludes other business accounts', async () => {
|
||||
const original = await ctx.db.productVariant.findUniqueOrThrow({
|
||||
where: { id: source.variantId },
|
||||
});
|
||||
const variant = await ctx
|
||||
.api()
|
||||
.post(`/api/v1/products/${original.productId}/variants`)
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
sku: randomUUID(),
|
||||
name: 'USD candle',
|
||||
price: '400.00',
|
||||
currency: 'USD',
|
||||
active: true,
|
||||
attributes: {},
|
||||
})
|
||||
.expect(201);
|
||||
const list = await ctx
|
||||
.api()
|
||||
.post(`/api/v1/b2b/accounts/${source.accountId}/price-lists`)
|
||||
.auth(ctx.token, auth)
|
||||
.send({ name: 'USD wholesale', currency: 'USD' })
|
||||
.expect(201);
|
||||
await ctx
|
||||
.api()
|
||||
.put(`/api/v1/b2b/price-lists/${list.body.id}/items/${variant.body.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 usdOrder = await order(list.body.id, variant.body.id);
|
||||
await pay(usdOrder, '0.01');
|
||||
const other = await seedPartnerOrder(ctx);
|
||||
await pay(other.order.id, '100.00');
|
||||
const result = (await report()).body.currencies;
|
||||
expect(result.map((row: { currency: string }) => row.currency)).toEqual([
|
||||
'INR',
|
||||
'USD',
|
||||
]);
|
||||
expect(result[0]).toMatchObject({ orderCount: 4, paidTotal: '3603.50' });
|
||||
expect(result[1]).toMatchObject({
|
||||
currency: 'USD',
|
||||
orderCount: 1,
|
||||
merchandiseTotal: '3303.00',
|
||||
paidTotal: '0.01',
|
||||
outstandingTotal: '3302.99',
|
||||
});
|
||||
});
|
||||
|
||||
it('requires dedicated report permission and scopes account lookup', async () => {
|
||||
await ctx.api().get(reportUrl()).expect(401);
|
||||
const denied = await secondActor(ctx, true, [
|
||||
'b2b.order.read',
|
||||
'b2b.payment.read',
|
||||
]);
|
||||
await ctx.api().get(reportUrl()).auth(denied.token, auth).expect(403);
|
||||
const reader = await secondActor(ctx, true, ['b2b.report.read']);
|
||||
await ctx.api().get(reportUrl()).auth(reader.token, auth).expect(200);
|
||||
const outsider = await secondActor(ctx, false, ['b2b.report.read']);
|
||||
await ctx.api().get(reportUrl()).auth(outsider.token, auth).expect(404);
|
||||
await ctx
|
||||
.api()
|
||||
.get(`/api/v1/b2b/accounts/${randomUUID()}/report`)
|
||||
.auth(ctx.token, auth)
|
||||
.expect(404);
|
||||
await ctx
|
||||
.api()
|
||||
.get('/api/v1/b2b/accounts/invalid/report')
|
||||
.auth(ctx.token, auth)
|
||||
.expect(400);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue