feat(profitability): add sealed batch contribution scenarios
continuous-integration/drone/push Build is passing Details

This commit is contained in:
mihir 2026-10-08 16:03:29 +05:30
parent 5ac4e20ccf
commit eb37578e1d
15 changed files with 404 additions and 2 deletions

View File

@ -94,3 +94,5 @@ Commerce activity analytics: see [Phase 5B API guide](docs/commerce-analytics-ap
Captured-request forecast baseline: see [Phase 5C API guide](docs/capture-forecasts-api.md).
Accounting source events: see [Phase 5D API guide](docs/accounting-source-feed-api.md).
Indicative batch material contribution: see [Phase 5E API guide](docs/batch-contribution-api.md).

View File

@ -0,0 +1,30 @@
# Indicative batch contribution (Phase 5E)
Staff can compare a completed batch's sealed standard material/packaging cost with an explicit net unit-price assumption. The report reuses immutable actual-consumption/wastage and packaging cost evidence from Phase 2M, including frozen standard rate revisions. It does not infer costs from current catalog prices, pending orders, or unrelated batches.
`GET /api/v1/profitability/batches/:batchId?currency=INR&unitNetPrice=5.00` requires `profitability.read`. The active session, user/organization scope, and permission are rechecked inside the read transaction. `cost.read` alone does not grant access, and a profitability-only reader can see this summary without receiving detailed material/rate evidence. Existing system Owners gain the new permission; custom roles remain explicit.
Both query fields are required. Currency uses the existing supported currency set and must match the sealed snapshot; there is no FX conversion. `unitNetPrice` is a nonnegative two-decimal string up to `9999999999.99`, interpreted as a staff-selected selling-price assumption after discounts and excluding selling taxes/freight charges. No price is taken automatically from the catalog or an order. Negative, imprecise, oversized, missing, or extra fields return 400. Missing sessions return 401, insufficient permission 403, and currency mismatch `PROFITABILITY_CURRENCY` (409).
Only a sealed cost snapshot attached to a completed batch in the caller's organization is eligible. Missing, unsealed, unknown and foreign-scope evidence returns `BATCH_COST_NOT_FOUND` (404). Snapshot creation stays in the existing cost workflow; this read does not seal, recost, or rewrite any batch. The scoped response includes batch/variant/snapshot IDs, seal date, currency, good output quantity, explicit price, production/packaging subtotals, and `basis: "SEALED_BATCH_STANDARD_MATERIAL_COST"`.
The returned calculations are:
| Field | Definition |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `comparisonNetValue` | Price assumption multiplied by all good units. |
| `standardMaterialCost` | Sealed production plus packaging material total, including recorded wastage. |
| `materialContribution` | Comparison value minus sealed material cost; negative amounts are retained. |
| `contributionRateBps` | Contribution/value × 10,000, nearest integer with half away from zero; signed integer string, or null when comparison value is zero. |
| `breakEvenUnitNetPrice` | Sealed cost divided by good units, rounded **up** to a whole cent; null when no good units exist. |
| `comparisonState` | `ABOVE_MATERIAL_BREAK_EVEN`, `AT_MATERIAL_BREAK_EVEN`, `BELOW_MATERIAL_BREAK_EVEN`, or `NO_GOOD_OUTPUT`. |
Money uses exact integer cents and two-decimal strings. Scenario totals can exceed the per-order money limit without floating-point loss. Basis-point rates use strings so large negative values remain exact. A zero-price scenario returns the signed material shortfall and null rate. A batch with zero good output returns zero comparison value, negative captured material cost, null break-even/rate, and `NO_GOOD_OUTPUT`, avoiding division by zero. Break-even is calculated from the full batch cost; rounding a display unit cost down must not understate it.
The summary lists excluded categories: labour, overhead, fulfillment, channel fees, marketing and finance. These costs are not recorded here and are not silently estimated or treated as zero in a net-profit claim. The report is an indicative **material contribution scenario**, not realized revenue, recognized net profit, a complete margin statement, cost-of-goods-sold allocation, or evidence that all good units were sold. No sale-to-batch attribution, tax treatment, inventory valuation policy, or external ledger posting is invented.
Sealed rate changes and later catalog repricing do not change cost evidence or the chosen price assumption. Staff must supply a new price to evaluate another scenario. No customer data, supplier contact/evidence, creator identities, hashes or keys are returned. No audit event or report table is created for this read. Full cost lines remain behind their existing permission.
Deploy the additive Owner-permission migration before the application. No schema table, dependency, pricing policy, source amount or historical migration changes. Older code ignores the permission on rollback. This branch is stacked on the pushed Phase 5D accounting source branch; merge that prerequisite first or review the stacked diff accordingly.
Verification covers positive/negative/zero contribution, exact large values, upward break-even rounding, signed basis-point rounding, zero price/output, sealed evidence, frozen rates and ignored catalog changes, explicit currency matching, independent permission, organization isolation, strict price input and migration drift. Realized profitability, complete expense/COGS attribution, margin dashboards and native multi-connection PostgreSQL checks remain separate work.

View File

@ -71,6 +71,7 @@ Moderated forums, advanced analytics, forecasts, accounting adapters, profitabil
- 5B (implemented): bounded UTC daily checkout activity and frozen variant-demand analytics, current-state/currency separation, exact snapshot values, scoped reporting permissions, and UTC application sessions. Paid/fulfilled revenue, financial recognition, forecasts, cross-channel analytics and dashboard UI remain separate milestones.
- 5C (baseline implemented): bounded historical daily capture-rate projections with exact unit arithmetic, zero-day inclusion, cancellation exclusion, visible evidence/staleness and current catalog flags. Validated sales/seasonal forecasts, confidence intervals, stock actions and automated production planning remain separate milestones.
- 5D (source contract implemented): scoped, bounded accounting source-event pages for supplier invoices/payments and partner receipts, with original/correction links, exact captured amounts and deterministic cursor traversal. Provider posting, ledger/tax mapping and durable export acknowledgements remain separate milestones.
- 5E (material-contribution baseline implemented): explicit net-price scenarios against sealed batch material/packaging cost, signed exact contribution, upward break-even prices and zero-output handling. Realized net profit, complete expense/COGS attribution, sales-to-batch linkage and dashboards remain separate milestones.
## Definition of done for every feature

View File

@ -54,5 +54,6 @@
"20261007160000_moderated_forums": "3a7dce2115e06acd0f4b02d366721db5ebcf8b5f31106b5d85093c1374a2b6a5",
"20261007170000_commerce_analytics": "800e392f788e176e3fb27c04f956a18e5f1505b820af6bb2364fc990aa8d26ea",
"20261008100000_capture_forecasts": "69b94ac61b9f1c3f47268d5586d7f73c4c392cabdd3049d01f34e5e033cac043",
"20261008110000_accounting_sources": "47b89e83291dbdf7b9fc7f1f25e7260a9f06bde0291ae2f7db01200e75eed396"
"20261008110000_accounting_sources": "47b89e83291dbdf7b9fc7f1f25e7260a9f06bde0291ae2f7db01200e75eed396",
"20261008120000_batch_contribution": "4d6c577e6d59e9163c41253b828ed19729b76d881f21197f6b863c2f79233471"
}

View File

@ -0,0 +1,2 @@
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['profitability.read']))
WHERE is_system = true AND name = 'Owner';

View File

@ -5,6 +5,7 @@ import { CAMPAIGN_ERRORS } from './campaign-errors';
import { MESSAGING_ERRORS } from './messaging-errors';
import { BLOG_ERRORS } from './blog-errors';
import { FORUM_ERRORS } from './forum-errors';
import { PROFITABILITY_ERRORS } from './profitability-errors';
import { CHECKOUT_ERRORS } from './checkout-errors';
import { OPERATIONS_ERRORS } from './operations-errors';
import { PLATFORM_ERRORS } from './platform-errors';
@ -18,6 +19,7 @@ import { B2B_ARTWORK_ERRORS } from './b2b-artwork-errors';
import { B2B_ORDER_ERRORS } from './b2b-order-errors';
import { B2B_PAYMENT_ERRORS } from './b2b-payment-errors';
export const ERRORS = {
...PROFITABILITY_ERRORS,
...FORUM_ERRORS,
...BLOG_ERRORS,
...MESSAGING_ERRORS,

View File

@ -0,0 +1,12 @@
export const PROFITABILITY_ERRORS = {
PROFITABILITY_CURRENCY: [
409,
'Comparison currency must match the cost snapshot',
'Profitability currency mismatch',
],
PROFITABILITY_QUANTITY: [
409,
'Batch output quantity is invalid',
'Invalid batch contribution quantity',
],
} as const;

View File

@ -0,0 +1,42 @@
import { minor } from '../checkout/money';
import { AppError } from '../common/errors/app-error';
function signedMoney(value: bigint) {
const magnitude = value < 0n ? -value : value;
return `${value < 0n ? '-' : ''}${magnitude / 100n}.${(magnitude % 100n).toString().padStart(2, '0')}`;
}
export function materialContribution(
totalCost: string,
goodQuantity: number,
unitNetPrice: string,
) {
if (!Number.isInteger(goodQuantity) || goodQuantity < 0)
throw new AppError('PROFITABILITY_QUANTITY');
const cost = minor(totalCost);
const quantity = BigInt(goodQuantity);
const comparison = minor(unitNetPrice) * quantity;
const contribution = comparison - cost;
const magnitude = contribution < 0n ? -contribution : contribution;
const roundedRate =
comparison === 0n
? null
: (magnitude * 10000n + comparison / 2n) / comparison;
return {
comparisonNetValue: signedMoney(comparison),
materialContribution: signedMoney(contribution),
contributionRateBps:
roundedRate === null
? null
: (contribution < 0n ? -roundedRate : roundedRate).toString(),
breakEvenUnitNetPrice:
quantity === 0n ? null : signedMoney((cost + quantity - 1n) / quantity),
comparisonState:
quantity === 0n
? 'NO_GOOD_OUTPUT'
: contribution > 0n
? 'ABOVE_MATERIAL_BREAK_EVEN'
: contribution < 0n
? 'BELOW_MATERIAL_BREAK_EVEN'
: 'AT_MATERIAL_BREAK_EVEN',
};
}

View File

@ -4,6 +4,8 @@ import { IdentityModule } from '../identity/identity.module';
import { CostingStore } from './costing.store';
import { BatchCostController } from './batch-cost.controller';
import { BatchCostStore } from './batch-cost.store';
import { ProfitabilityStore } from './profitability.store';
import { ProfitabilityController } from './profitability.controller';
import {
MaterialCostRatesController,
PackagingCostController,
@ -12,8 +14,9 @@ import {
@Module({
imports: [DatabaseModule, IdentityModule],
providers: [CostingStore, BatchCostStore],
providers: [CostingStore, BatchCostStore, ProfitabilityStore],
controllers: [
ProfitabilityController,
MaterialCostRatesController,
ProductionCostController,
PackagingCostController,

View File

@ -0,0 +1,25 @@
import { Controller, Get, Param, ParseUUIDPipe, Query } from '@nestjs/common';
import {
CurrentPrincipal,
RequirePermission,
} from '../identity/access.decorator';
import type { Principal } from '../identity/identity.types';
import { SchemaPipe } from '../common/validation.pipe';
import {
contributionQuerySchema,
type ContributionQuery,
} from './profitability.schemas';
import { ProfitabilityStore } from './profitability.store';
@Controller('profitability/batches')
@RequirePermission('profitability.read')
export class ProfitabilityController {
constructor(private readonly profitability: ProfitabilityStore) {}
@Get(':batchId')
batch(
@CurrentPrincipal() actor: Principal,
@Param('batchId', ParseUUIDPipe) batchId: string,
@Query(new SchemaPipe(contributionQuerySchema)) query: ContributionQuery,
) {
return this.profitability.batch(actor, batchId, query);
}
}

View File

@ -0,0 +1,8 @@
import { z } from 'zod';
import { costQuerySchema } from './costing.schemas';
export const contributionQuerySchema = costQuerySchema
.extend({
unitNetPrice: z.string().regex(/^(0|[1-9]\d{0,9})\.\d{2}$/),
})
.strict();
export type ContributionQuery = z.infer<typeof contributionQuerySchema>;

View File

@ -0,0 +1,67 @@
import { Injectable } from '@nestjs/common';
import { AccessStore } from '../identity/access.store';
import type { Principal } from '../identity/identity.types';
import { AppError } from '../common/errors/app-error';
import { materialContribution } from './contribution-math';
import type { ContributionQuery } from './profitability.schemas';
@Injectable()
export class ProfitabilityStore {
constructor(private readonly access: AccessStore) {}
batch(actor: Principal, batchId: string, query: ContributionQuery) {
return this.access.mutate(
actor,
'profitability.read',
async (tx) => {
const snapshot = await tx.batchCostSnapshot.findFirst({
where: {
batchId,
organizationId: actor.organizationId,
sealedAt: { not: null },
batch: { status: 'COMPLETED' },
},
select: {
id: true,
batchId: true,
currency: true,
goodQuantity: true,
productionTotal: true,
packagingTotal: true,
total: true,
sealedAt: true,
batch: { select: { bom: { select: { variantId: true } } } },
},
});
if (!snapshot) throw new AppError('BATCH_COST_NOT_FOUND');
if (snapshot.currency !== query.currency)
throw new AppError('PROFITABILITY_CURRENCY');
return {
batchId,
variantId: snapshot.batch.bom.variantId,
costSnapshotId: snapshot.id,
sealedAt: snapshot.sealedAt,
basis: 'SEALED_BATCH_STANDARD_MATERIAL_COST',
currency: snapshot.currency,
goodQuantity: snapshot.goodQuantity,
unitNetPrice: query.unitNetPrice,
productionCost: snapshot.productionTotal.toFixed(2),
packagingCost: snapshot.packagingTotal.toFixed(2),
standardMaterialCost: snapshot.total.toFixed(2),
...materialContribution(
snapshot.total.toFixed(2),
snapshot.goodQuantity,
query.unitNetPrice,
),
excludedCostCategories: [
'LABOUR',
'OVERHEAD',
'FULFILLMENT',
'CHANNEL_FEES',
'MARKETING',
'FINANCE',
],
};
},
false,
);
}
}

View File

@ -1,4 +1,5 @@
export const PERMISSIONS = [
'profitability.read',
'accounting.read',
'forecasts.read',
'analytics.read',

View File

@ -0,0 +1,164 @@
import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { secondActor } from './helpers/commerce';
import {
prepareCostBatch,
startCostBatch,
recordCostUsage,
completeCostBatch,
packageCostBatch,
setCostRate,
} from './helpers/batch-cost';
describe('indicative batch material contribution', () => {
let ctx: IdentityApp;
beforeAll(async () => {
ctx = await identityApp();
});
afterAll(async () => {
await ctx.close();
});
beforeEach(async () => {
await ctx.clearLimits();
});
const report = (
id: string,
unitNetPrice = '5.00',
currency = 'INR',
token = ctx.token,
) =>
ctx
.api()
.get('/api/v1/profitability/batches/' + id)
.auth(token, { type: 'bearer' })
.query({ unitNetPrice, currency });
async function ready(good = 20) {
const batch = await prepareCostBatch(ctx);
await startCostBatch(ctx, batch.batchId);
await recordCostUsage(
ctx,
batch.batchId,
batch.productionLineId,
'CONSUMED',
'200.000',
);
await recordCostUsage(
ctx,
batch.batchId,
batch.productionLineId,
'WASTED',
'10.000',
);
await completeCostBatch(ctx, batch.batchId, good);
if (good)
await packageCostBatch(
ctx,
batch.batchId,
batch.packagingBomId,
batch.packagingLineId,
);
await setCostRate(ctx, batch.productionMaterialId, '0.1000');
await setCostRate(ctx, batch.packagingMaterialId, '2.0000');
const snapshot = await ctx
.api()
.post('/api/v1/production-batches/' + batch.batchId + '/cost-snapshot')
.auth(ctx.token, { type: 'bearer' })
.send({ currency: 'INR', idempotencyKey: randomUUID() })
.expect(201);
return { ...batch, snapshot: snapshot.body };
}
it('compares an explicit price with sealed costs and preserves frozen rates', async () => {
const f = await ready();
const result = await report(f.batchId).expect(200);
expect(result.body).toMatchObject({
batchId: f.batchId,
variantId: f.variantId,
costSnapshotId: f.snapshot.id,
basis: 'SEALED_BATCH_STANDARD_MATERIAL_COST',
currency: 'INR',
goodQuantity: 20,
unitNetPrice: '5.00',
productionCost: '21.00',
packagingCost: '40.00',
standardMaterialCost: '61.00',
comparisonNetValue: '100.00',
materialContribution: '39.00',
contributionRateBps: '3900',
breakEvenUnitNetPrice: '3.05',
comparisonState: 'ABOVE_MATERIAL_BREAK_EVEN',
});
expect(JSON.stringify(result.body)).not.toMatch(
/createdById|idempotencyKey|requestHash|revenue|netProfit/,
);
await setCostRate(ctx, f.productionMaterialId, '9.0000');
await ctx.db.productVariant.update({
where: { id: f.variantId },
data: { price: '999.00' },
});
const after = await report(f.batchId).expect(200);
expect(after.body.standardMaterialCost).toBe('61.00');
expect(after.body.materialContribution).toBe('39.00');
expect((await report(f.batchId, '1.00').expect(200)).body).toMatchObject({
comparisonNetValue: '20.00',
materialContribution: '-41.00',
contributionRateBps: '-20500',
comparisonState: 'BELOW_MATERIAL_BREAK_EVEN',
});
expect((await report(f.batchId, '3.05').expect(200)).body).toMatchObject({
materialContribution: '0.00',
contributionRateBps: '0',
comparisonState: 'AT_MATERIAL_BREAK_EVEN',
});
expect((await report(f.batchId, '0.00').expect(200)).body).toMatchObject({
materialContribution: '-61.00',
contributionRateBps: null,
});
});
it('reports zero good output without dividing by zero', async () => {
const f = await ready(0);
const result = await report(f.batchId).expect(200);
expect(result.body).toMatchObject({
goodQuantity: 0,
comparisonNetValue: '0.00',
standardMaterialCost: '21.00',
materialContribution: '-21.00',
breakEvenUnitNetPrice: null,
contributionRateBps: null,
comparisonState: 'NO_GOOD_OUTPUT',
});
});
it('requires sealed evidence, matching currency and scoped profitability permission', async () => {
const f = await prepareCostBatch(ctx);
await report(f.batchId).expect(404);
await report(randomUUID()).expect(404);
const readyBatch = await ready();
expect(
(await report(readyBatch.batchId, '5.00', 'USD').expect(409)).body.code,
).toBe('PROFITABILITY_CURRENCY');
const reader = await secondActor(ctx, true, ['profitability.read']);
await report(readyBatch.batchId, '5.00', 'INR', reader.token).expect(200);
const costReader = await secondActor(ctx, true, ['cost.read']);
await report(readyBatch.batchId, '5.00', 'INR', costReader.token).expect(
403,
);
const foreign = await secondActor(ctx, false, ['profitability.read']);
await report(readyBatch.batchId, '5.00', 'INR', foreign.token).expect(404);
await ctx
.api()
.get('/api/v1/profitability/batches/' + readyBatch.batchId)
.query({ currency: 'INR', unitNetPrice: '5.00' })
.expect(401);
for (const price of ['-1.00', '1.001', '1', '10000000000.00', 'NaN'])
await report(readyBatch.batchId, price).expect(400);
await ctx
.api()
.get('/api/v1/profitability/batches/' + readyBatch.batchId)
.auth(ctx.token, { type: 'bearer' })
.query({
currency: 'INR',
unitNetPrice: '5.00',
organizationId: foreign.organizationId,
})
.expect(400);
});
});

View File

@ -0,0 +1,42 @@
import { materialContribution } from '../src/costing/contribution-math';
import { contributionQuerySchema } from '../src/costing/profitability.schemas';
it('uses exact signed money, ceiling break-even and zero-denominator handling', () => {
expect(materialContribution('0.19', 2, '0.09')).toMatchObject({
materialContribution: '-0.01',
breakEvenUnitNetPrice: '0.10',
contributionRateBps: '-556',
});
expect(materialContribution('0.19', 2, '0.10')).toMatchObject({
materialContribution: '0.01',
contributionRateBps: '500',
});
expect(materialContribution('61.00', 20, '0.00')).toMatchObject({
comparisonNetValue: '0.00',
materialContribution: '-61.00',
contributionRateBps: null,
});
expect(materialContribution('21.00', 0, '5.00')).toMatchObject({
comparisonState: 'NO_GOOD_OUTPUT',
breakEvenUnitNetPrice: null,
contributionRateBps: null,
});
expect(
materialContribution('0.01', 1000000, '9999999999.99').comparisonNetValue,
).toBe('9999999999990000.00');
expect(() => materialContribution('1.00', -1, '1.00')).toThrow();
expect(() => materialContribution('1.00', 1.5, '1.00')).toThrow();
});
it('validates supported currencies and explicit bounded net-price strings', () => {
expect(
contributionQuerySchema.safeParse({ currency: 'INR', unitNetPrice: '0.00' })
.success,
).toBe(true);
for (const price of ['-1.00', '1', '01.00', '0.001', '10000000000.00'])
expect(
contributionQuerySchema.safeParse({
currency: 'INR',
unitNetPrice: price,
}).success,
).toBe(false);
});