feat(b2b): record partial partner order payments
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details

This commit is contained in:
mihir 2026-10-03 19:00:34 +05:30
parent c00f93bb77
commit 60ccbc92a1
23 changed files with 1027 additions and 94 deletions

View File

@ -63,3 +63,4 @@ B2B credit proposals and independent review: see [Phase 3D API guide](docs/b2b-c
B2B sample requests, review, and dispatch records: see [Phase 3E API guide](docs/b2b-samples-api.md).
B2B branding and artwork approvals: see [Phase 3F API guide](docs/b2b-artwork-api.md).
B2B partner purchase orders: see [Phase 3G API guide](docs/b2b-partner-orders-api.md).
B2B partner partial payments: see [Phase 3H API guide](docs/b2b-partner-payments-api.md).

View File

@ -23,3 +23,5 @@ Create example:
The partner reference is required and unique within the business account; `note` may be omitted or null. One quotation can produce only one order. An identical retry returns the existing order, while reuse of an idempotency key for different content returns a distinct 409 error. A cancellation body is `{ "reason": "Partner withdrew purchase order", "idempotencyKey": "<uuid>" }`. Cancellation is append-only and changes the computed response status from `RECEIVED` to `CANCELLED`; an identical retry returns the current order.
These are **merchandise-only** purchase-order records. Recording one does not reserve inventory, schedule production or delivery, calculate tax or shipping, charge a payment method, or draw on a credit policy. The order number and its snapshot can be used as stable inputs to later fulfillment and receivables workflows. Those workflows must explicitly validate a non-cancelled order and define their own financial and stock transitions.
Phase 3H adds [manual partial payment records](b2b-partner-payments-api.md). Cancellation now requires reversing any active receipt first.

View File

@ -0,0 +1,28 @@
# B2B partner partial payments (Phase 3H)
Staff can record externally received payments against a partner purchase order. The order's frozen `merchandiseTotal` and `currency` are the balance basis. These are manual receipt records: this API does not call a gateway, capture money, issue tax invoices, calculate shipping, or consume credit. Staff must verify the external receipt before recording it. A reversal corrects an erroneous record; it does not send a refund.
All paths are under `/api/v1/b2b/partner-orders/:orderId/payments` and require a bearer session. Access is organization scoped.
| Method | Suffix | Permission | Purpose |
| ------ | --------------------- | -------------------- | ---------------------------------------------------------------------------- |
| GET | `/` | `b2b.payment.read` | List records and exact paid/outstanding totals; accepts `limit` and `offset` |
| GET | `/:paymentId` | `b2b.payment.read` | Read one record and its optional reversal |
| POST | `/` | `b2b.payment.manage` | Record an external receipt |
| POST | `/:paymentId/reverse` | `b2b.payment.manage` | Append one reasoned reversal |
Example receipt:
```json
{
"idempotencyKey": "901a9906-cec5-4eaa-b6d5-d6ac7e23c6d2",
"reference": "UTR-123456",
"method": "BANK_TRANSFER",
"amount": "100.25",
"receivedOn": "2026-10-03"
}
```
`amount` must be positive, have exactly two decimal places, and fit the remaining order balance. Methods are `BANK_TRANSFER`, `UPI`, `CHEQUE`, `CASH`, or `OTHER`. The server normalizes the reference to uppercase and requires it to be unique across the organization, including reversed records. A retry with the same key and payload returns the original record; a changed payload returns a specific 409 error. The list reports `merchandiseTotal`, `paidTotal`, and `outstandingTotal` as two-decimal strings and includes reversed records for audit, but excludes their amounts from the paid total.
To reverse, send `{ "reason": "Recorded against the wrong bank entry", "idempotencyKey": "<uuid>" }`. Reversals are append-only and idempotent. An order with an active receipt cannot be cancelled; reverse all receipts first. A cancelled order cannot accept new receipts. Database guards enforce these balance and cancellation rules even for writes outside the API. Credit exposure, refunds, fulfillment, tax, and freight remain separate milestones.

View File

@ -45,6 +45,7 @@ Business verification, price lists, MOQ, quotations, credit policies, samples, b
- 3E (implemented): verified-account sample requests with immutable variant snapshots, independent review, and auditable manual dispatch references. Stock deduction, carrier integration, and sample billing remain later milestones.
- 3F (implemented): verified-account branding/artwork projects with private PostgreSQL file versions, independent per-version review, restricted downloads, and immutable approval history. Trademark clearance, malware scanning, and production linkage remain separate work.
- 3G (implemented): partner purchase orders captured from accepted, unexpired quotations with immutable merchandise snapshots, idempotent creation, unique partner references, and auditable cancellation. Fulfillment, stock reservation, tax, shipping, payments, and credit utilization remain separate milestones.
- 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.
## Phase 4: Growth channels

View File

@ -39,5 +39,6 @@
"20261001124700_b2b_credit_policies": "a831dc4568c19d8856be27dcb60ae4a7f8155dbeeb797cec2c2dd9f80b392837",
"20261001234900_b2b_sample_requests": "f4fb334341d996188dbea3fb85dbe5166bffd35bc8872f2c8404b6458bc7c142",
"20261003000100_b2b_artwork_approvals": "1359390fc3692bdc2dea8a4cc12223d97c7c15b0cdd2181b082b5e5acbe33677",
"20261003151400_b2b_partner_orders": "ffbba39ed98a16c122b0756a97d721adde9268904f9a7d9770407f341ef848ba"
"20261003151400_b2b_partner_orders": "ffbba39ed98a16c122b0756a97d721adde9268904f9a7d9770407f341ef848ba",
"20261003183000_b2b_partner_payments": "bc43c5a713c62aa201affa2f2595156a2fc68882774504cdf12ac4cf0f641452"
}

View File

@ -0,0 +1,86 @@
CREATE TABLE "b2b_partner_payments" (
"id" UUID NOT NULL PRIMARY KEY,
"organization_id" UUID NOT NULL,
"order_id" UUID NOT NULL,
"recorded_by_id" UUID NOT NULL,
"reference" VARCHAR(80) NOT NULL,
"method" VARCHAR(20) NOT NULL,
"currency" CHAR(3) NOT NULL,
"amount" DECIMAL(18,2) NOT NULL,
"received_on" DATE NOT NULL,
"idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "b2b_partner_payments_amount" CHECK ("amount" > 0),
CONSTRAINT "b2b_partner_payments_reference" CHECK ("reference" ~ '^[A-Z0-9][A-Z0-9._/-]{0,79}$'),
CONSTRAINT "b2b_partner_payments_method" CHECK ("method" IN ('BANK_TRANSFER', 'UPI', 'CHEQUE', 'CASH', 'OTHER')),
CONSTRAINT "b2b_partner_payments_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$')
);
CREATE UNIQUE INDEX "b2b_partner_payments_id_organization_id_key" ON "b2b_partner_payments"("id", "organization_id");
CREATE UNIQUE INDEX "b2b_partner_payments_organization_id_idempotency_key_key" ON "b2b_partner_payments"("organization_id", "idempotency_key");
CREATE UNIQUE INDEX "b2b_partner_payments_organization_id_reference_key" ON "b2b_partner_payments"("organization_id", "reference");
CREATE INDEX "b2b_partner_payments_organization_id_order_id_created_at_id_idx" ON "b2b_partner_payments"("organization_id", "order_id", "created_at", "id");
ALTER TABLE "b2b_partner_payments" ADD CONSTRAINT "b2b_partner_payments_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_partner_payments" ADD CONSTRAINT "b2b_partner_payments_order_id_organization_id_fkey" FOREIGN KEY ("order_id", "organization_id") REFERENCES "b2b_partner_orders"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_partner_payments" ADD CONSTRAINT "b2b_partner_payments_recorded_by_id_organization_id_fkey" FOREIGN KEY ("recorded_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "b2b_partner_payment_reversals" (
"payment_id" UUID NOT NULL PRIMARY KEY,
"organization_id" UUID NOT NULL,
"reversed_by_id" UUID NOT NULL,
"reason" VARCHAR(500) NOT NULL,
"idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "b2b_partner_payment_reversals_reason" CHECK (char_length(btrim("reason")) BETWEEN 3 AND 500),
CONSTRAINT "b2b_partner_payment_reversals_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$')
);
CREATE UNIQUE INDEX "b2b_partner_payment_reversals_payment_id_organization_id_key" ON "b2b_partner_payment_reversals"("payment_id", "organization_id");
CREATE UNIQUE INDEX "b2b_partner_payment_reversals_organization_id_idempotency_k_key" ON "b2b_partner_payment_reversals"("organization_id", "idempotency_key");
ALTER TABLE "b2b_partner_payment_reversals" ADD CONSTRAINT "b2b_partner_payment_reversals_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_partner_payment_reversals" ADD CONSTRAINT "b2b_partner_payment_reversals_payment_id_organization_id_fkey" FOREIGN KEY ("payment_id", "organization_id") REFERENCES "b2b_partner_payments"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_partner_payment_reversals" ADD CONSTRAINT "b2b_partner_payment_reversals_reversed_by_id_organization__fkey" FOREIGN KEY ("reversed_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE FUNCTION guard_b2b_partner_payment() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE source_order b2b_partner_orders%ROWTYPE; already_paid DECIMAL(18,2);
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Partner payment records are immutable'; END IF;
SELECT * INTO source_order FROM b2b_partner_orders
WHERE id = NEW.order_id AND organization_id = NEW.organization_id FOR UPDATE;
IF source_order.id IS NULL THEN RAISE EXCEPTION 'Partner order not found for payment'; END IF;
IF EXISTS (SELECT 1 FROM b2b_partner_order_cancellations
WHERE order_id = NEW.order_id AND organization_id = NEW.organization_id)
THEN RAISE EXCEPTION 'Cancelled partner order cannot receive payment'; END IF;
IF NEW.currency <> source_order.currency THEN RAISE EXCEPTION 'Partner payment currency mismatch'; END IF;
SELECT COALESCE(SUM(p.amount), 0) INTO already_paid FROM b2b_partner_payments p
WHERE p.order_id = NEW.order_id AND p.organization_id = NEW.organization_id
AND NOT EXISTS (SELECT 1 FROM b2b_partner_payment_reversals r WHERE r.payment_id = p.id);
IF already_paid + NEW.amount > source_order.merchandise_total
THEN RAISE EXCEPTION 'Partner payment exceeds merchandise total'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER b2b_partner_payments_guard BEFORE INSERT OR UPDATE OR DELETE ON b2b_partner_payments
FOR EACH ROW EXECUTE FUNCTION guard_b2b_partner_payment();
CREATE FUNCTION reject_b2b_partner_payment_reversal_mutation() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'Partner payment reversals are immutable'; END;
$$;
CREATE TRIGGER b2b_partner_payment_reversals_guard BEFORE UPDATE OR DELETE ON b2b_partner_payment_reversals
FOR EACH ROW EXECUTE FUNCTION reject_b2b_partner_payment_reversal_mutation();
CREATE FUNCTION guard_b2b_partner_order_cancellation_payment() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
PERFORM id FROM b2b_partner_orders WHERE id = NEW.order_id AND organization_id = NEW.organization_id FOR UPDATE;
IF EXISTS (SELECT 1 FROM b2b_partner_payments p
WHERE p.order_id = NEW.order_id AND p.organization_id = NEW.organization_id
AND NOT EXISTS (SELECT 1 FROM b2b_partner_payment_reversals r WHERE r.payment_id = p.id))
THEN RAISE EXCEPTION 'Partner order with active payment cannot be cancelled'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER b2b_partner_order_cancellations_payment_guard BEFORE INSERT ON b2b_partner_order_cancellations
FOR EACH ROW EXECUTE FUNCTION guard_b2b_partner_order_cancellation_payment();
UPDATE "roles" SET "permissions" = ARRAY(SELECT DISTINCT unnest("permissions" || ARRAY['b2b.payment.read', 'b2b.payment.manage']))
WHERE "is_system" = true AND "name" = 'Owner';

View File

@ -19,6 +19,7 @@ model B2bPartnerOrder {
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
lines B2bPartnerOrderLine[]
cancellation B2bPartnerOrderCancellation?
payments B2bPartnerPayment[]
@@unique([id, organizationId])
@@unique([organizationId, number])
@@unique([quoteId, organizationId])
@ -62,3 +63,43 @@ model B2bPartnerOrderCancellation {
@@unique([organizationId, idempotencyKey])
@@map("b2b_partner_order_cancellations")
}
model B2bPartnerPayment {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
orderId String @map("order_id") @db.Uuid
recordedById String @map("recorded_by_id") @db.Uuid
reference String @db.VarChar(80)
method String @db.VarChar(20)
currency String @db.Char(3)
amount Decimal @db.Decimal(18,2)
receivedOn DateTime @map("received_on") @db.Date
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
order B2bPartnerOrder @relation(fields: [orderId, organizationId], references: [id, organizationId], onDelete: Restrict)
recordedBy User @relation(fields: [recordedById, organizationId], references: [id, organizationId], onDelete: Restrict)
reversal B2bPartnerPaymentReversal?
@@unique([id, organizationId])
@@unique([organizationId, idempotencyKey])
@@unique([organizationId, reference])
@@index([organizationId, orderId, createdAt, id])
@@map("b2b_partner_payments")
}
model B2bPartnerPaymentReversal {
paymentId String @id @map("payment_id") @db.Uuid
organizationId String @map("organization_id") @db.Uuid
reversedById String @map("reversed_by_id") @db.Uuid
reason String @db.VarChar(500)
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
payment B2bPartnerPayment @relation(fields: [paymentId, organizationId], references: [id, organizationId], onDelete: Restrict)
reversedBy User @relation(fields: [reversedById, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([paymentId, organizationId])
@@unique([organizationId, idempotencyKey])
@@map("b2b_partner_payment_reversals")
}

View File

@ -68,6 +68,8 @@ model Organization {
b2bPartnerOrders B2bPartnerOrder[]
b2bPartnerOrderLines B2bPartnerOrderLine[]
b2bPartnerOrderCancellations B2bPartnerOrderCancellation[]
b2bPartnerPayments B2bPartnerPayment[]
b2bPartnerPaymentReversals B2bPartnerPaymentReversal[]
@@map("organizations")
}
model User {
@ -123,6 +125,8 @@ model User {
b2bArtworkDecisions B2bArtworkDecision[]
b2bPartnerOrders B2bPartnerOrder[]
b2bPartnerOrderCancellations B2bPartnerOrderCancellation[]
b2bPartnerPayments B2bPartnerPayment[]
b2bPartnerPaymentReversals B2bPartnerPaymentReversal[]
stockEntries StockLedger[]
stockReservations StockReservation[]
carts Cart[]

View File

@ -26,6 +26,9 @@ import { ArtworkReviewStore } from './artwork-review.store';
import { PartnerOrdersController } from './partner-orders.controller';
import { PartnerOrderStore } from './partner-order.store';
import { PartnerOrderCancelStore } from './partner-order-cancel.store';
import { PartnerPaymentsController } from './partner-payments.controller';
import { PartnerPaymentReadStore } from './partner-payment-read.store';
import { PartnerPaymentWriteStore } from './partner-payment-write.store';
@Module({
imports: [DatabaseModule, IdentityModule],
@ -39,6 +42,7 @@ import { PartnerOrderCancelStore } from './partner-order-cancel.store';
ArtworksController,
ArtworkVersionsController,
PartnerOrdersController,
PartnerPaymentsController,
],
providers: [
BusinessStore,
@ -55,6 +59,8 @@ import { PartnerOrderCancelStore } from './partner-order-cancel.store';
ArtworkReviewStore,
PartnerOrderStore,
PartnerOrderCancelStore,
PartnerPaymentReadStore,
PartnerPaymentWriteStore,
],
})
export class B2bModule {}

View File

@ -6,6 +6,7 @@ import { recordAudit } from '../identity/audit';
import type { Principal } from '../identity/identity.types';
import { presentPartnerOrder, requirePartnerOrder } from './partner-order-view';
import type { CancelPartnerOrderInput } from './partner-order.schemas';
import { activePartnerPayments } from './partner-payment-balance';
@Injectable()
export class PartnerOrderCancelStore {
@ -29,6 +30,12 @@ export class PartnerOrderCancelStore {
return presentPartnerOrder(order);
}
if (order.cancellation) throw new AppError('B2B_ORDER_ALREADY_CANCELLED');
if (
await tx.b2bPartnerPayment.count({
where: activePartnerPayments(actor.organizationId, id),
})
)
throw new AppError('B2B_PAYMENT_CANCEL_BLOCKED');
await tx.b2bPartnerOrderCancellation.create({
data: {
orderId: id,

View File

@ -0,0 +1,30 @@
import { AppError } from '../common/errors/app-error';
import { Prisma } from '../generated/prisma/client';
export const activePartnerPayments = (
organizationId: string,
orderId: string,
) => ({
organizationId,
orderId,
reversal: { is: null },
});
export function partnerPaymentBalance(total: string, paid: string) {
const outstanding = new Prisma.Decimal(total).sub(paid);
if (outstanding.isNegative())
throw new AppError('B2B_PAYMENT_BALANCE_INVALID');
return {
paidTotal: new Prisma.Decimal(paid).toFixed(2),
outstandingTotal: outstanding.toFixed(2),
};
}
export function assertPartnerPaymentFits(
total: string,
paid: string,
amount: string,
) {
if (new Prisma.Decimal(paid).add(amount).greaterThan(total))
throw new AppError('B2B_PAYMENT_AMOUNT_LIMIT');
}

View File

@ -0,0 +1,59 @@
import { Injectable } from '@nestjs/common';
import { AppError } from '../common/errors/app-error';
import { DatabaseService } from '../database/database.service';
import type { PageInput } from '../identity/identity.schemas';
import type { Principal } from '../identity/identity.types';
import {
activePartnerPayments,
partnerPaymentBalance,
} from './partner-payment-balance';
import {
partnerPaymentInclude,
presentPartnerPayment,
} from './partner-payment-view';
import { requirePartnerOrder } from './partner-order-view';
@Injectable()
export class PartnerPaymentReadStore {
constructor(private readonly db: DatabaseService) {}
async list(actor: Principal, orderId: string, query: PageInput) {
const order = await requirePartnerOrder(
this.db,
actor.organizationId,
orderId,
);
const [sum, payments] = await Promise.all([
this.db.b2bPartnerPayment.aggregate({
where: activePartnerPayments(actor.organizationId, orderId),
_sum: { amount: true },
}),
this.db.b2bPartnerPayment.findMany({
where: { organizationId: actor.organizationId, orderId },
include: partnerPaymentInclude,
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
take: query.limit,
skip: query.offset,
}),
]);
return {
orderId,
currency: order.currency,
merchandiseTotal: order.merchandiseTotal.toFixed(2),
...partnerPaymentBalance(
order.merchandiseTotal.toFixed(2),
sum._sum.amount?.toFixed(2) ?? '0.00',
),
payments: payments.map(presentPartnerPayment),
};
}
async get(actor: Principal, orderId: string, id: string) {
const payment = await this.db.b2bPartnerPayment.findFirst({
where: { id, orderId, organizationId: actor.organizationId },
include: partnerPaymentInclude,
});
if (!payment) throw new AppError('B2B_PAYMENT_NOT_FOUND');
return presentPartnerPayment(payment);
}
}

View File

@ -0,0 +1,14 @@
import type {
B2bPartnerPayment,
B2bPartnerPaymentReversal,
} from '../generated/prisma/client';
export const partnerPaymentInclude = { reversal: true };
export function presentPartnerPayment(
payment: B2bPartnerPayment & {
reversal: B2bPartnerPaymentReversal | null;
},
) {
return { ...payment, amount: payment.amount.toFixed(2) };
}

View File

@ -0,0 +1,149 @@
import { Injectable } from '@nestjs/common';
import { AppError } from '../common/errors/app-error';
import { commandHash } from '../common/idempotency';
import { AccessStore } from '../identity/access.store';
import { recordAudit } from '../identity/audit';
import type { Principal } from '../identity/identity.types';
import {
activePartnerPayments,
assertPartnerPaymentFits,
} from './partner-payment-balance';
import {
partnerPaymentInclude,
presentPartnerPayment,
} from './partner-payment-view';
import type {
RecordPartnerPaymentInput,
ReversePartnerPaymentInput,
} from './partner-payment.schemas';
import { requirePartnerOrder } from './partner-order-view';
@Injectable()
export class PartnerPaymentWriteStore {
constructor(private readonly access: AccessStore) {}
record(actor: Principal, orderId: string, input: RecordPartnerPaymentInput) {
const hash = commandHash(
orderId,
input.reference,
input.method,
input.amount,
input.receivedOn.toISOString().slice(0, 10),
);
return this.access.mutate(actor, 'b2b.payment.manage', async (tx) => {
const replay = await tx.b2bPartnerPayment.findUnique({
where: {
organizationId_idempotencyKey: {
organizationId: actor.organizationId,
idempotencyKey: input.idempotencyKey,
},
},
include: partnerPaymentInclude,
});
if (replay) {
if (replay.requestHash !== hash)
throw new AppError('B2B_PAYMENT_REPLAY_CONFLICT');
return presentPartnerPayment(replay);
}
const order = await requirePartnerOrder(
tx,
actor.organizationId,
orderId,
);
if (order.cancellation) throw new AppError('B2B_PAYMENT_ORDER_CANCELLED');
const duplicate = await tx.b2bPartnerPayment.findFirst({
where: {
organizationId: actor.organizationId,
reference: input.reference,
},
select: { id: true },
});
if (duplicate) throw new AppError('B2B_PAYMENT_REFERENCE_USED');
const sum = await tx.b2bPartnerPayment.aggregate({
where: activePartnerPayments(actor.organizationId, orderId),
_sum: { amount: true },
});
assertPartnerPaymentFits(
order.merchandiseTotal.toFixed(2),
sum._sum.amount?.toFixed(2) ?? '0.00',
input.amount,
);
const payment = await tx.b2bPartnerPayment.create({
data: {
organizationId: actor.organizationId,
orderId,
recordedById: actor.userId,
reference: input.reference,
method: input.method,
currency: order.currency,
amount: input.amount,
receivedOn: input.receivedOn,
idempotencyKey: input.idempotencyKey,
requestHash: hash,
},
include: partnerPaymentInclude,
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'b2b_payment.recorded',
payment.id,
);
return presentPartnerPayment(payment);
});
}
reverse(
actor: Principal,
orderId: string,
id: string,
input: ReversePartnerPaymentInput,
) {
const hash = commandHash(orderId, id, input.reason);
return this.access.mutate(actor, 'b2b.payment.manage', async (tx) => {
const payment = await tx.b2bPartnerPayment.findFirst({
where: { id, orderId, organizationId: actor.organizationId },
include: partnerPaymentInclude,
});
if (!payment) throw new AppError('B2B_PAYMENT_NOT_FOUND');
const replay = await tx.b2bPartnerPaymentReversal.findUnique({
where: {
organizationId_idempotencyKey: {
organizationId: actor.organizationId,
idempotencyKey: input.idempotencyKey,
},
},
});
if (replay) {
if (replay.requestHash !== hash)
throw new AppError('B2B_PAYMENT_REVERSE_REPLAY_CONFLICT');
return presentPartnerPayment(payment);
}
if (payment.reversal) throw new AppError('B2B_PAYMENT_ALREADY_REVERSED');
await tx.b2bPartnerPaymentReversal.create({
data: {
paymentId: id,
organizationId: actor.organizationId,
reversedById: actor.userId,
reason: input.reason,
idempotencyKey: input.idempotencyKey,
requestHash: hash,
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'b2b_payment.reversed',
id,
);
return presentPartnerPayment(
await tx.b2bPartnerPayment.findUniqueOrThrow({
where: { id },
include: partnerPaymentInclude,
}),
);
});
}
}

View File

@ -0,0 +1,40 @@
import { z } from 'zod';
import { text } from '../common/input';
const reference = z
.string()
.trim()
.min(1)
.max(80)
.regex(/^[A-Za-z0-9][A-Za-z0-9._/-]*$/)
.transform((value) => value.toUpperCase());
const amount = z
.string()
.regex(/^(0|[1-9]\d{0,15})\.\d{2}$/)
.refine((value) => value !== '0.00');
export const recordPartnerPaymentSchema = z
.object({
idempotencyKey: z.uuid(),
reference,
method: z.enum(['BANK_TRANSFER', 'UPI', 'CHEQUE', 'CASH', 'OTHER']),
amount,
receivedOn: z.iso
.date()
.transform((value) => new Date(`${value}T00:00:00.000Z`)),
})
.strict();
export const reversePartnerPaymentSchema = z
.object({
reason: text(500, 3),
idempotencyKey: z.uuid(),
})
.strict();
export type RecordPartnerPaymentInput = z.infer<
typeof recordPartnerPaymentSchema
>;
export type ReversePartnerPaymentInput = z.infer<
typeof reversePartnerPaymentSchema
>;

View File

@ -0,0 +1,75 @@
import {
Body,
Controller,
Get,
Param,
ParseUUIDPipe,
Post,
Query,
} from '@nestjs/common';
import { SchemaPipe } from '../common/validation.pipe';
import {
CurrentPrincipal,
RequirePermission,
} from '../identity/access.decorator';
import { pageSchema, type PageInput } from '../identity/identity.schemas';
import type { Principal } from '../identity/identity.types';
import { PartnerPaymentReadStore } from './partner-payment-read.store';
import { PartnerPaymentWriteStore } from './partner-payment-write.store';
import {
recordPartnerPaymentSchema,
reversePartnerPaymentSchema,
type RecordPartnerPaymentInput,
type ReversePartnerPaymentInput,
} from './partner-payment.schemas';
@Controller('b2b/partner-orders/:orderId/payments')
export class PartnerPaymentsController {
constructor(
private readonly reads: PartnerPaymentReadStore,
private readonly writes: PartnerPaymentWriteStore,
) {}
@Get()
@RequirePermission('b2b.payment.read')
list(
@CurrentPrincipal() actor: Principal,
@Param('orderId', ParseUUIDPipe) orderId: string,
@Query(new SchemaPipe(pageSchema)) query: PageInput,
) {
return this.reads.list(actor, orderId, query);
}
@Post()
@RequirePermission('b2b.payment.manage')
record(
@CurrentPrincipal() actor: Principal,
@Param('orderId', ParseUUIDPipe) orderId: string,
@Body(new SchemaPipe(recordPartnerPaymentSchema))
input: RecordPartnerPaymentInput,
) {
return this.writes.record(actor, orderId, input);
}
@Get(':paymentId')
@RequirePermission('b2b.payment.read')
get(
@CurrentPrincipal() actor: Principal,
@Param('orderId', ParseUUIDPipe) orderId: string,
@Param('paymentId', ParseUUIDPipe) paymentId: string,
) {
return this.reads.get(actor, orderId, paymentId);
}
@Post(':paymentId/reverse')
@RequirePermission('b2b.payment.manage')
reverse(
@CurrentPrincipal() actor: Principal,
@Param('orderId', ParseUUIDPipe) orderId: string,
@Param('paymentId', ParseUUIDPipe) paymentId: string,
@Body(new SchemaPipe(reversePartnerPaymentSchema))
input: ReversePartnerPaymentInput,
) {
return this.writes.reverse(actor, orderId, paymentId, input);
}
}

View File

@ -0,0 +1,47 @@
export const B2B_PAYMENT_ERRORS = {
B2B_PAYMENT_NOT_FOUND: [
404,
'Partner payment not found',
'Scoped partner payment lookup failed',
],
B2B_PAYMENT_ORDER_CANCELLED: [
409,
'Cancelled partner order cannot receive payment',
'Partner payment rejected on cancelled order',
],
B2B_PAYMENT_REFERENCE_USED: [
409,
'Partner receipt reference is already recorded',
'Partner payment external reference collision',
],
B2B_PAYMENT_REPLAY_CONFLICT: [
409,
'Idempotency key was used for a different partner receipt',
'Partner payment create replay payload mismatch',
],
B2B_PAYMENT_AMOUNT_LIMIT: [
409,
'Payment exceeds the partner order balance',
'Partner payment exceeds merchandise total',
],
B2B_PAYMENT_ALREADY_REVERSED: [
409,
'Partner payment is already reversed',
'Partner payment duplicate reversal',
],
B2B_PAYMENT_REVERSE_REPLAY_CONFLICT: [
409,
'Idempotency key was used for a different reversal',
'Partner payment reversal replay payload mismatch',
],
B2B_PAYMENT_BALANCE_INVALID: [
500,
'Partner order balance cannot be calculated',
'Partner payment ledger exceeds order total',
],
B2B_PAYMENT_CANCEL_BLOCKED: [
409,
'Reverse active payments before cancelling the order',
'Partner order cancellation blocked by active receipt',
],
} as const;

View File

@ -9,6 +9,7 @@ import { B2B_CREDIT_ERRORS } from './b2b-credit-errors';
import { B2B_SAMPLE_ERRORS } from './b2b-sample-errors';
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 = {
...PLATFORM_ERRORS,
...COMMERCE_ERRORS,
@ -21,5 +22,6 @@ export const ERRORS = {
...B2B_SAMPLE_ERRORS,
...B2B_ARTWORK_ERRORS,
...B2B_ORDER_ERRORS,
...B2B_PAYMENT_ERRORS,
} as const;
export type ErrorCode = keyof typeof ERRORS;

View File

@ -55,5 +55,7 @@ export const PERMISSIONS = [
'b2b.artwork.review',
'b2b.order.read',
'b2b.order.manage',
'b2b.payment.read',
'b2b.payment.manage',
] as const;
export type Permission = (typeof PERMISSIONS)[number];

View File

@ -1,104 +1,14 @@
import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { secondActor, seedProduct } from './helpers/commerce';
import { secondActor } from './helpers/commerce';
import { seedPartnerQuote } from './helpers/b2b-partner-order';
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 quote = (accepted = true) => seedPartnerQuote(ctx, accepted);
const input = (quoteId: string) => ({
quoteId,
partnerReference: `PO-${randomUUID()}`,

View File

@ -0,0 +1,65 @@
import { randomUUID } from 'node:crypto';
import {
recordPartnerPaymentSchema,
reversePartnerPaymentSchema,
} from '../src/b2b/partner-payment.schemas';
import {
assertPartnerPaymentFits,
partnerPaymentBalance,
} from '../src/b2b/partner-payment-balance';
const valid = () => ({
idempotencyKey: randomUUID(),
reference: ' bank/123 ',
method: 'BANK_TRANSFER',
amount: '100.25',
receivedOn: '2026-10-03',
});
describe('partner payment validation and exact balances', () => {
it('normalizes references and preserves exact cents', () => {
expect(recordPartnerPaymentSchema.parse(valid())).toMatchObject({
reference: 'BANK/123',
amount: '100.25',
});
expect(partnerPaymentBalance('3303.00', '100.25')).toEqual({
paidTotal: '100.25',
outstandingTotal: '3202.75',
});
expect(() =>
assertPartnerPaymentFits('3303.00', '3202.75', '100.25'),
).not.toThrow();
});
it('rejects malformed, negative, zero, and over-limit amounts', () => {
for (const amount of [
'0.00',
'-1.00',
'1',
'1.001',
'01.00',
'99999999999999999.00',
])
expect(
recordPartnerPaymentSchema.safeParse({ ...valid(), amount }).success,
).toBe(false);
expect(() =>
assertPartnerPaymentFits('3303.00', '3202.75', '100.26'),
).toThrow('Payment exceeds the partner order balance');
expect(() => partnerPaymentBalance('10.00', '10.01')).toThrow(
'Partner order balance cannot be calculated',
);
});
it('rejects unknown fields and short reversal reasons', () => {
expect(
recordPartnerPaymentSchema.safeParse({ ...valid(), other: 'x' }).success,
).toBe(false);
expect(
reversePartnerPaymentSchema.safeParse({
reason: 'x',
idempotencyKey: randomUUID(),
}).success,
).toBe(false);
});
});

View File

@ -0,0 +1,251 @@
import { randomUUID } from 'node:crypto';
import { seedPartnerOrder } from './helpers/b2b-partner-order';
import { secondActor } from './helpers/commerce';
import { identityApp, type IdentityApp } from './helpers/identity-app';
describe('B2B partner partial payments', () => {
let ctx: IdentityApp;
const auth = { type: 'bearer' as const };
const payment = (
amount: string,
reference: string = randomUUID(),
idempotencyKey = randomUUID(),
) => ({
amount,
reference,
idempotencyKey,
method: 'BANK_TRANSFER',
receivedOn: '2026-10-03',
});
beforeAll(async () => {
ctx = await identityApp();
}, 60000);
afterAll(async () => {
await ctx?.close();
});
beforeEach(async () => {
await ctx.clearLimits();
});
it('records partial receipts, returns exact balances, and rejects duplicate or excessive payments', async () => {
const { order } = await seedPartnerOrder(ctx);
const url = `/api/v1/b2b/partner-orders/${order.id}/payments`;
const input = payment('100.25', ' bank/123 ');
const first = await ctx
.api()
.post(url)
.auth(ctx.token, auth)
.send(input)
.expect(201);
expect(first.body).toMatchObject({
amount: '100.25',
currency: 'INR',
reference: 'BANK/123',
});
expect(
(await ctx.api().post(url).auth(ctx.token, auth).send(input).expect(201))
.body.id,
).toBe(first.body.id);
expect(
(
await ctx
.api()
.post(url)
.auth(ctx.token, auth)
.send({ ...input, amount: '101.25' })
.expect(409)
).body.code,
).toBe('B2B_PAYMENT_REPLAY_CONFLICT');
expect(
(
await ctx
.api()
.post(url)
.auth(ctx.token, auth)
.send(payment('1.00', 'BANK/123'))
.expect(409)
).body.code,
).toBe('B2B_PAYMENT_REFERENCE_USED');
await ctx
.api()
.post(url)
.auth(ctx.token, auth)
.send(payment('200.00'))
.expect(201);
expect(
(
await ctx
.api()
.post(url)
.auth(ctx.token, auth)
.send(payment('3002.76'))
.expect(409)
).body.code,
).toBe('B2B_PAYMENT_AMOUNT_LIMIT');
const listed = await ctx
.api()
.get(`${url}?limit=1&offset=1`)
.auth(ctx.token, auth)
.expect(200);
expect(listed.body).toMatchObject({
orderId: order.id,
currency: 'INR',
merchandiseTotal: '3303.00',
paidTotal: '300.25',
outstandingTotal: '3002.75',
});
expect(listed.body.payments).toHaveLength(1);
expect(
(
await ctx
.api()
.get(`${url}/${first.body.id}`)
.auth(ctx.token, auth)
.expect(200)
).body.amount,
).toBe('100.25');
expect(
await ctx.db.auditEvent.count({
where: { action: 'b2b_payment.recorded', targetId: first.body.id },
}),
).toBe(1);
});
it('blocks cancellation until active receipts are reversed, preserving a retryable audit trail', async () => {
const { order } = await seedPartnerOrder(ctx);
const url = `/api/v1/b2b/partner-orders/${order.id}/payments`;
const input = payment('100.25');
const recorded = await ctx
.api()
.post(url)
.auth(ctx.token, auth)
.send(input)
.expect(201);
const cancelUrl = `/api/v1/b2b/partner-orders/${order.id}/cancel`;
expect(
(
await ctx
.api()
.post(cancelUrl)
.auth(ctx.token, auth)
.send({
reason: 'Partner withdrew order',
idempotencyKey: randomUUID(),
})
.expect(409)
).body.code,
).toBe('B2B_PAYMENT_CANCEL_BLOCKED');
const reverseUrl = `${url}/${recorded.body.id}/reverse`;
const reversal = {
reason: 'Bank entry was recorded in error',
idempotencyKey: randomUUID(),
};
const reversed = await ctx
.api()
.post(reverseUrl)
.auth(ctx.token, auth)
.send(reversal)
.expect(201);
expect(reversed.body.reversal.reason).toBe(reversal.reason);
expect(
(
await ctx
.api()
.post(reverseUrl)
.auth(ctx.token, auth)
.send(reversal)
.expect(201)
).body.reversal.paymentId,
).toBe(recorded.body.id);
expect(
(
await ctx
.api()
.post(reverseUrl)
.auth(ctx.token, auth)
.send({ ...reversal, reason: 'Different reason' })
.expect(409)
).body.code,
).toBe('B2B_PAYMENT_REVERSE_REPLAY_CONFLICT');
expect(
(
await ctx
.api()
.post(reverseUrl)
.auth(ctx.token, auth)
.send({ ...reversal, idempotencyKey: randomUUID() })
.expect(409)
).body.code,
).toBe('B2B_PAYMENT_ALREADY_REVERSED');
expect(
(await ctx.api().get(url).auth(ctx.token, auth).expect(200)).body,
).toMatchObject({ paidTotal: '0.00', outstandingTotal: '3303.00' });
await ctx
.api()
.post(cancelUrl)
.auth(ctx.token, auth)
.send({ reason: 'Partner withdrew order', idempotencyKey: randomUUID() })
.expect(201);
expect(
(
await ctx
.api()
.post(url)
.auth(ctx.token, auth)
.send(payment('1.00'))
.expect(409)
).body.code,
).toBe('B2B_PAYMENT_ORDER_CANCELLED');
expect(
await ctx.db.auditEvent.count({
where: { action: 'b2b_payment.reversed', targetId: recorded.body.id },
}),
).toBe(1);
});
it('requires scoped read and manage permissions', async () => {
const { order } = await seedPartnerOrder(ctx);
const url = `/api/v1/b2b/partner-orders/${order.id}/payments`;
const outsider = await secondActor(ctx, false, [
'b2b.payment.read',
'b2b.payment.manage',
]);
expect(
(await ctx.api().get(url).auth(outsider.token, auth).expect(404)).body
.code,
).toBe('B2B_ORDER_NOT_FOUND');
const noAccess = await secondActor(ctx);
await ctx.api().get(url).auth(noAccess.token, auth).expect(403);
await ctx
.api()
.post(url)
.auth(noAccess.token, auth)
.send(payment('1.00'))
.expect(403);
const readOnly = await secondActor(ctx, true, ['b2b.payment.read']);
await ctx.api().get(url).auth(readOnly.token, auth).expect(200);
await ctx
.api()
.post(url)
.auth(readOnly.token, auth)
.send(payment('1.00'))
.expect(403);
});
it('serializes competing receipts so only one can use the remaining balance', async () => {
const { order } = await seedPartnerOrder(ctx);
const url = `/api/v1/b2b/partner-orders/${order.id}/payments`;
const results = await Promise.all([
ctx.api().post(url).auth(ctx.token, auth).send(payment('2000.00')),
ctx.api().post(url).auth(ctx.token, auth).send(payment('2000.00')),
]);
expect(results.map((result) => result.status).sort()).toEqual([201, 409]);
expect(results.find((result) => result.status === 409)?.body.code).toBe(
'B2B_PAYMENT_AMOUNT_LIMIT',
);
expect(
(await ctx.api().get(url).auth(ctx.token, auth).expect(200)).body,
).toMatchObject({ paidTotal: '2000.00', outstandingTotal: '1303.00' });
});
});

View File

@ -0,0 +1,112 @@
import { randomUUID } from 'node:crypto';
import { secondActor, seedProduct } from './commerce';
import type { IdentityApp } from './identity-app';
const auth = { type: 'bearer' as const };
export async function seedPartnerQuote(ctx: IdentityApp, accepted = true) {
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 accountId = created.body.id as string;
await ctx
.api()
.post(`/api/v1/b2b/accounts/${accountId}/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/${accountId}/decision`)
.auth(reviewer.token, auth)
.send({
decision: 'APPROVED',
note: 'Registration checked',
idempotencyKey: randomUUID(),
})
.expect(201);
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,
};
}
export async function seedPartnerOrder(ctx: IdentityApp) {
const source = await seedPartnerQuote(ctx);
const created = await ctx
.api()
.post('/api/v1/b2b/partner-orders')
.auth(ctx.token, auth)
.send({
quoteId: source.quoteId,
partnerReference: `PO-${randomUUID()}`,
note: 'Requested by purchasing team',
idempotencyKey: randomUUID(),
})
.expect(201);
return {
...source,
order: created.body as { id: string; merchandiseTotal: string },
};
}