Merge pull request 'feat(b2b): add partner purchase orders' (#32) from feat/b2b-partner-orders into main
continuous-integration/drone/push Build is failing Details

Reviewed-on: #32
This commit is contained in:
Mihir Motiyani 2026-10-03 17:01:02 +05:30
commit 5a503c7520
20 changed files with 968 additions and 1 deletions

View File

@ -62,3 +62,4 @@ B2B quotations and response tracking: see [Phase 3C API guide](docs/b2b-quotatio
B2B credit proposals and independent review: see [Phase 3D API guide](docs/b2b-credit-policies-api.md). B2B credit proposals and independent review: see [Phase 3D API guide](docs/b2b-credit-policies-api.md).
B2B sample requests, review, and dispatch records: see [Phase 3E API guide](docs/b2b-samples-api.md). 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 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).

View File

@ -0,0 +1,25 @@
# B2B partner purchase orders (Phase 3G)
All endpoints are under `/api/v1/b2b/partner-orders` and require a bearer session. Staff record a partner purchase order only from an **accepted, unexpired** quotation for a verified business account. The order copies the quotation's account profile snapshot, currency, merchandise total, and every line's variant, SKU, name, quantity, minimum quantity, unit price, and line total. Those records are immutable.
| Method | Path | Permission | Purpose |
| ------ | ------------- | ------------------ | --------------------------------------------- |
| GET | `/` | `b2b.order.read` | List; optional `accountId`, `limit`, `offset` |
| GET | `/:id` | `b2b.order.read` | Read order, lines, and cancellation |
| POST | `/` | `b2b.order.manage` | Record purchase order from a quote |
| POST | `/:id/cancel` | `b2b.order.manage` | Record one reasoned cancellation |
Create example:
```json
{
"quoteId": "b92c23e5-794d-47e7-a7f4-428b84543fa1",
"partnerReference": "CUSTOMER-PO-123",
"note": "Requested by purchasing team",
"idempotencyKey": "10fc5585-34a6-4ead-b5ce-d83418eb50df"
}
```
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.

View File

@ -44,6 +44,7 @@ Business verification, price lists, MOQ, quotations, credit policies, samples, b
- 3D (implemented): staff-proposed credit limits and net terms with independent review, immutable decision history, suspension, and one active policy per business account and currency. Credit exposure, receivables, payment collection, and order enforcement remain later milestones. - 3D (implemented): staff-proposed credit limits and net terms with independent review, immutable decision history, suspension, and one active policy per business account and currency. Credit exposure, receivables, payment collection, and order enforcement remain later milestones.
- 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. - 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. - 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.
## Phase 4: Growth channels ## Phase 4: Growth channels

View File

@ -43,6 +43,7 @@ model BusinessAccount {
creditPolicies B2bCreditPolicy[] creditPolicies B2bCreditPolicy[]
sampleRequests B2bSampleRequest[] sampleRequests B2bSampleRequest[]
artworks B2bArtwork[] artworks B2bArtwork[]
partnerOrders B2bPartnerOrder[]
@@unique([organizationId, code]) @@unique([organizationId, code])
@@unique([organizationId, countryCode, registrationNumber]) @@unique([organizationId, countryCode, registrationNumber])
@@unique([id, organizationId]) @@unique([id, organizationId])
@ -132,6 +133,7 @@ model B2bQuote {
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict) createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
lines B2bQuoteLine[] lines B2bQuoteLine[]
response B2bQuoteResponse? response B2bQuoteResponse?
partnerOrder B2bPartnerOrder?
@@unique([id, organizationId]) @@unique([id, organizationId])
@@unique([organizationId, number]) @@unique([organizationId, number])
@@unique([organizationId, idempotencyKey]) @@unique([organizationId, idempotencyKey])

View File

@ -41,6 +41,7 @@ model ProductVariant {
b2bPriceListItems B2bPriceListItem[] b2bPriceListItems B2bPriceListItem[]
b2bQuoteLines B2bQuoteLine[] b2bQuoteLines B2bQuoteLine[]
b2bSampleRequests B2bSampleRequest[] b2bSampleRequests B2bSampleRequest[]
b2bPartnerOrderLines B2bPartnerOrderLine[]
product Product @relation(fields: [productId, organizationId], references: [id, organizationId], onDelete: Restrict) product Product @relation(fields: [productId, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([organizationId, sku]) @@unique([organizationId, sku])
@@unique([id, organizationId]) @@unique([id, organizationId])

View File

@ -38,5 +38,6 @@
"20260930190500_b2b_quotations": "0497ece6cb035687548773ce265842125fa1a655e5951e8d958290d664f5c3f0", "20260930190500_b2b_quotations": "0497ece6cb035687548773ce265842125fa1a655e5951e8d958290d664f5c3f0",
"20261001124700_b2b_credit_policies": "a831dc4568c19d8856be27dcb60ae4a7f8155dbeeb797cec2c2dd9f80b392837", "20261001124700_b2b_credit_policies": "a831dc4568c19d8856be27dcb60ae4a7f8155dbeeb797cec2c2dd9f80b392837",
"20261001234900_b2b_sample_requests": "f4fb334341d996188dbea3fb85dbe5166bffd35bc8872f2c8404b6458bc7c142", "20261001234900_b2b_sample_requests": "f4fb334341d996188dbea3fb85dbe5166bffd35bc8872f2c8404b6458bc7c142",
"20261003000100_b2b_artwork_approvals": "1359390fc3692bdc2dea8a4cc12223d97c7c15b0cdd2181b082b5e5acbe33677" "20261003000100_b2b_artwork_approvals": "1359390fc3692bdc2dea8a4cc12223d97c7c15b0cdd2181b082b5e5acbe33677",
"20261003151400_b2b_partner_orders": "ffbba39ed98a16c122b0756a97d721adde9268904f9a7d9770407f341ef848ba"
} }

View File

@ -0,0 +1,118 @@
CREATE TABLE "b2b_partner_orders" (
"id" UUID NOT NULL PRIMARY KEY,
"organization_id" UUID NOT NULL,
"account_id" UUID NOT NULL,
"quote_id" UUID NOT NULL,
"created_by_id" UUID NOT NULL,
"number" VARCHAR(24) NOT NULL,
"partner_reference" VARCHAR(80) NOT NULL,
"note" VARCHAR(500),
"account_snapshot" JSONB NOT NULL,
"currency" CHAR(3) NOT NULL,
"merchandise_total" DECIMAL(18,2) 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_orders_number" CHECK ("number" ~ '^BO-[A-F0-9]{20}$'),
CONSTRAINT "b2b_partner_orders_reference" CHECK (char_length(btrim("partner_reference")) BETWEEN 1 AND 80),
CONSTRAINT "b2b_partner_orders_note" CHECK ("note" IS NULL OR char_length(btrim("note")) BETWEEN 3 AND 500),
CONSTRAINT "b2b_partner_orders_total" CHECK ("merchandise_total" > 0),
CONSTRAINT "b2b_partner_orders_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$')
);
CREATE UNIQUE INDEX "b2b_partner_orders_id_organization_id_key" ON "b2b_partner_orders"("id", "organization_id");
CREATE UNIQUE INDEX "b2b_partner_orders_organization_id_number_key" ON "b2b_partner_orders"("organization_id", "number");
CREATE UNIQUE INDEX "b2b_partner_orders_quote_id_organization_id_key" ON "b2b_partner_orders"("quote_id", "organization_id");
CREATE UNIQUE INDEX "b2b_partner_orders_organization_id_account_id_partner_refer_key" ON "b2b_partner_orders"("organization_id", "account_id", "partner_reference");
CREATE UNIQUE INDEX "b2b_partner_orders_organization_id_idempotency_key_key" ON "b2b_partner_orders"("organization_id", "idempotency_key");
CREATE INDEX "b2b_partner_orders_organization_id_account_id_created_at_id_idx" ON "b2b_partner_orders"("organization_id", "account_id", "created_at", "id");
ALTER TABLE "b2b_partner_orders" ADD CONSTRAINT "b2b_partner_orders_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_partner_orders" ADD CONSTRAINT "b2b_partner_orders_account_id_organization_id_fkey" FOREIGN KEY ("account_id", "organization_id") REFERENCES "business_accounts"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_partner_orders" ADD CONSTRAINT "b2b_partner_orders_quote_id_organization_id_fkey" FOREIGN KEY ("quote_id", "organization_id") REFERENCES "b2b_quotes"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_partner_orders" ADD CONSTRAINT "b2b_partner_orders_created_by_id_organization_id_fkey" FOREIGN KEY ("created_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "b2b_partner_order_lines" (
"id" UUID NOT NULL PRIMARY KEY,
"organization_id" UUID NOT NULL,
"order_id" UUID NOT NULL,
"variant_id" UUID NOT NULL,
"sku" VARCHAR(64) NOT NULL,
"name" VARCHAR(160) NOT NULL,
"quantity" INTEGER NOT NULL,
"min_quantity" INTEGER NOT NULL,
"unit_price" DECIMAL(12,2) NOT NULL,
"line_total" DECIMAL(18,2) NOT NULL,
CONSTRAINT "b2b_partner_order_lines_quantity" CHECK ("quantity" BETWEEN 1 AND 1000000 AND "quantity" >= "min_quantity"),
CONSTRAINT "b2b_partner_order_lines_money" CHECK ("unit_price" > 0 AND "line_total" = "unit_price" * "quantity")
);
CREATE UNIQUE INDEX "b2b_partner_order_lines_order_id_variant_id_key" ON "b2b_partner_order_lines"("order_id", "variant_id");
CREATE INDEX "b2b_partner_order_lines_organization_id_order_id_id_idx" ON "b2b_partner_order_lines"("organization_id", "order_id", "id");
ALTER TABLE "b2b_partner_order_lines" ADD CONSTRAINT "b2b_partner_order_lines_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_partner_order_lines" ADD CONSTRAINT "b2b_partner_order_lines_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_order_lines" ADD CONSTRAINT "b2b_partner_order_lines_variant_id_organization_id_fkey" FOREIGN KEY ("variant_id", "organization_id") REFERENCES "product_variants"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "b2b_partner_order_cancellations" (
"order_id" UUID NOT NULL PRIMARY KEY,
"organization_id" UUID NOT NULL,
"actor_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_order_cancellations_reason" CHECK (char_length(btrim("reason")) BETWEEN 3 AND 500),
CONSTRAINT "b2b_partner_order_cancellations_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$')
);
CREATE UNIQUE INDEX "b2b_partner_order_cancellations_order_id_organization_id_key" ON "b2b_partner_order_cancellations"("order_id", "organization_id");
CREATE UNIQUE INDEX "b2b_partner_order_cancellations_organization_id_idempotency_key" ON "b2b_partner_order_cancellations"("organization_id", "idempotency_key");
ALTER TABLE "b2b_partner_order_cancellations" ADD CONSTRAINT "b2b_partner_order_cancellations_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_partner_order_cancellations" ADD CONSTRAINT "b2b_partner_order_cancellations_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_order_cancellations" ADD CONSTRAINT "b2b_partner_order_cancellations_actor_id_organization_id_fkey" FOREIGN KEY ("actor_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE FUNCTION guard_b2b_partner_order() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE source_quote b2b_quotes%ROWTYPE;
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Partner orders are immutable'; END IF;
SELECT * INTO source_quote FROM b2b_quotes WHERE id = NEW.quote_id AND organization_id = NEW.organization_id;
IF source_quote.id IS NULL OR source_quote.account_id <> NEW.account_id
OR source_quote.account_snapshot IS DISTINCT FROM NEW.account_snapshot
OR source_quote.currency <> NEW.currency OR source_quote.merchandise_total <> NEW.merchandise_total
THEN RAISE EXCEPTION 'Partner order must match the accepted quote'; END IF;
IF source_quote.expires_at <= CURRENT_TIMESTAMP OR NOT EXISTS (
SELECT 1 FROM b2b_quote_responses WHERE quote_id = NEW.quote_id AND organization_id = NEW.organization_id AND kind = 'ACCEPTED'
) THEN RAISE EXCEPTION 'Partner order requires an accepted unexpired quote'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER b2b_partner_orders_guard BEFORE INSERT OR UPDATE OR DELETE ON b2b_partner_orders FOR EACH ROW EXECUTE FUNCTION guard_b2b_partner_order();
CREATE FUNCTION guard_b2b_partner_order_line() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE source_line b2b_quote_lines%ROWTYPE; source_quote_id UUID;
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Partner order lines are immutable'; END IF;
SELECT quote_id INTO source_quote_id FROM b2b_partner_orders WHERE id = NEW.order_id AND organization_id = NEW.organization_id;
SELECT * INTO source_line FROM b2b_quote_lines WHERE quote_id = source_quote_id AND variant_id = NEW.variant_id;
IF source_line.id IS NULL OR (NEW.sku, NEW.name, NEW.quantity, NEW.min_quantity, NEW.unit_price, NEW.line_total)
IS DISTINCT FROM (source_line.sku, source_line.name, source_line.quantity, source_line.min_quantity, source_line.unit_price, source_line.line_total)
THEN RAISE EXCEPTION 'Partner order line must match quote line snapshot'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER b2b_partner_order_lines_guard BEFORE INSERT OR UPDATE OR DELETE ON b2b_partner_order_lines FOR EACH ROW EXECUTE FUNCTION guard_b2b_partner_order_line();
CREATE FUNCTION check_b2b_partner_order_total() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF (SELECT COUNT(*) FROM b2b_partner_order_lines WHERE order_id = NEW.id) <> (SELECT COUNT(*) FROM b2b_quote_lines WHERE quote_id = NEW.quote_id)
OR (SELECT SUM(line_total) FROM b2b_partner_order_lines WHERE order_id = NEW.id) <> NEW.merchandise_total
THEN RAISE EXCEPTION 'Partner order lines must match the quote and total'; END IF;
RETURN NEW;
END;
$$;
CREATE CONSTRAINT TRIGGER b2b_partner_orders_total_guard AFTER INSERT ON b2b_partner_orders
DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION check_b2b_partner_order_total();
CREATE FUNCTION reject_b2b_partner_order_mutation() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'Partner order cancellations are immutable'; END;
$$;
CREATE TRIGGER b2b_partner_order_cancellations_guard BEFORE UPDATE OR DELETE ON b2b_partner_order_cancellations FOR EACH ROW EXECUTE FUNCTION reject_b2b_partner_order_mutation();
UPDATE "roles" SET "permissions" = ARRAY(SELECT DISTINCT unnest("permissions" || ARRAY['b2b.order.read', 'b2b.order.manage']))
WHERE "is_system" = true AND "name" = 'Owner';

View File

@ -0,0 +1,64 @@
model B2bPartnerOrder {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
accountId String @map("account_id") @db.Uuid
quoteId String @map("quote_id") @db.Uuid
createdById String @map("created_by_id") @db.Uuid
number String @db.VarChar(24)
partnerReference String @map("partner_reference") @db.VarChar(80)
note String? @db.VarChar(500)
accountSnapshot Json @map("account_snapshot") @db.JsonB
currency String @db.Char(3)
merchandiseTotal Decimal @map("merchandise_total") @db.Decimal(18,2)
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)
account BusinessAccount @relation(fields: [accountId, organizationId], references: [id, organizationId], onDelete: Restrict)
quote B2bQuote @relation(fields: [quoteId, organizationId], references: [id, organizationId], onDelete: Restrict)
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
lines B2bPartnerOrderLine[]
cancellation B2bPartnerOrderCancellation?
@@unique([id, organizationId])
@@unique([organizationId, number])
@@unique([quoteId, organizationId])
@@unique([organizationId, accountId, partnerReference])
@@unique([organizationId, idempotencyKey])
@@index([organizationId, accountId, createdAt, id])
@@map("b2b_partner_orders")
}
model B2bPartnerOrderLine {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
orderId String @map("order_id") @db.Uuid
variantId String @map("variant_id") @db.Uuid
sku String @db.VarChar(64)
name String @db.VarChar(160)
quantity Int
minQuantity Int @map("min_quantity")
unitPrice Decimal @map("unit_price") @db.Decimal(12,2)
lineTotal Decimal @map("line_total") @db.Decimal(18,2)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
order B2bPartnerOrder @relation(fields: [orderId, organizationId], references: [id, organizationId], onDelete: Restrict)
variant ProductVariant @relation(fields: [variantId, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([orderId, variantId])
@@index([organizationId, orderId, id])
@@map("b2b_partner_order_lines")
}
model B2bPartnerOrderCancellation {
orderId String @id @map("order_id") @db.Uuid
organizationId String @map("organization_id") @db.Uuid
actorId String @map("actor_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)
order B2bPartnerOrder @relation(fields: [orderId, organizationId], references: [id, organizationId], onDelete: Restrict)
actor User @relation(fields: [actorId, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([orderId, organizationId])
@@unique([organizationId, idempotencyKey])
@@map("b2b_partner_order_cancellations")
}

View File

@ -65,6 +65,9 @@ model Organization {
b2bArtworks B2bArtwork[] b2bArtworks B2bArtwork[]
b2bArtworkVersions B2bArtworkVersion[] b2bArtworkVersions B2bArtworkVersion[]
b2bArtworkDecisions B2bArtworkDecision[] b2bArtworkDecisions B2bArtworkDecision[]
b2bPartnerOrders B2bPartnerOrder[]
b2bPartnerOrderLines B2bPartnerOrderLine[]
b2bPartnerOrderCancellations B2bPartnerOrderCancellation[]
@@map("organizations") @@map("organizations")
} }
model User { model User {
@ -118,6 +121,8 @@ model User {
b2bArtworks B2bArtwork[] b2bArtworks B2bArtwork[]
b2bArtworkVersions B2bArtworkVersion[] b2bArtworkVersions B2bArtworkVersion[]
b2bArtworkDecisions B2bArtworkDecision[] b2bArtworkDecisions B2bArtworkDecision[]
b2bPartnerOrders B2bPartnerOrder[]
b2bPartnerOrderCancellations B2bPartnerOrderCancellation[]
stockEntries StockLedger[] stockEntries StockLedger[]
stockReservations StockReservation[] stockReservations StockReservation[]
carts Cart[] carts Cart[]

View File

@ -23,6 +23,9 @@ import {
} from './artworks.controller'; } from './artworks.controller';
import { ArtworkStore } from './artwork.store'; import { ArtworkStore } from './artwork.store';
import { ArtworkReviewStore } from './artwork-review.store'; 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';
@Module({ @Module({
imports: [DatabaseModule, IdentityModule], imports: [DatabaseModule, IdentityModule],
@ -35,6 +38,7 @@ import { ArtworkReviewStore } from './artwork-review.store';
SamplesController, SamplesController,
ArtworksController, ArtworksController,
ArtworkVersionsController, ArtworkVersionsController,
PartnerOrdersController,
], ],
providers: [ providers: [
BusinessStore, BusinessStore,
@ -49,6 +53,8 @@ import { ArtworkReviewStore } from './artwork-review.store';
SampleActionStore, SampleActionStore,
ArtworkStore, ArtworkStore,
ArtworkReviewStore, ArtworkReviewStore,
PartnerOrderStore,
PartnerOrderCancelStore,
], ],
}) })
export class B2bModule {} export class B2bModule {}

View File

@ -0,0 +1,54 @@
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 { presentPartnerOrder, requirePartnerOrder } from './partner-order-view';
import type { CancelPartnerOrderInput } from './partner-order.schemas';
@Injectable()
export class PartnerOrderCancelStore {
constructor(private readonly access: AccessStore) {}
cancel(actor: Principal, id: string, input: CancelPartnerOrderInput) {
return this.access.mutate(actor, 'b2b.order.manage', async (tx) => {
const order = await requirePartnerOrder(tx, actor.organizationId, id);
const hash = commandHash(id, input.reason);
const replay = await tx.b2bPartnerOrderCancellation.findUnique({
where: {
organizationId_idempotencyKey: {
organizationId: actor.organizationId,
idempotencyKey: input.idempotencyKey,
},
},
});
if (replay) {
if (replay.requestHash !== hash)
throw new AppError('B2B_ORDER_CANCEL_REPLAY_CONFLICT');
return presentPartnerOrder(order);
}
if (order.cancellation) throw new AppError('B2B_ORDER_ALREADY_CANCELLED');
await tx.b2bPartnerOrderCancellation.create({
data: {
orderId: id,
organizationId: actor.organizationId,
actorId: actor.userId,
reason: input.reason,
idempotencyKey: input.idempotencyKey,
requestHash: hash,
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'b2b_order.cancelled',
id,
);
return presentPartnerOrder(
await requirePartnerOrder(tx, actor.organizationId, id),
);
});
}
}

View File

@ -0,0 +1,43 @@
import { AppError } from '../common/errors/app-error';
import type { DatabaseService } from '../database/database.service';
import type {
Prisma,
B2bPartnerOrder,
B2bPartnerOrderLine,
B2bPartnerOrderCancellation,
} from '../generated/prisma/client';
type Db = DatabaseService | Prisma.TransactionClient;
export const partnerOrderInclude = {
lines: { orderBy: { id: 'asc' as const } },
cancellation: true,
};
export async function requirePartnerOrder(
db: Db,
organizationId: string,
id: string,
) {
const order = await db.b2bPartnerOrder.findFirst({
where: { id, organizationId },
include: partnerOrderInclude,
});
if (!order) throw new AppError('B2B_ORDER_NOT_FOUND');
return order;
}
export function presentPartnerOrder(
order: B2bPartnerOrder & {
lines: B2bPartnerOrderLine[];
cancellation: B2bPartnerOrderCancellation | null;
},
) {
return {
...order,
status: order.cancellation ? 'CANCELLED' : 'RECEIVED',
merchandiseTotal: order.merchandiseTotal.toFixed(2),
lines: order.lines.map((line) => ({
...line,
unitPrice: line.unitPrice.toFixed(2),
lineTotal: line.lineTotal.toFixed(2),
})),
};
}

View File

@ -0,0 +1,24 @@
import { z } from 'zod';
import { text } from '../common/input';
import { pageSchema } from '../identity/identity.schemas';
export const createPartnerOrderSchema = z
.object({
quoteId: z.uuid(),
partnerReference: text(80),
note: text(500, 3).nullable().optional(),
idempotencyKey: z.uuid(),
})
.strict();
export const cancelPartnerOrderSchema = z
.object({
reason: text(500, 3),
idempotencyKey: z.uuid(),
})
.strict();
export const partnerOrderQuerySchema = pageSchema
.extend({ accountId: z.uuid().optional() })
.strict();
export type CreatePartnerOrderInput = z.infer<typeof createPartnerOrderSchema>;
export type CancelPartnerOrderInput = z.infer<typeof cancelPartnerOrderSchema>;
export type PartnerOrderQuery = z.infer<typeof partnerOrderQuerySchema>;

View File

@ -0,0 +1,139 @@
import { randomUUID } from 'node:crypto';
import { Injectable } from '@nestjs/common';
import { AppError } from '../common/errors/app-error';
import { commandHash } from '../common/idempotency';
import { DatabaseService } from '../database/database.service';
import type { Prisma } from '../generated/prisma/client';
import { AccessStore } from '../identity/access.store';
import { recordAudit } from '../identity/audit';
import type { Principal } from '../identity/identity.types';
import { isVerifiedBusinessAccount } from './business-verification';
import {
partnerOrderInclude,
presentPartnerOrder,
requirePartnerOrder,
} from './partner-order-view';
import type {
CreatePartnerOrderInput,
PartnerOrderQuery,
} from './partner-order.schemas';
import { requireQuote } from './quote-lookup';
@Injectable()
export class PartnerOrderStore {
constructor(
private readonly db: DatabaseService,
private readonly access: AccessStore,
) {}
async list(actor: Principal, query: PartnerOrderQuery) {
const orders = await this.db.b2bPartnerOrder.findMany({
where: {
organizationId: actor.organizationId,
...(query.accountId ? { accountId: query.accountId } : {}),
},
include: partnerOrderInclude,
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
take: query.limit,
skip: query.offset,
});
return orders.map(presentPartnerOrder);
}
async get(actor: Principal, id: string) {
return presentPartnerOrder(
await requirePartnerOrder(this.db, actor.organizationId, id),
);
}
create(actor: Principal, input: CreatePartnerOrderInput) {
const note = input.note ?? null;
const hash = commandHash(input.quoteId, input.partnerReference, note ?? '');
return this.access.mutate(actor, 'b2b.order.manage', async (tx) => {
const replay = await tx.b2bPartnerOrder.findUnique({
where: {
organizationId_idempotencyKey: {
organizationId: actor.organizationId,
idempotencyKey: input.idempotencyKey,
},
},
include: partnerOrderInclude,
});
if (replay) {
if (replay.requestHash !== hash)
throw new AppError('B2B_ORDER_REPLAY_CONFLICT');
return presentPartnerOrder(replay);
}
const quote = await requireQuote(tx, actor.organizationId, input.quoteId);
if (quote.response?.kind !== 'ACCEPTED')
throw new AppError('B2B_ORDER_QUOTE_NOT_ACCEPTED');
if (quote.expiresAt.getTime() <= Date.now())
throw new AppError('B2B_ORDER_QUOTE_EXPIRED');
if (
!(await isVerifiedBusinessAccount(
tx,
actor.organizationId,
quote.accountId,
))
)
throw new AppError('B2B_ORDER_ACCOUNT_UNVERIFIED');
if (
await tx.b2bPartnerOrder.findFirst({
where: { quoteId: quote.id, organizationId: actor.organizationId },
})
)
throw new AppError('B2B_ORDER_QUOTE_USED');
if (
await tx.b2bPartnerOrder.findFirst({
where: {
organizationId: actor.organizationId,
accountId: quote.accountId,
partnerReference: input.partnerReference,
},
})
)
throw new AppError('B2B_ORDER_REFERENCE_USED');
const id = randomUUID();
await tx.b2bPartnerOrder.create({
data: {
id,
organizationId: actor.organizationId,
accountId: quote.accountId,
quoteId: quote.id,
createdById: actor.userId,
number: `BO-${id.replaceAll('-', '').slice(0, 20).toUpperCase()}`,
partnerReference: input.partnerReference,
note,
accountSnapshot: quote.accountSnapshot as Prisma.InputJsonValue,
currency: quote.currency,
merchandiseTotal: quote.merchandiseTotal,
idempotencyKey: input.idempotencyKey,
requestHash: hash,
},
});
await tx.b2bPartnerOrderLine.createMany({
data: quote.lines.map((line) => ({
organizationId: actor.organizationId,
orderId: id,
variantId: line.variantId,
sku: line.sku,
name: line.name,
quantity: line.quantity,
minQuantity: line.minQuantity,
unitPrice: line.unitPrice,
lineTotal: line.lineTotal,
})),
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'b2b_order.received',
id,
);
return presentPartnerOrder(
await requirePartnerOrder(tx, actor.organizationId, id),
);
});
}
}

View File

@ -0,0 +1,72 @@
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 type { Principal } from '../identity/identity.types';
import { PartnerOrderCancelStore } from './partner-order-cancel.store';
import { PartnerOrderStore } from './partner-order.store';
import {
cancelPartnerOrderSchema,
createPartnerOrderSchema,
partnerOrderQuerySchema,
type CancelPartnerOrderInput,
type CreatePartnerOrderInput,
type PartnerOrderQuery,
} from './partner-order.schemas';
@Controller('b2b/partner-orders')
export class PartnerOrdersController {
constructor(
private readonly orders: PartnerOrderStore,
private readonly cancellations: PartnerOrderCancelStore,
) {}
@Get()
@RequirePermission('b2b.order.read')
list(
@CurrentPrincipal() actor: Principal,
@Query(new SchemaPipe(partnerOrderQuerySchema)) query: PartnerOrderQuery,
) {
return this.orders.list(actor, query);
}
@Post()
@RequirePermission('b2b.order.manage')
create(
@CurrentPrincipal() actor: Principal,
@Body(new SchemaPipe(createPartnerOrderSchema))
input: CreatePartnerOrderInput,
) {
return this.orders.create(actor, input);
}
@Get(':id')
@RequirePermission('b2b.order.read')
get(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
) {
return this.orders.get(actor, id);
}
@Post(':id/cancel')
@RequirePermission('b2b.order.manage')
cancel(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@Body(new SchemaPipe(cancelPartnerOrderSchema))
input: CancelPartnerOrderInput,
) {
return this.cancellations.cancel(actor, id, input);
}
}

View File

@ -0,0 +1,47 @@
export const B2B_ORDER_ERRORS = {
B2B_ORDER_NOT_FOUND: [
404,
'Partner purchase order not found',
'Scoped B2B partner order lookup failed',
],
B2B_ORDER_QUOTE_NOT_ACCEPTED: [
409,
'Quotation must be accepted before an order is recorded',
'B2B order quote acceptance gate failed',
],
B2B_ORDER_QUOTE_EXPIRED: [
409,
'Quotation has expired and needs a new issue',
'B2B order quote expiry gate failed',
],
B2B_ORDER_ACCOUNT_UNVERIFIED: [
409,
'Business account must be verified for a partner order',
'B2B order account verification gate failed',
],
B2B_ORDER_QUOTE_USED: [
409,
'Quotation already has a partner purchase order',
'B2B order duplicate quote',
],
B2B_ORDER_REFERENCE_USED: [
409,
'Partner purchase order reference is already used for this account',
'B2B order partner reference collision',
],
B2B_ORDER_REPLAY_CONFLICT: [
409,
'Idempotency key was used for a different partner order',
'B2B order create replay payload mismatch',
],
B2B_ORDER_CANCEL_REPLAY_CONFLICT: [
409,
'Idempotency key was used for a different cancellation',
'B2B order cancellation replay payload mismatch',
],
B2B_ORDER_ALREADY_CANCELLED: [
409,
'Partner purchase order is already cancelled',
'B2B order duplicate cancellation',
],
} as const;

View File

@ -8,6 +8,7 @@ import { B2B_QUOTE_ERRORS } from './b2b-quote-errors';
import { B2B_CREDIT_ERRORS } from './b2b-credit-errors'; import { B2B_CREDIT_ERRORS } from './b2b-credit-errors';
import { B2B_SAMPLE_ERRORS } from './b2b-sample-errors'; import { B2B_SAMPLE_ERRORS } from './b2b-sample-errors';
import { B2B_ARTWORK_ERRORS } from './b2b-artwork-errors'; import { B2B_ARTWORK_ERRORS } from './b2b-artwork-errors';
import { B2B_ORDER_ERRORS } from './b2b-order-errors';
export const ERRORS = { export const ERRORS = {
...PLATFORM_ERRORS, ...PLATFORM_ERRORS,
...COMMERCE_ERRORS, ...COMMERCE_ERRORS,
@ -19,5 +20,6 @@ export const ERRORS = {
...B2B_CREDIT_ERRORS, ...B2B_CREDIT_ERRORS,
...B2B_SAMPLE_ERRORS, ...B2B_SAMPLE_ERRORS,
...B2B_ARTWORK_ERRORS, ...B2B_ARTWORK_ERRORS,
...B2B_ORDER_ERRORS,
} as const; } as const;
export type ErrorCode = keyof typeof ERRORS; export type ErrorCode = keyof typeof ERRORS;

View File

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

View File

@ -0,0 +1,38 @@
import { randomUUID } from 'node:crypto';
import {
createPartnerOrderSchema,
cancelPartnerOrderSchema,
} from '../src/b2b/partner-order.schemas';
describe('partner purchase order validation', () => {
const create = () => ({
quoteId: randomUUID(),
partnerReference: 'CUSTOMER-PO-123',
note: null,
idempotencyKey: randomUUID(),
});
it('accepts a reference and optional note', () => {
expect(createPartnerOrderSchema.safeParse(create()).success).toBe(true);
expect(
createPartnerOrderSchema.safeParse({
...create(),
note: 'Rush packaging',
}).success,
).toBe(true);
});
it('rejects empty, excessive, or markup references', () => {
for (const partnerReference of [' ', 'x'.repeat(81), '<script>'])
expect(
createPartnerOrderSchema.safeParse({ ...create(), partnerReference })
.success,
).toBe(false);
});
it('requires a meaningful cancellation reason', () => {
expect(
cancelPartnerOrderSchema.safeParse({
reason: ' ',
idempotencyKey: randomUUID(),
}).success,
).toBe(false);
});
});

View File

@ -0,0 +1,322 @@
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);
});
});