feat/b2b-quotations #28
|
|
@ -58,3 +58,4 @@ Material warehouse transfers: see [Phase 2R API guide](docs/material-transfers-a
|
|||
Manual material-stock adjustments: see [Phase 2S API guide](docs/material-adjustments-api.md).
|
||||
Business-account profiles and manual verification: see [Phase 3A API guide](docs/b2b-business-verification-api.md).
|
||||
Partner price lists and minimum quantities: see [Phase 3B API guide](docs/b2b-price-lists-api.md).
|
||||
B2B quotations and response tracking: see [Phase 3C API guide](docs/b2b-quotations-api.md).
|
||||
|
|
|
|||
|
|
@ -0,0 +1,16 @@
|
|||
# B2B quotations (Phase 3C)
|
||||
|
||||
Staff issue quotations to verified business accounts using an active account-specific price list. Issuance saves the account profile, price-list name, variant SKU and name, unit prices, MOQs, quantities, and merchandise total as immutable snapshots. An archived price list or later catalog price change cannot alter an issued quote.
|
||||
|
||||
| Method | Route | Permission | Purpose |
|
||||
| ------ | --------------------------------- | ------------------ | ------------------------------------------------------------------- |
|
||||
| GET | `/api/v1/b2b/quotes` | `b2b.quote.read` | List scoped quotes with `limit`, `offset`, and optional `accountId` |
|
||||
| POST | `/api/v1/b2b/quotes` | `b2b.quote.manage` | Issue a quotation |
|
||||
| GET | `/api/v1/b2b/quotes/:id` | `b2b.quote.read` | Read the full snapshot and response |
|
||||
| POST | `/api/v1/b2b/quotes/:id/response` | `b2b.quote.manage` | Record customer acceptance, decline, or staff withdrawal |
|
||||
|
||||
Issue with `accountId`, `priceListId`, `expiresAt` (RFC 3339 with timezone, within the next 90 days), optional `customerReference`, 1–100 distinct `lines` of `{ "variantId": "<UUID>", "quantity": 12 }`, and `idempotencyKey` (UUID). Every quantity must meet its price-list MOQ. The response includes an opaque `BQ-...` quotation number, currency, fixed two-decimal merchandise total, account snapshot, and line snapshots. Repeating the same request and key returns the original quotation even if its price list has since been archived; changing the request with the same key returns a conflict.
|
||||
|
||||
A new quotation has status `ISSUED`, or `EXPIRED` once its deadline passes without a response. Recording `{ "kind": "ACCEPTED", "note": "Customer accepted by email", "idempotencyKey": "<UUID>" }` changes the displayed status to `ACCEPTED`. `DECLINED` and `WITHDRAWN` are also available. Staff must record a note identifying the basis for the response. Only one response is allowed, and it must be recorded before expiry. Responses are immutable and support idempotent retries.
|
||||
|
||||
This is a merchandise-only quotation. It excludes tax, shipping, stock reservation, payment, and credit terms, and `ACCEPTED` does not create an order. Staff should communicate those limits before seeking acceptance; B2B order conversion belongs to a later phase. Apply the timestamped migration with `pnpm db:deploy`. Existing system Owner roles gain the quotation permissions; custom roles must be granted them explicitly.
|
||||
|
|
@ -39,7 +39,8 @@ Suppliers, material/urli classification and compatibility, procurement, purchase
|
|||
Business verification, price lists, MOQ, quotations, credit policies, samples, branding/artwork approvals, partner purchase orders, partial payments, custom candle requests and partner reporting.
|
||||
|
||||
- 3A (implemented): organization-scoped business profiles and manual staff verification with immutable submission/decision history. Partner login and automated external registry checks are outside this milestone.
|
||||
- 3B (implemented): account-specific, currency-scoped variant price lists and minimum quantities, with verified-account activation, immutable active terms, and a merchandise price check. Quotations and order integration remain later milestones.
|
||||
- 3B (implemented): account-specific, currency-scoped variant price lists and minimum quantities, with verified-account activation, immutable active terms, and a merchandise price check. Order integration remains a later milestone.
|
||||
- 3C (implemented): staff-issued merchandise quotations with immutable account and price snapshots, expiry, idempotent issuance, and one auditable customer response. Tax, shipping, stock reservation, credit policy, and order conversion remain later milestones.
|
||||
|
||||
## Phase 4: Growth channels
|
||||
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@
|
|||
"admin:seed-local": "node dist/cli/local-admin.js seed",
|
||||
"db:test": "node scripts/test-migrations.mjs",
|
||||
"migrations:check": "node scripts/check-migrations.mjs",
|
||||
"security:audit": "pnpm audit --prod --audit-level=high"
|
||||
"security:audit": "pnpm audit --prod --audit-level=moderate"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^11.1.0",
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ overrides:
|
|||
prisma>mysql2: 3.23.1
|
||||
'@nestjs/platform-express>multer': 2.4.0
|
||||
'@nestjs/swagger>js-yaml': 5.4.1
|
||||
ajv>fast-uri: 3.1.8
|
||||
|
||||
importers:
|
||||
|
||||
|
|
@ -1725,8 +1726,8 @@ packages:
|
|||
fast-safe-stringify@2.1.1:
|
||||
resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==}
|
||||
|
||||
fast-uri@3.1.7:
|
||||
resolution: {integrity: sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==}
|
||||
fast-uri@3.1.8:
|
||||
resolution: {integrity: sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==}
|
||||
|
||||
fb-watchman@2.0.2:
|
||||
resolution: {integrity: sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==}
|
||||
|
|
@ -4039,7 +4040,7 @@ snapshots:
|
|||
ajv@8.20.0:
|
||||
dependencies:
|
||||
fast-deep-equal: 3.1.3
|
||||
fast-uri: 3.1.7
|
||||
fast-uri: 3.1.8
|
||||
json-schema-traverse: 1.0.0
|
||||
require-from-string: 2.0.2
|
||||
|
||||
|
|
@ -4534,7 +4535,7 @@ snapshots:
|
|||
|
||||
fast-safe-stringify@2.1.1: {}
|
||||
|
||||
fast-uri@3.1.7: {}
|
||||
fast-uri@3.1.8: {}
|
||||
|
||||
fb-watchman@2.0.2:
|
||||
dependencies:
|
||||
|
|
|
|||
|
|
@ -10,3 +10,4 @@ overrides:
|
|||
'prisma>mysql2': 3.23.1
|
||||
'@nestjs/platform-express>multer': 2.4.0
|
||||
'@nestjs/swagger>js-yaml': 5.4.1
|
||||
'ajv>fast-uri': 3.1.8
|
||||
|
|
|
|||
|
|
@ -10,6 +10,12 @@ enum B2bPriceListStatus {
|
|||
ARCHIVED
|
||||
}
|
||||
|
||||
enum B2bQuoteResponseKind {
|
||||
ACCEPTED
|
||||
DECLINED
|
||||
WITHDRAWN
|
||||
}
|
||||
|
||||
model BusinessAccount {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
|
|
@ -33,6 +39,7 @@ model BusinessAccount {
|
|||
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
events BusinessVerificationEvent[]
|
||||
priceLists B2bPriceList[]
|
||||
quotes B2bQuote[]
|
||||
@@unique([organizationId, code])
|
||||
@@unique([organizationId, countryCode, registrationNumber])
|
||||
@@unique([id, organizationId])
|
||||
|
|
@ -55,6 +62,7 @@ model B2bPriceList {
|
|||
account BusinessAccount @relation(fields: [accountId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
items B2bPriceListItem[]
|
||||
quotes B2bQuote[]
|
||||
@@unique([id, organizationId])
|
||||
@@unique([organizationId, accountId, currency, activeSlot])
|
||||
@@index([organizationId, accountId, status, createdAt, id])
|
||||
|
|
@ -98,3 +106,70 @@ model BusinessVerificationEvent {
|
|||
@@index([organizationId, accountId, sequence])
|
||||
@@map("business_verification_events")
|
||||
}
|
||||
|
||||
model B2bQuote {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
accountId String @map("account_id") @db.Uuid
|
||||
priceListId String @map("price_list_id") @db.Uuid
|
||||
createdById String @map("created_by_id") @db.Uuid
|
||||
number String @db.VarChar(24)
|
||||
accountSnapshot Json @map("account_snapshot") @db.JsonB
|
||||
priceListName String @map("price_list_name") @db.VarChar(100)
|
||||
currency String @db.Char(3)
|
||||
merchandiseTotal Decimal @map("merchandise_total") @db.Decimal(18,2)
|
||||
customerReference String? @map("customer_reference") @db.VarChar(100)
|
||||
expiresAt DateTime @map("expires_at") @db.Timestamptz(3)
|
||||
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)
|
||||
priceList B2bPriceList @relation(fields: [priceListId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
lines B2bQuoteLine[]
|
||||
response B2bQuoteResponse?
|
||||
@@unique([id, organizationId])
|
||||
@@unique([organizationId, number])
|
||||
@@unique([organizationId, idempotencyKey])
|
||||
@@index([organizationId, accountId, createdAt, id])
|
||||
@@map("b2b_quotes")
|
||||
}
|
||||
|
||||
model B2bQuoteLine {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
quoteId String @map("quote_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)
|
||||
quote B2bQuote @relation(fields: [quoteId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
variant ProductVariant @relation(fields: [variantId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
@@unique([quoteId, variantId])
|
||||
@@index([organizationId, quoteId, id])
|
||||
@@map("b2b_quote_lines")
|
||||
}
|
||||
|
||||
model B2bQuoteResponse {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
quoteId String @map("quote_id") @db.Uuid
|
||||
actorId String @map("actor_id") @db.Uuid
|
||||
kind B2bQuoteResponseKind
|
||||
note 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)
|
||||
quote B2bQuote @relation(fields: [quoteId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
actor User @relation(fields: [actorId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
@@unique([quoteId, organizationId])
|
||||
@@unique([organizationId, idempotencyKey])
|
||||
@@index([organizationId, quoteId])
|
||||
@@map("b2b_quote_responses")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -39,6 +39,7 @@ model ProductVariant {
|
|||
orderLines OrderLine[]
|
||||
boms ProductBom[]
|
||||
b2bPriceListItems B2bPriceListItem[]
|
||||
b2bQuoteLines B2bQuoteLine[]
|
||||
product Product @relation(fields: [productId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
@@unique([organizationId, sku])
|
||||
@@unique([id, organizationId])
|
||||
|
|
|
|||
|
|
@ -34,5 +34,6 @@
|
|||
"20260930002200_material_warehouse_transfers": "0f193ecd186971e19fdc823944312be70646b348a1a846ab41703d269936e21a",
|
||||
"20260930003800_material_stock_adjustments": "2002d6826f34da5a999a0098a7191aa00f5fdc4ca54446b776270021d48ef5eb",
|
||||
"20260930010000_b2b_business_verification": "1ab6537ff21436ce3421024f6f61e647c2c82a35a09a769833c6b82cdccca32b",
|
||||
"20260930011800_b2b_price_lists": "c2f29a61c6fee93cbffb9d67654c323b2894b3aad7bb296b514f46b623db62d9"
|
||||
"20260930011800_b2b_price_lists": "c2f29a61c6fee93cbffb9d67654c323b2894b3aad7bb296b514f46b623db62d9",
|
||||
"20260930190500_b2b_quotations": "0497ece6cb035687548773ce265842125fa1a655e5951e8d958290d664f5c3f0"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,141 @@
|
|||
CREATE TYPE "B2bQuoteResponseKind" AS ENUM ('ACCEPTED', 'DECLINED', 'WITHDRAWN');
|
||||
|
||||
CREATE TABLE "b2b_quotes" (
|
||||
"id" UUID NOT NULL PRIMARY KEY,
|
||||
"organization_id" UUID NOT NULL,
|
||||
"account_id" UUID NOT NULL,
|
||||
"price_list_id" UUID NOT NULL,
|
||||
"created_by_id" UUID NOT NULL,
|
||||
"number" VARCHAR(24) NOT NULL,
|
||||
"account_snapshot" JSONB NOT NULL,
|
||||
"price_list_name" VARCHAR(100) NOT NULL,
|
||||
"currency" CHAR(3) NOT NULL,
|
||||
"merchandise_total" DECIMAL(18,2) NOT NULL,
|
||||
"customer_reference" VARCHAR(100),
|
||||
"expires_at" TIMESTAMPTZ(3) NOT NULL,
|
||||
"idempotency_key" UUID NOT NULL,
|
||||
"request_hash" CHAR(64) NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "b2b_quotes_number_format" CHECK ("number" ~ '^BQ-[A-F0-9]{20}$'),
|
||||
CONSTRAINT "b2b_quotes_total" CHECK ("merchandise_total" > 0),
|
||||
CONSTRAINT "b2b_quotes_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$')
|
||||
);
|
||||
CREATE UNIQUE INDEX "b2b_quotes_id_organization_id_key" ON "b2b_quotes"("id", "organization_id");
|
||||
CREATE UNIQUE INDEX "b2b_quotes_organization_id_number_key" ON "b2b_quotes"("organization_id", "number");
|
||||
CREATE UNIQUE INDEX "b2b_quotes_organization_id_idempotency_key_key" ON "b2b_quotes"("organization_id", "idempotency_key");
|
||||
CREATE INDEX "b2b_quotes_organization_id_account_id_created_at_id_idx" ON "b2b_quotes"("organization_id", "account_id", "created_at", "id");
|
||||
ALTER TABLE "b2b_quotes" ADD CONSTRAINT "b2b_quotes_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
ALTER TABLE "b2b_quotes" ADD CONSTRAINT "b2b_quotes_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_quotes" ADD CONSTRAINT "b2b_quotes_price_list_id_organization_id_fkey" FOREIGN KEY ("price_list_id", "organization_id") REFERENCES "b2b_price_lists"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
ALTER TABLE "b2b_quotes" ADD CONSTRAINT "b2b_quotes_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_quote_lines" (
|
||||
"id" UUID NOT NULL PRIMARY KEY,
|
||||
"organization_id" UUID NOT NULL,
|
||||
"quote_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_quote_lines_quantity" CHECK ("quantity" BETWEEN 1 AND 1000000 AND "quantity" >= "min_quantity"),
|
||||
CONSTRAINT "b2b_quote_lines_money" CHECK ("unit_price" > 0 AND "line_total" = "unit_price" * "quantity")
|
||||
);
|
||||
CREATE UNIQUE INDEX "b2b_quote_lines_quote_id_variant_id_key" ON "b2b_quote_lines"("quote_id", "variant_id");
|
||||
CREATE INDEX "b2b_quote_lines_organization_id_quote_id_id_idx" ON "b2b_quote_lines"("organization_id", "quote_id", "id");
|
||||
ALTER TABLE "b2b_quote_lines" ADD CONSTRAINT "b2b_quote_lines_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
ALTER TABLE "b2b_quote_lines" ADD CONSTRAINT "b2b_quote_lines_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_quote_lines" ADD CONSTRAINT "b2b_quote_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_quote_responses" (
|
||||
"id" UUID NOT NULL PRIMARY KEY,
|
||||
"organization_id" UUID NOT NULL,
|
||||
"quote_id" UUID NOT NULL,
|
||||
"actor_id" UUID NOT NULL,
|
||||
"kind" "B2bQuoteResponseKind" NOT NULL,
|
||||
"note" 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_quote_responses_note" CHECK (char_length(btrim("note")) BETWEEN 3 AND 500),
|
||||
CONSTRAINT "b2b_quote_responses_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$')
|
||||
);
|
||||
CREATE UNIQUE INDEX "b2b_quote_responses_quote_id_organization_id_key" ON "b2b_quote_responses"("quote_id", "organization_id");
|
||||
CREATE UNIQUE INDEX "b2b_quote_responses_organization_id_idempotency_key_key" ON "b2b_quote_responses"("organization_id", "idempotency_key");
|
||||
CREATE INDEX "b2b_quote_responses_organization_id_quote_id_idx" ON "b2b_quote_responses"("organization_id", "quote_id");
|
||||
ALTER TABLE "b2b_quote_responses" ADD CONSTRAINT "b2b_quote_responses_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
ALTER TABLE "b2b_quote_responses" ADD CONSTRAINT "b2b_quote_responses_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_quote_responses" ADD CONSTRAINT "b2b_quote_responses_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_quote() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE account business_accounts%ROWTYPE;
|
||||
DECLARE list b2b_price_lists%ROWTYPE;
|
||||
BEGIN
|
||||
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Issued B2B quotations are immutable'; END IF;
|
||||
SELECT * INTO account FROM business_accounts WHERE id = NEW.account_id AND organization_id = NEW.organization_id;
|
||||
SELECT * INTO list FROM b2b_price_lists WHERE id = NEW.price_list_id AND organization_id = NEW.organization_id;
|
||||
IF list.status IS DISTINCT FROM 'ACTIVE' OR list.account_id IS DISTINCT FROM NEW.account_id
|
||||
OR list.currency IS DISTINCT FROM NEW.currency OR list.name IS DISTINCT FROM NEW.price_list_name
|
||||
THEN RAISE EXCEPTION 'Quotation price list does not match the active account terms'; END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM business_verification_events
|
||||
WHERE account_id = NEW.account_id AND kind = 'APPROVED' AND sequence =
|
||||
(SELECT MAX(sequence) FROM business_verification_events WHERE account_id = NEW.account_id))
|
||||
THEN RAISE EXCEPTION 'Quotation business account is not verified'; END IF;
|
||||
IF NEW.expires_at <= CURRENT_TIMESTAMP OR NEW.expires_at > CURRENT_TIMESTAMP + INTERVAL '90 days'
|
||||
THEN RAISE EXCEPTION 'Quotation expiry must be within ninety days'; END IF;
|
||||
IF NEW.account_snapshot IS DISTINCT FROM jsonb_build_object(
|
||||
'legalName', account.legal_name, 'tradingName', account.trading_name,
|
||||
'registrationNumber', account.registration_number, 'taxIdentifier', account.tax_identifier,
|
||||
'countryCode', account.country_code, 'contactEmail', account.contact_email,
|
||||
'contactPhone', account.contact_phone, 'billingLine1', account.billing_line1,
|
||||
'billingCity', account.billing_city, 'billingRegion', account.billing_region,
|
||||
'billingPostalCode', account.billing_postal_code, 'profileVersion', account.profile_version
|
||||
) THEN RAISE EXCEPTION 'Quotation account snapshot is not current'; END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER b2b_quotes_guard BEFORE INSERT OR UPDATE OR DELETE ON b2b_quotes FOR EACH ROW EXECUTE FUNCTION guard_b2b_quote();
|
||||
|
||||
CREATE FUNCTION guard_b2b_quote_line() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE quote b2b_quotes%ROWTYPE;
|
||||
DECLARE item b2b_price_list_items%ROWTYPE;
|
||||
DECLARE variant product_variants%ROWTYPE;
|
||||
BEGIN
|
||||
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Issued B2B quotation lines are immutable'; END IF;
|
||||
SELECT * INTO quote FROM b2b_quotes WHERE id = NEW.quote_id AND organization_id = NEW.organization_id;
|
||||
SELECT * INTO item FROM b2b_price_list_items WHERE price_list_id = quote.price_list_id AND variant_id = NEW.variant_id;
|
||||
SELECT * INTO variant FROM product_variants WHERE id = NEW.variant_id AND organization_id = NEW.organization_id;
|
||||
IF item.id IS NULL OR item.unit_price <> NEW.unit_price OR item.min_quantity <> NEW.min_quantity
|
||||
OR variant.sku IS DISTINCT FROM NEW.sku OR variant.name IS DISTINCT FROM NEW.name
|
||||
THEN RAISE EXCEPTION 'Quotation line does not match its price list item and variant snapshot'; END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER b2b_quote_lines_guard BEFORE INSERT OR UPDATE OR DELETE ON b2b_quote_lines FOR EACH ROW EXECUTE FUNCTION guard_b2b_quote_line();
|
||||
|
||||
CREATE FUNCTION check_b2b_quote_total() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF (SELECT COUNT(*) FROM b2b_quote_lines WHERE quote_id = NEW.id) = 0 OR
|
||||
(SELECT SUM(line_total) FROM b2b_quote_lines WHERE quote_id = NEW.id) <> NEW.merchandise_total
|
||||
THEN RAISE EXCEPTION 'Quotation total must equal its line snapshots'; END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE CONSTRAINT TRIGGER b2b_quotes_total_guard AFTER INSERT ON b2b_quotes
|
||||
DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION check_b2b_quote_total();
|
||||
|
||||
CREATE FUNCTION guard_b2b_quote_response() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE deadline TIMESTAMPTZ;
|
||||
BEGIN
|
||||
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Quotation responses are immutable'; END IF;
|
||||
SELECT expires_at INTO deadline FROM b2b_quotes WHERE id = NEW.quote_id AND organization_id = NEW.organization_id;
|
||||
IF deadline <= CURRENT_TIMESTAMP THEN RAISE EXCEPTION 'Quotation has expired'; END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER b2b_quote_responses_guard BEFORE INSERT OR UPDATE OR DELETE ON b2b_quote_responses FOR EACH ROW EXECUTE FUNCTION guard_b2b_quote_response();
|
||||
|
||||
UPDATE "roles" SET "permissions" = ARRAY(SELECT DISTINCT unnest("permissions" || ARRAY['b2b.quote.read', 'b2b.quote.manage']))
|
||||
WHERE "is_system" = true AND "name" = 'Owner';
|
||||
|
|
@ -55,6 +55,9 @@ model Organization {
|
|||
businessVerificationEvents BusinessVerificationEvent[]
|
||||
b2bPriceLists B2bPriceList[]
|
||||
b2bPriceListItems B2bPriceListItem[]
|
||||
b2bQuotes B2bQuote[]
|
||||
b2bQuoteLines B2bQuoteLine[]
|
||||
b2bQuoteResponses B2bQuoteResponse[]
|
||||
@@map("organizations")
|
||||
}
|
||||
model User {
|
||||
|
|
@ -99,6 +102,8 @@ model User {
|
|||
businessAccounts BusinessAccount[]
|
||||
businessVerificationEvents BusinessVerificationEvent[]
|
||||
b2bPriceLists B2bPriceList[]
|
||||
b2bQuotes B2bQuote[]
|
||||
b2bQuoteResponses B2bQuoteResponse[]
|
||||
stockEntries StockLedger[]
|
||||
stockReservations StockReservation[]
|
||||
carts Cart[]
|
||||
|
|
|
|||
|
|
@ -8,6 +8,9 @@ import { PriceListsController } from './price-lists.controller';
|
|||
import { PriceListItemsController } from './price-list-items.controller';
|
||||
import { PriceListStore } from './price-list.store';
|
||||
import { PriceListItemStore } from './price-list-item.store';
|
||||
import { QuotesController } from './quotes.controller';
|
||||
import { QuoteStore } from './quote.store';
|
||||
import { QuoteResponseStore } from './quote-response.store';
|
||||
|
||||
@Module({
|
||||
imports: [DatabaseModule, IdentityModule],
|
||||
|
|
@ -15,12 +18,15 @@ import { PriceListItemStore } from './price-list-item.store';
|
|||
BusinessController,
|
||||
PriceListsController,
|
||||
PriceListItemsController,
|
||||
QuotesController,
|
||||
],
|
||||
providers: [
|
||||
BusinessStore,
|
||||
VerificationStore,
|
||||
PriceListStore,
|
||||
PriceListItemStore,
|
||||
QuoteStore,
|
||||
QuoteResponseStore,
|
||||
],
|
||||
})
|
||||
export class B2bModule {}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,31 @@
|
|||
import { AppError } from '../common/errors/app-error';
|
||||
import { commandHash } from '../common/idempotency';
|
||||
import { Prisma } from '../generated/prisma/client';
|
||||
import type { IssueQuoteInput } from './quote.schemas';
|
||||
|
||||
const MAX_AMOUNT = new Prisma.Decimal('9999999999999999.99');
|
||||
const NINETY_DAYS = 90 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export function prepareQuoteCommand(input: IssueQuoteInput) {
|
||||
const expiresAt = new Date(input.expiresAt);
|
||||
const reference = input.customerReference ?? null;
|
||||
const lines = [...input.lines].sort((a, b) =>
|
||||
a.variantId.localeCompare(b.variantId),
|
||||
);
|
||||
const requestHash = commandHash(
|
||||
input.accountId,
|
||||
input.priceListId,
|
||||
expiresAt.toISOString(),
|
||||
reference ?? '',
|
||||
JSON.stringify(lines),
|
||||
);
|
||||
return { expiresAt, reference, lines, requestHash };
|
||||
}
|
||||
|
||||
export function assertQuoteLimits(expiresAt: Date, amounts: string[]) {
|
||||
const remaining = expiresAt.getTime() - Date.now();
|
||||
if (remaining <= 0 || remaining > NINETY_DAYS)
|
||||
throw new AppError('B2B_QUOTE_EXPIRY_INVALID');
|
||||
if (amounts.some((amount) => new Prisma.Decimal(amount).gt(MAX_AMOUNT)))
|
||||
throw new AppError('B2B_QUOTE_AMOUNT_LIMIT');
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { AppError } from '../common/errors/app-error';
|
||||
import type { DatabaseService } from '../database/database.service';
|
||||
import type { Prisma } from '../generated/prisma/client';
|
||||
|
||||
type Db = DatabaseService | Prisma.TransactionClient;
|
||||
export const quoteInclude = {
|
||||
lines: { orderBy: { id: 'asc' as const } },
|
||||
response: true,
|
||||
};
|
||||
|
||||
export async function requireQuote(db: Db, organizationId: string, id: string) {
|
||||
const quote = await db.b2bQuote.findFirst({
|
||||
where: { id, organizationId },
|
||||
include: quoteInclude,
|
||||
});
|
||||
if (!quote) throw new AppError('B2B_QUOTE_NOT_FOUND');
|
||||
return quote;
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
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 { requireQuote } from './quote-lookup';
|
||||
import type { QuoteResponseInput } from './quote.schemas';
|
||||
import { presentQuote } from './quote-view';
|
||||
|
||||
@Injectable()
|
||||
export class QuoteResponseStore {
|
||||
constructor(private readonly access: AccessStore) {}
|
||||
|
||||
respond(actor: Principal, id: string, input: QuoteResponseInput) {
|
||||
return this.access.mutate(actor, 'b2b.quote.manage', async (tx) => {
|
||||
const quote = await requireQuote(tx, actor.organizationId, id);
|
||||
const hash = commandHash(id, input.kind, input.note);
|
||||
const replay = await tx.b2bQuoteResponse.findUnique({
|
||||
where: {
|
||||
organizationId_idempotencyKey: {
|
||||
organizationId: actor.organizationId,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
},
|
||||
},
|
||||
});
|
||||
if (replay) {
|
||||
if (replay.requestHash !== hash)
|
||||
throw new AppError('B2B_QUOTE_RESPONSE_REPLAY_CONFLICT');
|
||||
return presentQuote(quote);
|
||||
}
|
||||
if (quote.response) throw new AppError('B2B_QUOTE_ALREADY_RESOLVED');
|
||||
if (quote.expiresAt.getTime() <= Date.now())
|
||||
throw new AppError('B2B_QUOTE_EXPIRED');
|
||||
await tx.b2bQuoteResponse.create({
|
||||
data: {
|
||||
organizationId: actor.organizationId,
|
||||
quoteId: id,
|
||||
actorId: actor.userId,
|
||||
kind: input.kind,
|
||||
note: input.note,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
requestHash: hash,
|
||||
},
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
`b2b_quote.${input.kind.toLowerCase()}`,
|
||||
id,
|
||||
);
|
||||
return presentQuote(await requireQuote(tx, actor.organizationId, id));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
import type {
|
||||
B2bQuote,
|
||||
B2bQuoteLine,
|
||||
B2bQuoteResponse,
|
||||
} from '../generated/prisma/client';
|
||||
|
||||
export type FullQuote = B2bQuote & {
|
||||
lines: B2bQuoteLine[];
|
||||
response: B2bQuoteResponse | null;
|
||||
};
|
||||
|
||||
export function presentQuote(quote: FullQuote) {
|
||||
const status =
|
||||
quote.response?.kind ??
|
||||
(quote.expiresAt.getTime() <= Date.now() ? 'EXPIRED' : 'ISSUED');
|
||||
return {
|
||||
...quote,
|
||||
merchandiseTotal: quote.merchandiseTotal.toFixed(2),
|
||||
lines: quote.lines.map((line) => ({
|
||||
...line,
|
||||
unitPrice: line.unitPrice.toFixed(2),
|
||||
lineTotal: line.lineTotal.toFixed(2),
|
||||
})),
|
||||
status,
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
import { z } from 'zod';
|
||||
import { text } from '../common/input';
|
||||
import { pageSchema } from '../identity/identity.schemas';
|
||||
import { priceCheckSchema } from './price-list.schemas';
|
||||
|
||||
export const issueQuoteSchema = z
|
||||
.object({
|
||||
accountId: z.uuid(),
|
||||
priceListId: z.uuid(),
|
||||
expiresAt: z.iso.datetime({ offset: true }),
|
||||
customerReference: text(100).nullable().optional(),
|
||||
lines: priceCheckSchema.shape.lines,
|
||||
idempotencyKey: z.uuid(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const quoteResponseSchema = z
|
||||
.object({
|
||||
kind: z.enum(['ACCEPTED', 'DECLINED', 'WITHDRAWN']),
|
||||
note: text(500, 3),
|
||||
idempotencyKey: z.uuid(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const quoteQuerySchema = pageSchema
|
||||
.extend({ accountId: z.uuid().optional() })
|
||||
.strict();
|
||||
|
||||
export type IssueQuoteInput = z.infer<typeof issueQuoteSchema>;
|
||||
export type QuoteResponseInput = z.infer<typeof quoteResponseSchema>;
|
||||
export type QuoteQuery = z.infer<typeof quoteQuerySchema>;
|
||||
|
|
@ -0,0 +1,146 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { AccessStore } from '../identity/access.store';
|
||||
import { recordAudit } from '../identity/audit';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import { profileSnapshot } from './business-profile';
|
||||
import { calculatePriceCheck } from './price-check';
|
||||
import {
|
||||
assertEligiblePriceVariants,
|
||||
requireBusinessAccount,
|
||||
requirePriceList,
|
||||
} from './price-list.helpers';
|
||||
import { assertQuoteLimits, prepareQuoteCommand } from './quote-command';
|
||||
import { quoteInclude, requireQuote } from './quote-lookup';
|
||||
import type { IssueQuoteInput, QuoteQuery } from './quote.schemas';
|
||||
import { presentQuote } from './quote-view';
|
||||
|
||||
@Injectable()
|
||||
export class QuoteStore {
|
||||
constructor(
|
||||
private readonly db: DatabaseService,
|
||||
private readonly access: AccessStore,
|
||||
) {}
|
||||
|
||||
async list(actor: Principal, query: QuoteQuery) {
|
||||
const quotes = await this.db.b2bQuote.findMany({
|
||||
where: {
|
||||
organizationId: actor.organizationId,
|
||||
...(query.accountId ? { accountId: query.accountId } : {}),
|
||||
},
|
||||
include: quoteInclude,
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
take: query.limit,
|
||||
skip: query.offset,
|
||||
});
|
||||
return quotes.map(presentQuote);
|
||||
}
|
||||
|
||||
async get(actor: Principal, id: string) {
|
||||
return presentQuote(await requireQuote(this.db, actor.organizationId, id));
|
||||
}
|
||||
|
||||
issue(actor: Principal, input: IssueQuoteInput) {
|
||||
const command = prepareQuoteCommand(input);
|
||||
return this.access.mutate(actor, 'b2b.quote.manage', async (tx) => {
|
||||
const replay = await tx.b2bQuote.findUnique({
|
||||
where: {
|
||||
organizationId_idempotencyKey: {
|
||||
organizationId: actor.organizationId,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
},
|
||||
},
|
||||
include: quoteInclude,
|
||||
});
|
||||
if (replay) {
|
||||
if (replay.requestHash !== command.requestHash)
|
||||
throw new AppError('B2B_QUOTE_REPLAY_CONFLICT');
|
||||
return presentQuote(replay);
|
||||
}
|
||||
const account = await requireBusinessAccount(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
input.accountId,
|
||||
);
|
||||
const latest = await tx.businessVerificationEvent.findFirst({
|
||||
where: { accountId: account.id, organizationId: actor.organizationId },
|
||||
orderBy: { sequence: 'desc' },
|
||||
});
|
||||
if (latest?.kind !== 'APPROVED')
|
||||
throw new AppError('B2B_QUOTE_ACCOUNT_UNVERIFIED');
|
||||
const list = await requirePriceList(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
input.priceListId,
|
||||
);
|
||||
if (list.accountId !== account.id)
|
||||
throw new AppError('B2B_QUOTE_ACCOUNT_MISMATCH');
|
||||
if (list.status !== 'ACTIVE')
|
||||
throw new AppError('B2B_QUOTE_LIST_INACTIVE');
|
||||
await assertEligiblePriceVariants(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
list.currency,
|
||||
list.items,
|
||||
);
|
||||
const prices = calculatePriceCheck(list, { lines: command.lines });
|
||||
assertQuoteLimits(command.expiresAt, [
|
||||
prices.merchandiseTotal,
|
||||
...prices.lines.map((line) => line.lineTotal),
|
||||
]);
|
||||
const variants = await tx.productVariant.findMany({
|
||||
where: {
|
||||
id: { in: command.lines.map((line) => line.variantId) },
|
||||
organizationId: actor.organizationId,
|
||||
},
|
||||
});
|
||||
const byId = new Map(variants.map((variant) => [variant.id, variant]));
|
||||
const id = randomUUID();
|
||||
await tx.b2bQuote.create({
|
||||
data: {
|
||||
id,
|
||||
organizationId: actor.organizationId,
|
||||
accountId: account.id,
|
||||
priceListId: list.id,
|
||||
createdById: actor.userId,
|
||||
number: `BQ-${id.replaceAll('-', '').slice(0, 20).toUpperCase()}`,
|
||||
accountSnapshot: profileSnapshot(account),
|
||||
priceListName: list.name,
|
||||
currency: list.currency,
|
||||
merchandiseTotal: prices.merchandiseTotal,
|
||||
customerReference: command.reference,
|
||||
expiresAt: command.expiresAt,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
requestHash: command.requestHash,
|
||||
},
|
||||
});
|
||||
await tx.b2bQuoteLine.createMany({
|
||||
data: prices.lines.map((line) => {
|
||||
const variant = byId.get(line.variantId);
|
||||
if (!variant) throw new AppError('B2B_PRICE_VARIANT_INELIGIBLE');
|
||||
return {
|
||||
organizationId: actor.organizationId,
|
||||
quoteId: id,
|
||||
variantId: line.variantId,
|
||||
sku: variant.sku,
|
||||
name: variant.name,
|
||||
quantity: line.quantity,
|
||||
minQuantity: line.minQuantity,
|
||||
unitPrice: line.unitPrice,
|
||||
lineTotal: line.lineTotal,
|
||||
};
|
||||
}),
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
'b2b_quote.issued',
|
||||
id,
|
||||
);
|
||||
return presentQuote(await requireQuote(tx, actor.organizationId, id));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
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 { QuoteStore } from './quote.store';
|
||||
import { QuoteResponseStore } from './quote-response.store';
|
||||
import {
|
||||
issueQuoteSchema,
|
||||
quoteQuerySchema,
|
||||
quoteResponseSchema,
|
||||
type IssueQuoteInput,
|
||||
type QuoteQuery,
|
||||
type QuoteResponseInput,
|
||||
} from './quote.schemas';
|
||||
|
||||
@Controller('b2b/quotes')
|
||||
export class QuotesController {
|
||||
constructor(
|
||||
private readonly quotes: QuoteStore,
|
||||
private readonly responses: QuoteResponseStore,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
@RequirePermission('b2b.quote.read')
|
||||
list(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Query(new SchemaPipe(quoteQuerySchema)) query: QuoteQuery,
|
||||
) {
|
||||
return this.quotes.list(actor, query);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@RequirePermission('b2b.quote.manage')
|
||||
issue(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Body(new SchemaPipe(issueQuoteSchema)) input: IssueQuoteInput,
|
||||
) {
|
||||
return this.quotes.issue(actor, input);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@RequirePermission('b2b.quote.read')
|
||||
get(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
) {
|
||||
return this.quotes.get(actor, id);
|
||||
}
|
||||
|
||||
@Post(':id/response')
|
||||
@RequirePermission('b2b.quote.manage')
|
||||
respond(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body(new SchemaPipe(quoteResponseSchema)) input: QuoteResponseInput,
|
||||
) {
|
||||
return this.responses.respond(actor, id, input);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
export const B2B_QUOTE_ERRORS = {
|
||||
B2B_QUOTE_NOT_FOUND: [
|
||||
404,
|
||||
'B2B quotation not found',
|
||||
'Scoped B2B quotation lookup failed',
|
||||
],
|
||||
B2B_QUOTE_LIST_INACTIVE: [
|
||||
409,
|
||||
'Quotation requires an active price list',
|
||||
'B2B quotation price list inactive',
|
||||
],
|
||||
B2B_QUOTE_ACCOUNT_MISMATCH: [
|
||||
409,
|
||||
'Price list belongs to a different business account',
|
||||
'B2B quotation account and price list mismatch',
|
||||
],
|
||||
B2B_QUOTE_ACCOUNT_UNVERIFIED: [
|
||||
409,
|
||||
'Business account must be verified before quoting',
|
||||
'B2B quotation account verification gate failed',
|
||||
],
|
||||
B2B_QUOTE_EXPIRY_INVALID: [
|
||||
400,
|
||||
'Quotation expiry must be in the next 90 days',
|
||||
'B2B quotation expiry outside allowed window',
|
||||
],
|
||||
B2B_QUOTE_AMOUNT_LIMIT: [
|
||||
400,
|
||||
'Quotation amount exceeds the supported limit',
|
||||
'B2B quotation decimal capacity exceeded',
|
||||
],
|
||||
B2B_QUOTE_REPLAY_CONFLICT: [
|
||||
409,
|
||||
'Idempotency key was used for a different quotation request',
|
||||
'B2B quotation idempotency payload mismatch',
|
||||
],
|
||||
B2B_QUOTE_RESPONSE_REPLAY_CONFLICT: [
|
||||
409,
|
||||
'Idempotency key was used for a different quotation response',
|
||||
'B2B quotation response idempotency payload mismatch',
|
||||
],
|
||||
B2B_QUOTE_ALREADY_RESOLVED: [
|
||||
409,
|
||||
'Quotation already has a recorded response',
|
||||
'B2B quotation response state invalid',
|
||||
],
|
||||
B2B_QUOTE_EXPIRED: [
|
||||
409,
|
||||
'Quotation has expired',
|
||||
'B2B quotation response expiry gate failed',
|
||||
],
|
||||
} as const;
|
||||
|
|
@ -4,6 +4,7 @@ import { PLATFORM_ERRORS } from './platform-errors';
|
|||
import { COMMERCE_ERRORS } from './commerce-errors';
|
||||
import { B2B_ERRORS } from './b2b-errors';
|
||||
import { B2B_PRICE_ERRORS } from './b2b-price-errors';
|
||||
import { B2B_QUOTE_ERRORS } from './b2b-quote-errors';
|
||||
export const ERRORS = {
|
||||
...PLATFORM_ERRORS,
|
||||
...COMMERCE_ERRORS,
|
||||
|
|
@ -11,5 +12,6 @@ export const ERRORS = {
|
|||
...OPERATIONS_ERRORS,
|
||||
...B2B_ERRORS,
|
||||
...B2B_PRICE_ERRORS,
|
||||
...B2B_QUOTE_ERRORS,
|
||||
} as const;
|
||||
export type ErrorCode = keyof typeof ERRORS;
|
||||
|
|
|
|||
|
|
@ -41,5 +41,7 @@ export const PERMISSIONS = [
|
|||
'b2b.verify',
|
||||
'b2b.price.read',
|
||||
'b2b.price.manage',
|
||||
'b2b.quote.read',
|
||||
'b2b.quote.manage',
|
||||
] as const;
|
||||
export type Permission = (typeof PERMISSIONS)[number];
|
||||
|
|
|
|||
|
|
@ -0,0 +1,287 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
||||
import { secondActor, seedProduct } from './helpers/commerce';
|
||||
|
||||
describe('B2B quotations', () => {
|
||||
let ctx: IdentityApp;
|
||||
const auth = { type: 'bearer' as const };
|
||||
const quotes = '/api/v1/b2b/quotes';
|
||||
async function account() {
|
||||
const created = await ctx
|
||||
.api()
|
||||
.post('/api/v1/b2b/accounts')
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
code: `Q-${randomUUID().slice(0, 8)}`,
|
||||
legalName: 'Quotation Partner Limited',
|
||||
tradingName: null,
|
||||
registrationNumber: randomUUID(),
|
||||
taxIdentifier: null,
|
||||
countryCode: 'IN',
|
||||
contactEmail: 'quotes@example.com',
|
||||
contactPhone: null,
|
||||
billingLine1: '10 Market Lane',
|
||||
billingCity: 'Pune',
|
||||
billingRegion: 'Maharashtra',
|
||||
billingPostalCode: '411001',
|
||||
})
|
||||
.expect(201);
|
||||
return created.body.id as string;
|
||||
}
|
||||
async function verifiedAccount() {
|
||||
const id = await account();
|
||||
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 by staff',
|
||||
idempotencyKey: randomUUID(),
|
||||
})
|
||||
.expect(201);
|
||||
return id;
|
||||
}
|
||||
async function activeList(accountId: string) {
|
||||
const { variant } = await seedProduct(ctx, true);
|
||||
const created = await ctx
|
||||
.api()
|
||||
.post(`/api/v1/b2b/accounts/${accountId}/price-lists`)
|
||||
.auth(ctx.token, auth)
|
||||
.send({ name: 'Partner wholesale', currency: 'INR' })
|
||||
.expect(201);
|
||||
const listId = created.body.id as string;
|
||||
await ctx
|
||||
.api()
|
||||
.put(`/api/v1/b2b/price-lists/${listId}/items/${variant.id}`)
|
||||
.auth(ctx.token, auth)
|
||||
.send({ unitPrice: '275.25', minQuantity: 12 })
|
||||
.expect(200);
|
||||
await ctx
|
||||
.api()
|
||||
.post(`/api/v1/b2b/price-lists/${listId}/activate`)
|
||||
.auth(ctx.token, auth)
|
||||
.expect(201);
|
||||
return {
|
||||
listId,
|
||||
variantId: variant.id as string,
|
||||
sku: variant.sku as string,
|
||||
};
|
||||
}
|
||||
const issueInput = (
|
||||
accountId: string,
|
||||
priceListId: string,
|
||||
variantId: string,
|
||||
) => ({
|
||||
accountId,
|
||||
priceListId,
|
||||
expiresAt: new Date(Date.now() + 7 * 86400000).toISOString(),
|
||||
customerReference: 'Inquiry 123',
|
||||
lines: [{ variantId, quantity: 12 }],
|
||||
idempotencyKey: randomUUID(),
|
||||
});
|
||||
|
||||
beforeAll(async () => {
|
||||
ctx = await identityApp();
|
||||
}, 60000);
|
||||
afterAll(async () => {
|
||||
await ctx?.close();
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await ctx.clearLimits();
|
||||
});
|
||||
|
||||
it('issues an immutable merchandise snapshot and replays after list archival', async () => {
|
||||
const accountId = await verifiedAccount();
|
||||
const { listId, variantId, sku } = await activeList(accountId);
|
||||
const input = issueInput(accountId, listId, variantId);
|
||||
const issued = await ctx
|
||||
.api()
|
||||
.post(quotes)
|
||||
.auth(ctx.token, auth)
|
||||
.send(input)
|
||||
.expect(201);
|
||||
expect(issued.body).toMatchObject({
|
||||
status: 'ISSUED',
|
||||
currency: 'INR',
|
||||
merchandiseTotal: '3303.00',
|
||||
accountSnapshot: { legalName: 'Quotation Partner Limited' },
|
||||
lines: [
|
||||
{
|
||||
variantId,
|
||||
sku,
|
||||
quantity: 12,
|
||||
minQuantity: 12,
|
||||
unitPrice: '275.25',
|
||||
lineTotal: '3303.00',
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(issued.body.number).toMatch(/^BQ-[A-F0-9]{20}$/);
|
||||
await ctx
|
||||
.api()
|
||||
.post(`/api/v1/b2b/price-lists/${listId}/archive`)
|
||||
.auth(ctx.token, auth)
|
||||
.expect(201);
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.post(quotes)
|
||||
.auth(ctx.token, auth)
|
||||
.send(input)
|
||||
.expect(201)
|
||||
).body.id,
|
||||
).toBe(issued.body.id);
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.get(`${quotes}/${issued.body.id}`)
|
||||
.auth(ctx.token, auth)
|
||||
.expect(200)
|
||||
).body.lines[0].unitPrice,
|
||||
).toBe('275.25');
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.post(quotes)
|
||||
.auth(ctx.token, auth)
|
||||
.send({ ...input, customerReference: 'Changed' })
|
||||
.expect(409)
|
||||
).body.code,
|
||||
).toBe('B2B_QUOTE_REPLAY_CONFLICT');
|
||||
});
|
||||
|
||||
it('enforces verified active terms, expiry, MOQ, tenant scope, and permissions', async () => {
|
||||
const unverified = await account();
|
||||
const accountId = await verifiedAccount();
|
||||
const { listId, variantId } = await activeList(accountId);
|
||||
const input = issueInput(accountId, listId, variantId);
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.post(quotes)
|
||||
.auth(ctx.token, auth)
|
||||
.send({ ...input, accountId: unverified })
|
||||
.expect(409)
|
||||
).body.code,
|
||||
).toBe('B2B_QUOTE_ACCOUNT_UNVERIFIED');
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.post(quotes)
|
||||
.auth(ctx.token, auth)
|
||||
.send({ ...input, lines: [{ variantId, quantity: 11 }] })
|
||||
.expect(409)
|
||||
).body.code,
|
||||
).toBe('B2B_PRICE_MINIMUM_QUANTITY');
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.post(quotes)
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
...input,
|
||||
expiresAt: new Date(Date.now() - 1000).toISOString(),
|
||||
})
|
||||
.expect(400)
|
||||
).body.code,
|
||||
).toBe('B2B_QUOTE_EXPIRY_INVALID');
|
||||
const issued = await ctx
|
||||
.api()
|
||||
.post(quotes)
|
||||
.auth(ctx.token, auth)
|
||||
.send(input)
|
||||
.expect(201);
|
||||
const other = await secondActor(ctx, false, ['b2b.quote.read']);
|
||||
await ctx
|
||||
.api()
|
||||
.get(`${quotes}/${issued.body.id}`)
|
||||
.auth(other.token, auth)
|
||||
.expect(404);
|
||||
const reader = await secondActor(ctx, true, ['b2b.quote.read']);
|
||||
await ctx
|
||||
.api()
|
||||
.post(quotes)
|
||||
.auth(reader.token, auth)
|
||||
.send(issueInput(accountId, listId, variantId))
|
||||
.expect(403);
|
||||
});
|
||||
|
||||
it('records one staff-attested response and rejects changed or later responses', async () => {
|
||||
const accountId = await verifiedAccount();
|
||||
const { listId, variantId } = await activeList(accountId);
|
||||
const issued = await ctx
|
||||
.api()
|
||||
.post(quotes)
|
||||
.auth(ctx.token, auth)
|
||||
.send(issueInput(accountId, listId, variantId))
|
||||
.expect(201);
|
||||
const route = `${quotes}/${issued.body.id}/response`;
|
||||
const body = {
|
||||
kind: 'ACCEPTED',
|
||||
note: 'Customer accepted by email',
|
||||
idempotencyKey: randomUUID(),
|
||||
};
|
||||
const accepted = await ctx
|
||||
.api()
|
||||
.post(route)
|
||||
.auth(ctx.token, auth)
|
||||
.send(body)
|
||||
.expect(201);
|
||||
expect(accepted.body).toMatchObject({
|
||||
status: 'ACCEPTED',
|
||||
response: { kind: 'ACCEPTED', note: body.note },
|
||||
});
|
||||
expect(
|
||||
(await ctx.api().post(route).auth(ctx.token, auth).send(body).expect(201))
|
||||
.body.response.id,
|
||||
).toBe(accepted.body.response.id);
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.post(route)
|
||||
.auth(ctx.token, auth)
|
||||
.send({ ...body, note: 'Changed note' })
|
||||
.expect(409)
|
||||
).body.code,
|
||||
).toBe('B2B_QUOTE_RESPONSE_REPLAY_CONFLICT');
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.post(route)
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
kind: 'WITHDRAWN',
|
||||
note: 'Staff withdrawal',
|
||||
idempotencyKey: randomUUID(),
|
||||
})
|
||||
.expect(409)
|
||||
).body.code,
|
||||
).toBe('B2B_QUOTE_ALREADY_RESOLVED');
|
||||
const list = await ctx
|
||||
.api()
|
||||
.get(`${quotes}?accountId=${accountId}`)
|
||||
.auth(ctx.token, auth)
|
||||
.expect(200);
|
||||
expect(list.body).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ id: issued.body.id, status: 'ACCEPTED' }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import {
|
||||
assertQuoteLimits,
|
||||
prepareQuoteCommand,
|
||||
} from '../src/b2b/quote-command';
|
||||
|
||||
describe('B2B quotation command', () => {
|
||||
const accountId = randomUUID();
|
||||
const priceListId = randomUUID();
|
||||
const first = randomUUID();
|
||||
const second = randomUUID();
|
||||
const base = {
|
||||
accountId,
|
||||
priceListId,
|
||||
expiresAt: '2026-12-01T10:00:00+05:30',
|
||||
customerReference: null,
|
||||
idempotencyKey: randomUUID(),
|
||||
lines: [
|
||||
{ variantId: first, quantity: 10 },
|
||||
{ variantId: second, quantity: 5 },
|
||||
],
|
||||
};
|
||||
|
||||
it('hashes equivalent expiry offsets and line order identically', () => {
|
||||
const original = prepareQuoteCommand(base);
|
||||
const reordered = prepareQuoteCommand({
|
||||
...base,
|
||||
expiresAt: '2026-12-01T04:30:00Z',
|
||||
lines: [...base.lines].reverse(),
|
||||
});
|
||||
expect(reordered.requestHash).toBe(original.requestHash);
|
||||
expect(reordered.lines).toEqual(original.lines);
|
||||
});
|
||||
|
||||
it('rejects expired, distant, and oversized monetary quotes', () => {
|
||||
expect(() =>
|
||||
assertQuoteLimits(new Date(Date.now() - 1000), ['1.00']),
|
||||
).toThrow(expect.objectContaining({ code: 'B2B_QUOTE_EXPIRY_INVALID' }));
|
||||
expect(() =>
|
||||
assertQuoteLimits(new Date(Date.now() + 91 * 86400000), ['1.00']),
|
||||
).toThrow(expect.objectContaining({ code: 'B2B_QUOTE_EXPIRY_INVALID' }));
|
||||
expect(() =>
|
||||
assertQuoteLimits(new Date(Date.now() + 86400000), [
|
||||
'10000000000000000.00',
|
||||
]),
|
||||
).toThrow(expect.objectContaining({ code: 'B2B_QUOTE_AMOUNT_LIMIT' }));
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue