feat(b2b): add partner price lists and minimum quantities
This commit is contained in:
parent
7577fb98f4
commit
5908d68a9e
|
|
@ -57,3 +57,4 @@ Finished-goods receipts: see [Phase 2Q API guide](docs/finished-goods-receipt-ap
|
||||||
Material warehouse transfers: see [Phase 2R API guide](docs/material-transfers-api.md).
|
Material warehouse transfers: see [Phase 2R API guide](docs/material-transfers-api.md).
|
||||||
Manual material-stock adjustments: see [Phase 2S API guide](docs/material-adjustments-api.md).
|
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).
|
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).
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,20 @@
|
||||||
|
# B2B partner price lists and minimum quantities (Phase 3B)
|
||||||
|
|
||||||
|
Staff create organization-scoped price lists for a business account. A draft can be edited; activating it requires a verified account, at least one eligible variant, and no other active list for the same account and currency. Active and archived terms cannot be changed. Archive the current list before activating its replacement.
|
||||||
|
|
||||||
|
| Method | Route | Permission | Purpose |
|
||||||
|
| ------ | ---------------------------------------------- | ------------------ | ---------------------------------------------------------------------- |
|
||||||
|
| GET | `/api/v1/b2b/accounts/:accountId/price-lists` | `b2b.price.read` | List the account's lists with `limit`, `offset`, and optional `status` |
|
||||||
|
| POST | `/api/v1/b2b/accounts/:accountId/price-lists` | `b2b.price.manage` | Create a draft with `name` and `currency` |
|
||||||
|
| GET | `/api/v1/b2b/price-lists/:id` | `b2b.price.read` | Read the list and its variant terms |
|
||||||
|
| PUT | `/api/v1/b2b/price-lists/:id/items/:variantId` | `b2b.price.manage` | Set draft `unitPrice` and `minQuantity` |
|
||||||
|
| DELETE | `/api/v1/b2b/price-lists/:id/items/:variantId` | `b2b.price.manage` | Remove a draft item |
|
||||||
|
| POST | `/api/v1/b2b/price-lists/:id/activate` | `b2b.price.manage` | Freeze and activate the list |
|
||||||
|
| POST | `/api/v1/b2b/price-lists/:id/archive` | `b2b.price.manage` | Retire the active list |
|
||||||
|
| POST | `/api/v1/b2b/price-lists/:id/price-check` | `b2b.price.read` | Check quantities and preview merchandise total |
|
||||||
|
|
||||||
|
Supported currencies are INR, USD, EUR, and GBP. `unitPrice` is a positive decimal string with exactly two fractional digits; `minQuantity` is an integer from 1 to 1,000,000. A variant must be active, belong to a published product in the same organization, and use the list currency. A price check takes `{ "lines": [{ "variantId": "<UUID>", "quantity": 12 }] }` with 1–100 distinct variants. It returns each unit price, minimum, line total, currency, and merchandise total. The check revalidates variant eligibility even after activation.
|
||||||
|
|
||||||
|
This merchandise preview excludes stock, discounts, tax, shipping, credit, and payment terms. It does not create a quotation or order. Those rules belong to later B2B phases and must snapshot the selected terms before an order can use them. Existing retail checkout prices are unchanged.
|
||||||
|
|
||||||
|
Run `pnpm db:deploy` before starting the updated API. The migration grants `b2b.price.read` and `b2b.price.manage` to existing system Owner roles; grant custom roles explicitly.
|
||||||
|
|
@ -39,6 +39,7 @@ 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.
|
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.
|
- 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.
|
||||||
|
|
||||||
## Phase 4: Growth channels
|
## Phase 4: Growth channels
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,12 @@ enum BusinessVerificationKind {
|
||||||
REJECTED
|
REJECTED
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum B2bPriceListStatus {
|
||||||
|
DRAFT
|
||||||
|
ACTIVE
|
||||||
|
ARCHIVED
|
||||||
|
}
|
||||||
|
|
||||||
model BusinessAccount {
|
model BusinessAccount {
|
||||||
id String @id @default(uuid()) @db.Uuid
|
id String @id @default(uuid()) @db.Uuid
|
||||||
organizationId String @map("organization_id") @db.Uuid
|
organizationId String @map("organization_id") @db.Uuid
|
||||||
|
|
@ -26,6 +32,7 @@ model BusinessAccount {
|
||||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
|
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
|
||||||
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
events BusinessVerificationEvent[]
|
events BusinessVerificationEvent[]
|
||||||
|
priceLists B2bPriceList[]
|
||||||
@@unique([organizationId, code])
|
@@unique([organizationId, code])
|
||||||
@@unique([organizationId, countryCode, registrationNumber])
|
@@unique([organizationId, countryCode, registrationNumber])
|
||||||
@@unique([id, organizationId])
|
@@unique([id, organizationId])
|
||||||
|
|
@ -33,6 +40,44 @@ model BusinessAccount {
|
||||||
@@map("business_accounts")
|
@@map("business_accounts")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
model B2bPriceList {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
organizationId String @map("organization_id") @db.Uuid
|
||||||
|
accountId String @map("account_id") @db.Uuid
|
||||||
|
createdById String @map("created_by_id") @db.Uuid
|
||||||
|
name String @db.VarChar(100)
|
||||||
|
currency String @db.Char(3)
|
||||||
|
status B2bPriceListStatus @default(DRAFT)
|
||||||
|
activeSlot Boolean? @map("active_slot")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(3)
|
||||||
|
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
|
||||||
|
account BusinessAccount @relation(fields: [accountId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
|
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
|
items B2bPriceListItem[]
|
||||||
|
@@unique([id, organizationId])
|
||||||
|
@@unique([organizationId, accountId, currency, activeSlot])
|
||||||
|
@@index([organizationId, accountId, status, createdAt, id])
|
||||||
|
@@map("b2b_price_lists")
|
||||||
|
}
|
||||||
|
|
||||||
|
model B2bPriceListItem {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
organizationId String @map("organization_id") @db.Uuid
|
||||||
|
priceListId String @map("price_list_id") @db.Uuid
|
||||||
|
variantId String @map("variant_id") @db.Uuid
|
||||||
|
unitPrice Decimal @map("unit_price") @db.Decimal(12,2)
|
||||||
|
minQuantity Int @map("min_quantity")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(3)
|
||||||
|
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
|
||||||
|
priceList B2bPriceList @relation(fields: [priceListId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
|
variant ProductVariant @relation(fields: [variantId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
|
@@unique([priceListId, variantId])
|
||||||
|
@@index([organizationId, priceListId, id])
|
||||||
|
@@map("b2b_price_list_items")
|
||||||
|
}
|
||||||
|
|
||||||
model BusinessVerificationEvent {
|
model BusinessVerificationEvent {
|
||||||
id String @id @default(uuid()) @db.Uuid
|
id String @id @default(uuid()) @db.Uuid
|
||||||
organizationId String @map("organization_id") @db.Uuid
|
organizationId String @map("organization_id") @db.Uuid
|
||||||
|
|
|
||||||
|
|
@ -38,6 +38,7 @@ model ProductVariant {
|
||||||
cartLines CartLine[]
|
cartLines CartLine[]
|
||||||
orderLines OrderLine[]
|
orderLines OrderLine[]
|
||||||
boms ProductBom[]
|
boms ProductBom[]
|
||||||
|
b2bPriceListItems B2bPriceListItem[]
|
||||||
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])
|
||||||
|
|
|
||||||
|
|
@ -33,5 +33,6 @@
|
||||||
"20260929203400_finished_goods_receipt": "7745c23f9037d7bb0de7bdfaf94610794b83213f041583c0f9678c4e837f53f0",
|
"20260929203400_finished_goods_receipt": "7745c23f9037d7bb0de7bdfaf94610794b83213f041583c0f9678c4e837f53f0",
|
||||||
"20260930002200_material_warehouse_transfers": "0f193ecd186971e19fdc823944312be70646b348a1a846ab41703d269936e21a",
|
"20260930002200_material_warehouse_transfers": "0f193ecd186971e19fdc823944312be70646b348a1a846ab41703d269936e21a",
|
||||||
"20260930003800_material_stock_adjustments": "2002d6826f34da5a999a0098a7191aa00f5fdc4ca54446b776270021d48ef5eb",
|
"20260930003800_material_stock_adjustments": "2002d6826f34da5a999a0098a7191aa00f5fdc4ca54446b776270021d48ef5eb",
|
||||||
"20260930010000_b2b_business_verification": "1ab6537ff21436ce3421024f6f61e647c2c82a35a09a769833c6b82cdccca32b"
|
"20260930010000_b2b_business_verification": "1ab6537ff21436ce3421024f6f61e647c2c82a35a09a769833c6b82cdccca32b",
|
||||||
|
"20260930011800_b2b_price_lists": "c2f29a61c6fee93cbffb9d67654c323b2894b3aad7bb296b514f46b623db62d9"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,99 @@
|
||||||
|
CREATE TYPE "B2bPriceListStatus" AS ENUM ('DRAFT', 'ACTIVE', 'ARCHIVED');
|
||||||
|
|
||||||
|
CREATE TABLE "b2b_price_lists" (
|
||||||
|
"id" UUID NOT NULL PRIMARY KEY,
|
||||||
|
"organization_id" UUID NOT NULL,
|
||||||
|
"account_id" UUID NOT NULL,
|
||||||
|
"created_by_id" UUID NOT NULL,
|
||||||
|
"name" VARCHAR(100) NOT NULL,
|
||||||
|
"currency" CHAR(3) NOT NULL,
|
||||||
|
"status" "B2bPriceListStatus" NOT NULL DEFAULT 'DRAFT',
|
||||||
|
"active_slot" BOOLEAN,
|
||||||
|
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMPTZ(3) NOT NULL,
|
||||||
|
CONSTRAINT "b2b_price_lists_currency" CHECK ("currency" IN ('INR', 'USD', 'EUR', 'GBP')),
|
||||||
|
CONSTRAINT "b2b_price_lists_active_slot" CHECK (
|
||||||
|
("status" = 'ACTIVE' AND "active_slot" IS TRUE) OR
|
||||||
|
("status" <> 'ACTIVE' AND "active_slot" IS NULL)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX "b2b_price_lists_id_organization_id_key" ON "b2b_price_lists"("id", "organization_id");
|
||||||
|
CREATE UNIQUE INDEX "b2b_price_lists_organization_id_account_id_currency_active__key" ON "b2b_price_lists"("organization_id", "account_id", "currency", "active_slot");
|
||||||
|
CREATE INDEX "b2b_price_lists_organization_id_account_id_status_created_a_idx" ON "b2b_price_lists"("organization_id", "account_id", "status", "created_at", "id");
|
||||||
|
ALTER TABLE "b2b_price_lists" ADD CONSTRAINT "b2b_price_lists_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "b2b_price_lists" ADD CONSTRAINT "b2b_price_lists_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_price_lists" ADD CONSTRAINT "b2b_price_lists_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_price_list_items" (
|
||||||
|
"id" UUID NOT NULL PRIMARY KEY,
|
||||||
|
"organization_id" UUID NOT NULL,
|
||||||
|
"price_list_id" UUID NOT NULL,
|
||||||
|
"variant_id" UUID NOT NULL,
|
||||||
|
"unit_price" DECIMAL(12,2) NOT NULL,
|
||||||
|
"min_quantity" INTEGER NOT NULL,
|
||||||
|
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMPTZ(3) NOT NULL,
|
||||||
|
CONSTRAINT "b2b_price_list_items_price" CHECK ("unit_price" > 0),
|
||||||
|
CONSTRAINT "b2b_price_list_items_min_quantity" CHECK ("min_quantity" BETWEEN 1 AND 1000000)
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX "b2b_price_list_items_price_list_id_variant_id_key" ON "b2b_price_list_items"("price_list_id", "variant_id");
|
||||||
|
CREATE INDEX "b2b_price_list_items_organization_id_price_list_id_id_idx" ON "b2b_price_list_items"("organization_id", "price_list_id", "id");
|
||||||
|
ALTER TABLE "b2b_price_list_items" ADD CONSTRAINT "b2b_price_list_items_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "b2b_price_list_items" ADD CONSTRAINT "b2b_price_list_items_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_price_list_items" ADD CONSTRAINT "b2b_price_list_items_variant_id_organization_id_fkey" FOREIGN KEY ("variant_id", "organization_id") REFERENCES "product_variants"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
CREATE FUNCTION guard_b2b_price_list() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE verified BOOLEAN;
|
||||||
|
BEGIN
|
||||||
|
IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'B2B price lists cannot be deleted'; END IF;
|
||||||
|
IF TG_OP = 'INSERT' THEN RETURN NEW; END IF;
|
||||||
|
IF (NEW.id, NEW.organization_id, NEW.account_id, NEW.created_by_id, NEW.name, NEW.currency, NEW.created_at)
|
||||||
|
IS DISTINCT FROM (OLD.id, OLD.organization_id, OLD.account_id, OLD.created_by_id, OLD.name, OLD.currency, OLD.created_at)
|
||||||
|
THEN RAISE EXCEPTION 'B2B price list identity and terms are immutable'; END IF;
|
||||||
|
IF OLD.status = 'DRAFT' AND NEW.status = 'ACTIVE' THEN
|
||||||
|
SELECT kind = 'APPROVED' INTO verified FROM business_verification_events
|
||||||
|
WHERE account_id = NEW.account_id ORDER BY sequence DESC LIMIT 1;
|
||||||
|
IF COALESCE(verified, FALSE) IS FALSE THEN RAISE EXCEPTION 'Business account is not verified'; END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM b2b_price_list_items WHERE price_list_id = NEW.id) THEN
|
||||||
|
RAISE EXCEPTION 'B2B price list has no items';
|
||||||
|
END IF;
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM b2b_price_list_items i
|
||||||
|
JOIN product_variants v ON v.id = i.variant_id
|
||||||
|
JOIN products p ON p.id = v.product_id
|
||||||
|
WHERE i.price_list_id = NEW.id AND (NOT v.active OR p.status <> 'PUBLISHED' OR v.currency <> NEW.currency)
|
||||||
|
) THEN RAISE EXCEPTION 'B2B price list contains ineligible variants'; END IF;
|
||||||
|
ELSIF NOT (OLD.status = 'ACTIVE' AND NEW.status = 'ARCHIVED') THEN
|
||||||
|
RAISE EXCEPTION 'B2B price list transition invalid';
|
||||||
|
END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
CREATE TRIGGER b2b_price_lists_guard BEFORE UPDATE OR DELETE ON b2b_price_lists FOR EACH ROW EXECUTE FUNCTION guard_b2b_price_list();
|
||||||
|
|
||||||
|
CREATE FUNCTION guard_b2b_price_list_item() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE list_status "B2bPriceListStatus";
|
||||||
|
DECLARE list_currency CHAR(3);
|
||||||
|
BEGIN
|
||||||
|
IF TG_OP = 'DELETE' THEN
|
||||||
|
SELECT status INTO list_status FROM b2b_price_lists WHERE id = OLD.price_list_id;
|
||||||
|
IF list_status <> 'DRAFT' THEN RAISE EXCEPTION 'Active or archived price list items are immutable'; END IF;
|
||||||
|
RETURN OLD;
|
||||||
|
END IF;
|
||||||
|
SELECT status, currency INTO list_status, list_currency FROM b2b_price_lists WHERE id = NEW.price_list_id AND organization_id = NEW.organization_id;
|
||||||
|
IF list_status <> 'DRAFT' THEN RAISE EXCEPTION 'Active or archived price list items are immutable'; END IF;
|
||||||
|
IF TG_OP = 'UPDATE' AND (NEW.id, NEW.organization_id, NEW.price_list_id, NEW.variant_id, NEW.created_at)
|
||||||
|
IS DISTINCT FROM (OLD.id, OLD.organization_id, OLD.price_list_id, OLD.variant_id, OLD.created_at)
|
||||||
|
THEN RAISE EXCEPTION 'B2B price list item identity is immutable'; END IF;
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM product_variants v JOIN products p ON p.id = v.product_id
|
||||||
|
WHERE v.id = NEW.variant_id AND v.organization_id = NEW.organization_id
|
||||||
|
AND v.active AND p.status = 'PUBLISHED' AND v.currency = list_currency
|
||||||
|
) THEN RAISE EXCEPTION 'Variant is ineligible for B2B price list'; END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
CREATE TRIGGER b2b_price_list_items_guard BEFORE INSERT OR UPDATE OR DELETE ON b2b_price_list_items FOR EACH ROW EXECUTE FUNCTION guard_b2b_price_list_item();
|
||||||
|
|
||||||
|
UPDATE "roles" SET "permissions" = ARRAY(SELECT DISTINCT unnest("permissions" || ARRAY['b2b.price.read', 'b2b.price.manage']))
|
||||||
|
WHERE "is_system" = true AND "name" = 'Owner';
|
||||||
|
|
@ -53,6 +53,8 @@ model Organization {
|
||||||
materialStockAdjustments MaterialStockAdjustment[]
|
materialStockAdjustments MaterialStockAdjustment[]
|
||||||
businessAccounts BusinessAccount[]
|
businessAccounts BusinessAccount[]
|
||||||
businessVerificationEvents BusinessVerificationEvent[]
|
businessVerificationEvents BusinessVerificationEvent[]
|
||||||
|
b2bPriceLists B2bPriceList[]
|
||||||
|
b2bPriceListItems B2bPriceListItem[]
|
||||||
@@map("organizations")
|
@@map("organizations")
|
||||||
}
|
}
|
||||||
model User {
|
model User {
|
||||||
|
|
@ -96,6 +98,7 @@ model User {
|
||||||
materialStockAdjustments MaterialStockAdjustment[]
|
materialStockAdjustments MaterialStockAdjustment[]
|
||||||
businessAccounts BusinessAccount[]
|
businessAccounts BusinessAccount[]
|
||||||
businessVerificationEvents BusinessVerificationEvent[]
|
businessVerificationEvents BusinessVerificationEvent[]
|
||||||
|
b2bPriceLists B2bPriceList[]
|
||||||
stockEntries StockLedger[]
|
stockEntries StockLedger[]
|
||||||
stockReservations StockReservation[]
|
stockReservations StockReservation[]
|
||||||
carts Cart[]
|
carts Cart[]
|
||||||
|
|
|
||||||
|
|
@ -4,10 +4,23 @@ import { IdentityModule } from '../identity/identity.module';
|
||||||
import { BusinessController } from './business.controller';
|
import { BusinessController } from './business.controller';
|
||||||
import { BusinessStore } from './business.store';
|
import { BusinessStore } from './business.store';
|
||||||
import { VerificationStore } from './verification.store';
|
import { VerificationStore } from './verification.store';
|
||||||
|
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';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [DatabaseModule, IdentityModule],
|
imports: [DatabaseModule, IdentityModule],
|
||||||
controllers: [BusinessController],
|
controllers: [
|
||||||
providers: [BusinessStore, VerificationStore],
|
BusinessController,
|
||||||
|
PriceListsController,
|
||||||
|
PriceListItemsController,
|
||||||
|
],
|
||||||
|
providers: [
|
||||||
|
BusinessStore,
|
||||||
|
VerificationStore,
|
||||||
|
PriceListStore,
|
||||||
|
PriceListItemStore,
|
||||||
|
],
|
||||||
})
|
})
|
||||||
export class B2bModule {}
|
export class B2bModule {}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,37 @@
|
||||||
|
import { AppError } from '../common/errors/app-error';
|
||||||
|
import {
|
||||||
|
Prisma,
|
||||||
|
type B2bPriceList,
|
||||||
|
type B2bPriceListItem,
|
||||||
|
} from '../generated/prisma/client';
|
||||||
|
import type { PriceCheckInput } from './price-list.schemas';
|
||||||
|
|
||||||
|
type PriceTerms = Pick<B2bPriceList, 'id' | 'currency'> & {
|
||||||
|
items: Pick<B2bPriceListItem, 'variantId' | 'minQuantity' | 'unitPrice'>[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export function calculatePriceCheck(list: PriceTerms, input: PriceCheckInput) {
|
||||||
|
const items = new Map(list.items.map((item) => [item.variantId, item]));
|
||||||
|
let total = new Prisma.Decimal(0);
|
||||||
|
const lines = input.lines.map(({ variantId, quantity }) => {
|
||||||
|
const item = items.get(variantId);
|
||||||
|
if (!item) throw new AppError('B2B_PRICE_ITEM_NOT_FOUND');
|
||||||
|
if (quantity < item.minQuantity)
|
||||||
|
throw new AppError('B2B_PRICE_MINIMUM_QUANTITY');
|
||||||
|
const lineTotal = item.unitPrice.mul(quantity);
|
||||||
|
total = total.add(lineTotal);
|
||||||
|
return {
|
||||||
|
variantId,
|
||||||
|
quantity,
|
||||||
|
minQuantity: item.minQuantity,
|
||||||
|
unitPrice: item.unitPrice.toFixed(2),
|
||||||
|
lineTotal: lineTotal.toFixed(2),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
priceListId: list.id,
|
||||||
|
currency: list.currency,
|
||||||
|
lines,
|
||||||
|
merchandiseTotal: total.toFixed(2),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,98 @@
|
||||||
|
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 {
|
||||||
|
assertEligiblePriceVariants,
|
||||||
|
requirePriceList,
|
||||||
|
} from './price-list.helpers';
|
||||||
|
import { calculatePriceCheck } from './price-check';
|
||||||
|
import type { PriceCheckInput, PriceListItemInput } from './price-list.schemas';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PriceListItemStore {
|
||||||
|
constructor(
|
||||||
|
private readonly db: DatabaseService,
|
||||||
|
private readonly access: AccessStore,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
save(
|
||||||
|
actor: Principal,
|
||||||
|
listId: string,
|
||||||
|
variantId: string,
|
||||||
|
input: PriceListItemInput,
|
||||||
|
) {
|
||||||
|
return this.access.mutate(actor, 'b2b.price.manage', async (tx) => {
|
||||||
|
const list = await requirePriceList(tx, actor.organizationId, listId);
|
||||||
|
if (list.status !== 'DRAFT')
|
||||||
|
throw new AppError('B2B_PRICE_LIST_DRAFT_REQUIRED');
|
||||||
|
const variant = await tx.productVariant.findFirst({
|
||||||
|
where: { id: variantId, organizationId: actor.organizationId },
|
||||||
|
include: { product: true },
|
||||||
|
});
|
||||||
|
if (!variant) throw new AppError('B2B_PRICE_VARIANT_NOT_FOUND');
|
||||||
|
if (!variant.active || variant.product.status !== 'PUBLISHED')
|
||||||
|
throw new AppError('B2B_PRICE_VARIANT_INELIGIBLE');
|
||||||
|
if (variant.currency !== list.currency)
|
||||||
|
throw new AppError('B2B_PRICE_CURRENCY_MISMATCH');
|
||||||
|
const item = await tx.b2bPriceListItem.upsert({
|
||||||
|
where: { priceListId_variantId: { priceListId: listId, variantId } },
|
||||||
|
create: {
|
||||||
|
...input,
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
priceListId: listId,
|
||||||
|
variantId,
|
||||||
|
},
|
||||||
|
update: input,
|
||||||
|
});
|
||||||
|
await recordAudit(
|
||||||
|
tx,
|
||||||
|
actor.organizationId,
|
||||||
|
actor.userId,
|
||||||
|
'b2b_price_list.item.saved',
|
||||||
|
item.id,
|
||||||
|
);
|
||||||
|
return item;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
remove(actor: Principal, listId: string, variantId: string) {
|
||||||
|
return this.access.mutate(actor, 'b2b.price.manage', async (tx) => {
|
||||||
|
const list = await requirePriceList(tx, actor.organizationId, listId);
|
||||||
|
if (list.status !== 'DRAFT')
|
||||||
|
throw new AppError('B2B_PRICE_LIST_DRAFT_REQUIRED');
|
||||||
|
const item = await tx.b2bPriceListItem.findFirst({
|
||||||
|
where: {
|
||||||
|
priceListId: listId,
|
||||||
|
variantId,
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!item) throw new AppError('B2B_PRICE_ITEM_NOT_FOUND');
|
||||||
|
await tx.b2bPriceListItem.delete({ where: { id: item.id } });
|
||||||
|
await recordAudit(
|
||||||
|
tx,
|
||||||
|
actor.organizationId,
|
||||||
|
actor.userId,
|
||||||
|
'b2b_price_list.item.removed',
|
||||||
|
item.id,
|
||||||
|
);
|
||||||
|
return { removed: true };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async check(actor: Principal, listId: string, input: PriceCheckInput) {
|
||||||
|
const list = await requirePriceList(this.db, actor.organizationId, listId);
|
||||||
|
if (list.status !== 'ACTIVE')
|
||||||
|
throw new AppError('B2B_PRICE_LIST_ACTIVE_REQUIRED');
|
||||||
|
await assertEligiblePriceVariants(
|
||||||
|
this.db,
|
||||||
|
actor.organizationId,
|
||||||
|
list.currency,
|
||||||
|
list.items,
|
||||||
|
);
|
||||||
|
return calculatePriceCheck(list, input);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,58 @@
|
||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Param,
|
||||||
|
ParseUUIDPipe,
|
||||||
|
Post,
|
||||||
|
Put,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { SchemaPipe } from '../common/validation.pipe';
|
||||||
|
import {
|
||||||
|
CurrentPrincipal,
|
||||||
|
RequirePermission,
|
||||||
|
} from '../identity/access.decorator';
|
||||||
|
import type { Principal } from '../identity/identity.types';
|
||||||
|
import { PriceListItemStore } from './price-list-item.store';
|
||||||
|
import {
|
||||||
|
priceCheckSchema,
|
||||||
|
priceListItemSchema,
|
||||||
|
type PriceCheckInput,
|
||||||
|
type PriceListItemInput,
|
||||||
|
} from './price-list.schemas';
|
||||||
|
|
||||||
|
@Controller('b2b/price-lists/:id')
|
||||||
|
export class PriceListItemsController {
|
||||||
|
constructor(private readonly items: PriceListItemStore) {}
|
||||||
|
|
||||||
|
@Put('items/:variantId')
|
||||||
|
@RequirePermission('b2b.price.manage')
|
||||||
|
save(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
@Param('variantId', ParseUUIDPipe) variantId: string,
|
||||||
|
@Body(new SchemaPipe(priceListItemSchema)) input: PriceListItemInput,
|
||||||
|
) {
|
||||||
|
return this.items.save(actor, id, variantId, input);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete('items/:variantId')
|
||||||
|
@RequirePermission('b2b.price.manage')
|
||||||
|
remove(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
@Param('variantId', ParseUUIDPipe) variantId: string,
|
||||||
|
) {
|
||||||
|
return this.items.remove(actor, id, variantId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('price-check')
|
||||||
|
@RequirePermission('b2b.price.read')
|
||||||
|
check(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
@Body(new SchemaPipe(priceCheckSchema)) input: PriceCheckInput,
|
||||||
|
) {
|
||||||
|
return this.items.check(actor, id, input);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,51 @@
|
||||||
|
import { AppError } from '../common/errors/app-error';
|
||||||
|
import type { Prisma } from '../generated/prisma/client';
|
||||||
|
import type { DatabaseService } from '../database/database.service';
|
||||||
|
|
||||||
|
type Db = Prisma.TransactionClient | DatabaseService;
|
||||||
|
|
||||||
|
export async function requirePriceList(
|
||||||
|
db: Db,
|
||||||
|
organizationId: string,
|
||||||
|
id: string,
|
||||||
|
) {
|
||||||
|
const list = await db.b2bPriceList.findFirst({
|
||||||
|
where: { id, organizationId },
|
||||||
|
include: { items: { orderBy: [{ createdAt: 'asc' }, { id: 'asc' }] } },
|
||||||
|
});
|
||||||
|
if (!list) throw new AppError('B2B_PRICE_LIST_NOT_FOUND');
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function requireBusinessAccount(
|
||||||
|
db: Db,
|
||||||
|
organizationId: string,
|
||||||
|
id: string,
|
||||||
|
) {
|
||||||
|
const account = await db.businessAccount.findFirst({
|
||||||
|
where: { id, organizationId },
|
||||||
|
});
|
||||||
|
if (!account) throw new AppError('BUSINESS_ACCOUNT_NOT_FOUND');
|
||||||
|
return account;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function assertEligiblePriceVariants(
|
||||||
|
db: Db,
|
||||||
|
organizationId: string,
|
||||||
|
currency: string,
|
||||||
|
items: { variantId: string }[],
|
||||||
|
) {
|
||||||
|
const variants = await db.productVariant.findMany({
|
||||||
|
where: { id: { in: items.map((item) => item.variantId) }, organizationId },
|
||||||
|
include: { product: true },
|
||||||
|
});
|
||||||
|
if (
|
||||||
|
variants.length !== items.length ||
|
||||||
|
variants.some(
|
||||||
|
(variant) => !variant.active || variant.product.status !== 'PUBLISHED',
|
||||||
|
)
|
||||||
|
)
|
||||||
|
throw new AppError('B2B_PRICE_VARIANT_INELIGIBLE');
|
||||||
|
if (variants.some((variant) => variant.currency !== currency))
|
||||||
|
throw new AppError('B2B_PRICE_CURRENCY_MISMATCH');
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,52 @@
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { CURRENCIES } from '../common/currency';
|
||||||
|
import { text } from '../common/input';
|
||||||
|
import { pageSchema } from '../identity/identity.schemas';
|
||||||
|
|
||||||
|
export const createPriceListSchema = z
|
||||||
|
.object({
|
||||||
|
name: text(100),
|
||||||
|
currency: z.enum(CURRENCIES),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
|
||||||
|
export const priceListQuerySchema = pageSchema
|
||||||
|
.extend({
|
||||||
|
status: z.enum(['DRAFT', 'ACTIVE', 'ARCHIVED']).optional(),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
|
||||||
|
export const priceListItemSchema = z
|
||||||
|
.object({
|
||||||
|
unitPrice: z
|
||||||
|
.string()
|
||||||
|
.regex(/^(0|[1-9]\d{0,9})\.\d{2}$/)
|
||||||
|
.refine((value) => value !== '0.00'),
|
||||||
|
minQuantity: z.number().int().min(1).max(1000000),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
|
||||||
|
export const priceCheckSchema = z
|
||||||
|
.object({
|
||||||
|
lines: z
|
||||||
|
.array(
|
||||||
|
z
|
||||||
|
.object({
|
||||||
|
variantId: z.uuid(),
|
||||||
|
quantity: z.number().int().min(1).max(1000000),
|
||||||
|
})
|
||||||
|
.strict(),
|
||||||
|
)
|
||||||
|
.min(1)
|
||||||
|
.max(100)
|
||||||
|
.refine(
|
||||||
|
(lines) =>
|
||||||
|
new Set(lines.map((line) => line.variantId)).size === lines.length,
|
||||||
|
),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
|
||||||
|
export type CreatePriceListInput = z.infer<typeof createPriceListSchema>;
|
||||||
|
export type PriceListQuery = z.infer<typeof priceListQuerySchema>;
|
||||||
|
export type PriceListItemInput = z.infer<typeof priceListItemSchema>;
|
||||||
|
export type PriceCheckInput = z.infer<typeof priceCheckSchema>;
|
||||||
|
|
@ -0,0 +1,130 @@
|
||||||
|
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 {
|
||||||
|
assertEligiblePriceVariants,
|
||||||
|
requireBusinessAccount,
|
||||||
|
requirePriceList,
|
||||||
|
} from './price-list.helpers';
|
||||||
|
import type {
|
||||||
|
CreatePriceListInput,
|
||||||
|
PriceListQuery,
|
||||||
|
} from './price-list.schemas';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PriceListStore {
|
||||||
|
constructor(
|
||||||
|
private readonly db: DatabaseService,
|
||||||
|
private readonly access: AccessStore,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async list(actor: Principal, accountId: string, query: PriceListQuery) {
|
||||||
|
await requireBusinessAccount(this.db, actor.organizationId, accountId);
|
||||||
|
return this.db.b2bPriceList.findMany({
|
||||||
|
where: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
accountId,
|
||||||
|
...(query.status ? { status: query.status } : {}),
|
||||||
|
},
|
||||||
|
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||||
|
take: query.limit,
|
||||||
|
skip: query.offset,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
get(actor: Principal, id: string) {
|
||||||
|
return requirePriceList(this.db, actor.organizationId, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
create(actor: Principal, accountId: string, input: CreatePriceListInput) {
|
||||||
|
return this.access.mutate(actor, 'b2b.price.manage', async (tx) => {
|
||||||
|
await requireBusinessAccount(tx, actor.organizationId, accountId);
|
||||||
|
const list = await tx.b2bPriceList.create({
|
||||||
|
data: {
|
||||||
|
...input,
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
accountId,
|
||||||
|
createdById: actor.userId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await recordAudit(
|
||||||
|
tx,
|
||||||
|
actor.organizationId,
|
||||||
|
actor.userId,
|
||||||
|
'b2b_price_list.created',
|
||||||
|
list.id,
|
||||||
|
);
|
||||||
|
return list;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
activate(actor: Principal, id: string) {
|
||||||
|
return this.access.mutate(actor, 'b2b.price.manage', async (tx) => {
|
||||||
|
const list = await requirePriceList(tx, actor.organizationId, id);
|
||||||
|
if (list.status !== 'DRAFT')
|
||||||
|
throw new AppError('B2B_PRICE_LIST_DRAFT_REQUIRED');
|
||||||
|
const latest = await tx.businessVerificationEvent.findFirst({
|
||||||
|
where: {
|
||||||
|
accountId: list.accountId,
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
},
|
||||||
|
orderBy: { sequence: 'desc' },
|
||||||
|
});
|
||||||
|
if (latest?.kind !== 'APPROVED')
|
||||||
|
throw new AppError('B2B_PRICE_ACCOUNT_UNVERIFIED');
|
||||||
|
if (!list.items.length) throw new AppError('B2B_PRICE_LIST_EMPTY');
|
||||||
|
await assertEligiblePriceVariants(
|
||||||
|
tx,
|
||||||
|
actor.organizationId,
|
||||||
|
list.currency,
|
||||||
|
list.items,
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
await tx.b2bPriceList.findFirst({
|
||||||
|
where: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
accountId: list.accountId,
|
||||||
|
currency: list.currency,
|
||||||
|
status: 'ACTIVE',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
)
|
||||||
|
throw new AppError('B2B_PRICE_LIST_ALREADY_ACTIVE');
|
||||||
|
const active = await tx.b2bPriceList.update({
|
||||||
|
where: { id },
|
||||||
|
data: { status: 'ACTIVE', activeSlot: true },
|
||||||
|
});
|
||||||
|
await recordAudit(
|
||||||
|
tx,
|
||||||
|
actor.organizationId,
|
||||||
|
actor.userId,
|
||||||
|
'b2b_price_list.activated',
|
||||||
|
id,
|
||||||
|
);
|
||||||
|
return active;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
archive(actor: Principal, id: string) {
|
||||||
|
return this.access.mutate(actor, 'b2b.price.manage', async (tx) => {
|
||||||
|
const list = await requirePriceList(tx, actor.organizationId, id);
|
||||||
|
if (list.status !== 'ACTIVE')
|
||||||
|
throw new AppError('B2B_PRICE_LIST_ACTIVE_REQUIRED');
|
||||||
|
const archived = await tx.b2bPriceList.update({
|
||||||
|
where: { id },
|
||||||
|
data: { status: 'ARCHIVED', activeSlot: null },
|
||||||
|
});
|
||||||
|
await recordAudit(
|
||||||
|
tx,
|
||||||
|
actor.organizationId,
|
||||||
|
actor.userId,
|
||||||
|
'b2b_price_list.archived',
|
||||||
|
id,
|
||||||
|
);
|
||||||
|
return archived;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,74 @@
|
||||||
|
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 { PriceListStore } from './price-list.store';
|
||||||
|
import {
|
||||||
|
createPriceListSchema,
|
||||||
|
priceListQuerySchema,
|
||||||
|
type CreatePriceListInput,
|
||||||
|
type PriceListQuery,
|
||||||
|
} from './price-list.schemas';
|
||||||
|
|
||||||
|
@Controller('b2b')
|
||||||
|
export class PriceListsController {
|
||||||
|
constructor(private readonly lists: PriceListStore) {}
|
||||||
|
|
||||||
|
@Get('accounts/:accountId/price-lists')
|
||||||
|
@RequirePermission('b2b.price.read')
|
||||||
|
list(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Param('accountId', ParseUUIDPipe) accountId: string,
|
||||||
|
@Query(new SchemaPipe(priceListQuerySchema)) query: PriceListQuery,
|
||||||
|
) {
|
||||||
|
return this.lists.list(actor, accountId, query);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('accounts/:accountId/price-lists')
|
||||||
|
@RequirePermission('b2b.price.manage')
|
||||||
|
create(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Param('accountId', ParseUUIDPipe) accountId: string,
|
||||||
|
@Body(new SchemaPipe(createPriceListSchema)) input: CreatePriceListInput,
|
||||||
|
) {
|
||||||
|
return this.lists.create(actor, accountId, input);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('price-lists/:id')
|
||||||
|
@RequirePermission('b2b.price.read')
|
||||||
|
get(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
) {
|
||||||
|
return this.lists.get(actor, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('price-lists/:id/activate')
|
||||||
|
@RequirePermission('b2b.price.manage')
|
||||||
|
activate(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
) {
|
||||||
|
return this.lists.activate(actor, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('price-lists/:id/archive')
|
||||||
|
@RequirePermission('b2b.price.manage')
|
||||||
|
archive(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
) {
|
||||||
|
return this.lists.archive(actor, id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,57 @@
|
||||||
|
export const B2B_PRICE_ERRORS = {
|
||||||
|
B2B_PRICE_LIST_NOT_FOUND: [
|
||||||
|
404,
|
||||||
|
'B2B price list not found',
|
||||||
|
'Scoped B2B price list lookup failed',
|
||||||
|
],
|
||||||
|
B2B_PRICE_LIST_DRAFT_REQUIRED: [
|
||||||
|
409,
|
||||||
|
'Price list must be a draft for this change',
|
||||||
|
'B2B price list draft state required',
|
||||||
|
],
|
||||||
|
B2B_PRICE_LIST_ACTIVE_REQUIRED: [
|
||||||
|
409,
|
||||||
|
'Price list must be active for this action',
|
||||||
|
'B2B price list active state required',
|
||||||
|
],
|
||||||
|
B2B_PRICE_LIST_ALREADY_ACTIVE: [
|
||||||
|
409,
|
||||||
|
'An active price list already exists for this account and currency',
|
||||||
|
'B2B active price list overlap',
|
||||||
|
],
|
||||||
|
B2B_PRICE_LIST_EMPTY: [
|
||||||
|
409,
|
||||||
|
'Add at least one variant before activation',
|
||||||
|
'B2B price list activation has no items',
|
||||||
|
],
|
||||||
|
B2B_PRICE_ACCOUNT_UNVERIFIED: [
|
||||||
|
409,
|
||||||
|
'Business account must be verified before price activation',
|
||||||
|
'B2B price list account verification gate failed',
|
||||||
|
],
|
||||||
|
B2B_PRICE_VARIANT_NOT_FOUND: [
|
||||||
|
404,
|
||||||
|
'Variant not found for this B2B price list',
|
||||||
|
'B2B price list variant scoped lookup failed',
|
||||||
|
],
|
||||||
|
B2B_PRICE_VARIANT_INELIGIBLE: [
|
||||||
|
409,
|
||||||
|
'Variant must be active in a published product',
|
||||||
|
'B2B price list variant eligibility failed',
|
||||||
|
],
|
||||||
|
B2B_PRICE_CURRENCY_MISMATCH: [
|
||||||
|
409,
|
||||||
|
'Variant currency differs from price list currency',
|
||||||
|
'B2B price list variant currency mismatch',
|
||||||
|
],
|
||||||
|
B2B_PRICE_ITEM_NOT_FOUND: [
|
||||||
|
404,
|
||||||
|
'Variant is not on this price list',
|
||||||
|
'B2B price list item scoped lookup failed',
|
||||||
|
],
|
||||||
|
B2B_PRICE_MINIMUM_QUANTITY: [
|
||||||
|
409,
|
||||||
|
'Requested quantity is below the minimum',
|
||||||
|
'B2B price list minimum quantity gate failed',
|
||||||
|
],
|
||||||
|
} as const;
|
||||||
|
|
@ -3,11 +3,13 @@ import { OPERATIONS_ERRORS } from './operations-errors';
|
||||||
import { PLATFORM_ERRORS } from './platform-errors';
|
import { PLATFORM_ERRORS } from './platform-errors';
|
||||||
import { COMMERCE_ERRORS } from './commerce-errors';
|
import { COMMERCE_ERRORS } from './commerce-errors';
|
||||||
import { B2B_ERRORS } from './b2b-errors';
|
import { B2B_ERRORS } from './b2b-errors';
|
||||||
|
import { B2B_PRICE_ERRORS } from './b2b-price-errors';
|
||||||
export const ERRORS = {
|
export const ERRORS = {
|
||||||
...PLATFORM_ERRORS,
|
...PLATFORM_ERRORS,
|
||||||
...COMMERCE_ERRORS,
|
...COMMERCE_ERRORS,
|
||||||
...CHECKOUT_ERRORS,
|
...CHECKOUT_ERRORS,
|
||||||
...OPERATIONS_ERRORS,
|
...OPERATIONS_ERRORS,
|
||||||
...B2B_ERRORS,
|
...B2B_ERRORS,
|
||||||
|
...B2B_PRICE_ERRORS,
|
||||||
} as const;
|
} as const;
|
||||||
export type ErrorCode = keyof typeof ERRORS;
|
export type ErrorCode = keyof typeof ERRORS;
|
||||||
|
|
|
||||||
|
|
@ -39,5 +39,7 @@ export const PERMISSIONS = [
|
||||||
'b2b.read',
|
'b2b.read',
|
||||||
'b2b.manage',
|
'b2b.manage',
|
||||||
'b2b.verify',
|
'b2b.verify',
|
||||||
|
'b2b.price.read',
|
||||||
|
'b2b.price.manage',
|
||||||
] as const;
|
] as const;
|
||||||
export type Permission = (typeof PERMISSIONS)[number];
|
export type Permission = (typeof PERMISSIONS)[number];
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,92 @@
|
||||||
|
import { Prisma } from '../src/generated/prisma/client';
|
||||||
|
import { calculatePriceCheck } from '../src/b2b/price-check';
|
||||||
|
import {
|
||||||
|
priceCheckSchema,
|
||||||
|
priceListItemSchema,
|
||||||
|
} from '../src/b2b/price-list.schemas';
|
||||||
|
|
||||||
|
const first = '11111111-1111-4111-8111-111111111111';
|
||||||
|
const second = '22222222-2222-4222-8222-222222222222';
|
||||||
|
const list = {
|
||||||
|
id: '33333333-3333-4333-8333-333333333333',
|
||||||
|
currency: 'INR',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
variantId: first,
|
||||||
|
unitPrice: new Prisma.Decimal('12.35'),
|
||||||
|
minQuantity: 10,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
variantId: second,
|
||||||
|
unitPrice: new Prisma.Decimal('0.10'),
|
||||||
|
minQuantity: 2,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('B2B price check', () => {
|
||||||
|
it('adds exact decimal line totals without floating-point rounding', () => {
|
||||||
|
expect(
|
||||||
|
calculatePriceCheck(list, {
|
||||||
|
lines: [
|
||||||
|
{ variantId: first, quantity: 10 },
|
||||||
|
{ variantId: second, quantity: 3 },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
).toEqual({
|
||||||
|
priceListId: list.id,
|
||||||
|
currency: 'INR',
|
||||||
|
merchandiseTotal: '123.80',
|
||||||
|
lines: [
|
||||||
|
{
|
||||||
|
variantId: first,
|
||||||
|
quantity: 10,
|
||||||
|
minQuantity: 10,
|
||||||
|
unitPrice: '12.35',
|
||||||
|
lineTotal: '123.50',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
variantId: second,
|
||||||
|
quantity: 3,
|
||||||
|
minQuantity: 2,
|
||||||
|
unitPrice: '0.10',
|
||||||
|
lineTotal: '0.30',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses distinct errors for missing terms and unmet minimums', () => {
|
||||||
|
expect(() =>
|
||||||
|
calculatePriceCheck(list, { lines: [{ variantId: first, quantity: 9 }] }),
|
||||||
|
).toThrow(expect.objectContaining({ code: 'B2B_PRICE_MINIMUM_QUANTITY' }));
|
||||||
|
expect(() =>
|
||||||
|
calculatePriceCheck(list, {
|
||||||
|
lines: [{ variantId: list.id, quantity: 10 }],
|
||||||
|
}),
|
||||||
|
).toThrow(expect.objectContaining({ code: 'B2B_PRICE_ITEM_NOT_FOUND' }));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects duplicate variant requests and invalid monetary inputs', () => {
|
||||||
|
expect(
|
||||||
|
priceCheckSchema.safeParse({
|
||||||
|
lines: [
|
||||||
|
{ variantId: first, quantity: 10 },
|
||||||
|
{ variantId: first, quantity: 20 },
|
||||||
|
],
|
||||||
|
}).success,
|
||||||
|
).toBe(false);
|
||||||
|
expect(
|
||||||
|
priceListItemSchema.safeParse({ unitPrice: '0.00', minQuantity: 1 })
|
||||||
|
.success,
|
||||||
|
).toBe(false);
|
||||||
|
expect(
|
||||||
|
priceListItemSchema.safeParse({ unitPrice: '1.001', minQuantity: 1 })
|
||||||
|
.success,
|
||||||
|
).toBe(false);
|
||||||
|
expect(
|
||||||
|
priceListItemSchema.safeParse({ unitPrice: '1.00', minQuantity: 0 })
|
||||||
|
.success,
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,237 @@
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
||||||
|
import { secondActor, seedProduct } from './helpers/commerce';
|
||||||
|
|
||||||
|
describe('B2B partner price lists and minimum quantities', () => {
|
||||||
|
let ctx: IdentityApp;
|
||||||
|
const auth = { type: 'bearer' as const };
|
||||||
|
const listRoute = (id: string) => `/api/v1/b2b/price-lists/${id}`;
|
||||||
|
const profile = () => ({
|
||||||
|
code: `PL-${randomUUID().slice(0, 8)}`,
|
||||||
|
legalName: 'Wholesale Candles Private Limited',
|
||||||
|
tradingName: null,
|
||||||
|
registrationNumber: randomUUID(),
|
||||||
|
taxIdentifier: null,
|
||||||
|
countryCode: 'IN',
|
||||||
|
contactEmail: 'wholesale@example.com',
|
||||||
|
contactPhone: null,
|
||||||
|
billingLine1: '12 Trade Road',
|
||||||
|
billingCity: 'Pune',
|
||||||
|
billingRegion: 'Maharashtra',
|
||||||
|
billingPostalCode: '411001',
|
||||||
|
});
|
||||||
|
async function account() {
|
||||||
|
const created = await ctx
|
||||||
|
.api()
|
||||||
|
.post('/api/v1/b2b/accounts')
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send(profile())
|
||||||
|
.expect(201);
|
||||||
|
return created.body.id as string;
|
||||||
|
}
|
||||||
|
async function verify(accountId: string) {
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`/api/v1/b2b/accounts/${accountId}/submit`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({ idempotencyKey: randomUUID() })
|
||||||
|
.expect(201);
|
||||||
|
const reviewer = await secondActor(ctx, true, ['b2b.verify']);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`/api/v1/b2b/accounts/${accountId}/decision`)
|
||||||
|
.auth(reviewer.token, auth)
|
||||||
|
.send({
|
||||||
|
decision: 'APPROVED',
|
||||||
|
note: 'Registry details reviewed',
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
}
|
||||||
|
async function createList(accountId: string, currency = 'INR') {
|
||||||
|
const created = await ctx
|
||||||
|
.api()
|
||||||
|
.post(`/api/v1/b2b/accounts/${accountId}/price-lists`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({ name: 'Wholesale standard', currency })
|
||||||
|
.expect(201);
|
||||||
|
return created.body.id as string;
|
||||||
|
}
|
||||||
|
const putItem = (
|
||||||
|
listId: string,
|
||||||
|
variantId: string,
|
||||||
|
unitPrice = '350.00',
|
||||||
|
minQuantity = 10,
|
||||||
|
) =>
|
||||||
|
ctx
|
||||||
|
.api()
|
||||||
|
.put(`${listRoute(listId)}/items/${variantId}`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({ unitPrice, minQuantity });
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
ctx = await identityApp();
|
||||||
|
}, 60000);
|
||||||
|
afterAll(async () => {
|
||||||
|
await ctx?.close();
|
||||||
|
});
|
||||||
|
beforeEach(async () => {
|
||||||
|
await ctx.clearLimits();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('gates activation on verification and items, then enforces MOQ and exact prices', async () => {
|
||||||
|
const accountId = await account();
|
||||||
|
const listId = await createList(accountId);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${listRoute(listId)}/activate`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.expect(409)
|
||||||
|
).body.code,
|
||||||
|
).toBe('B2B_PRICE_ACCOUNT_UNVERIFIED');
|
||||||
|
await verify(accountId);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${listRoute(listId)}/activate`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.expect(409)
|
||||||
|
).body.code,
|
||||||
|
).toBe('B2B_PRICE_LIST_EMPTY');
|
||||||
|
const { variant } = await seedProduct(ctx, true);
|
||||||
|
await putItem(listId, variant.id).expect(200);
|
||||||
|
const active = await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${listRoute(listId)}/activate`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.expect(201);
|
||||||
|
expect(active.body.status).toBe('ACTIVE');
|
||||||
|
expect((await putItem(listId, variant.id).expect(409)).body.code).toBe(
|
||||||
|
'B2B_PRICE_LIST_DRAFT_REQUIRED',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${listRoute(listId)}/price-check`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({ lines: [{ variantId: variant.id, quantity: 9 }] })
|
||||||
|
.expect(409)
|
||||||
|
).body.code,
|
||||||
|
).toBe('B2B_PRICE_MINIMUM_QUANTITY');
|
||||||
|
const check = await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${listRoute(listId)}/price-check`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({ lines: [{ variantId: variant.id, quantity: 12 }] })
|
||||||
|
.expect(201);
|
||||||
|
expect(check.body).toMatchObject({
|
||||||
|
currency: 'INR',
|
||||||
|
merchandiseTotal: '4200.00',
|
||||||
|
lines: [{ unitPrice: '350.00', lineTotal: '4200.00', minQuantity: 10 }],
|
||||||
|
});
|
||||||
|
await ctx.db.productVariant.update({
|
||||||
|
where: { id: variant.id },
|
||||||
|
data: { active: false },
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${listRoute(listId)}/price-check`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({ lines: [{ variantId: variant.id, quantity: 12 }] })
|
||||||
|
.expect(409)
|
||||||
|
).body.code,
|
||||||
|
).toBe('B2B_PRICE_VARIANT_INELIGIBLE');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps one active list per account/currency and permits a replacement after archival', async () => {
|
||||||
|
const accountId = await account();
|
||||||
|
await verify(accountId);
|
||||||
|
const { variant } = await seedProduct(ctx, true);
|
||||||
|
const first = await createList(accountId);
|
||||||
|
const replacement = await createList(accountId);
|
||||||
|
await putItem(first, variant.id).expect(200);
|
||||||
|
await putItem(replacement, variant.id, '330.00', 20).expect(200);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${listRoute(first)}/activate`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.expect(201);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${listRoute(replacement)}/activate`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.expect(409)
|
||||||
|
).body.code,
|
||||||
|
).toBe('B2B_PRICE_LIST_ALREADY_ACTIVE');
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${listRoute(first)}/archive`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.expect(201);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.delete(`${listRoute(first)}/items/${variant.id}`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.expect(409)
|
||||||
|
).body.code,
|
||||||
|
).toBe('B2B_PRICE_LIST_DRAFT_REQUIRED');
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${listRoute(first)}/price-check`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({ lines: [{ variantId: variant.id, quantity: 10 }] })
|
||||||
|
.expect(409)
|
||||||
|
).body.code,
|
||||||
|
).toBe('B2B_PRICE_LIST_ACTIVE_REQUIRED');
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${listRoute(replacement)}/activate`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.expect(201);
|
||||||
|
expect(
|
||||||
|
(await ctx.api().get(listRoute(first)).auth(ctx.token, auth).expect(200))
|
||||||
|
.body.items,
|
||||||
|
).toEqual([
|
||||||
|
expect.objectContaining({ variantId: variant.id, minQuantity: 10 }),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects ineligible variants, cross-tenant access and missing permissions', async () => {
|
||||||
|
const accountId = await account();
|
||||||
|
const listId = await createList(accountId, 'USD');
|
||||||
|
const { variant } = await seedProduct(ctx, true);
|
||||||
|
expect((await putItem(listId, variant.id).expect(409)).body.code).toBe(
|
||||||
|
'B2B_PRICE_CURRENCY_MISMATCH',
|
||||||
|
);
|
||||||
|
await putItem(listId, variant.id, '0.00').expect(400);
|
||||||
|
const draft = await seedProduct(ctx);
|
||||||
|
expect(
|
||||||
|
(await putItem(listId, draft.variant.id).expect(409)).body.code,
|
||||||
|
).toBe('B2B_PRICE_VARIANT_INELIGIBLE');
|
||||||
|
const other = await secondActor(ctx, false, ['b2b.price.read']);
|
||||||
|
await ctx.api().get(listRoute(listId)).auth(other.token, auth).expect(404);
|
||||||
|
const reader = await secondActor(ctx, true, ['b2b.price.read']);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${listRoute(listId)}/activate`)
|
||||||
|
.auth(reader.token, auth)
|
||||||
|
.expect(403);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.get(`/api/v1/b2b/accounts/${accountId}/price-lists`)
|
||||||
|
.auth(reader.token, auth)
|
||||||
|
.expect(200);
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue