Merge pull request 'feat(b2b): add business profiles and manual verification' (#26) from feat/b2b-business-verification into main

Reviewed-on: #26
This commit is contained in:
Mihir Motiyani 2026-09-30 01:13:32 +05:30
commit 7577fb98f4
18 changed files with 938 additions and 1 deletions

View File

@ -56,3 +56,4 @@ Packaging material stock posting: see [Phase 2P API guide](docs/packaging-materi
Finished-goods receipts: see [Phase 2Q API guide](docs/finished-goods-receipt-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).
Business-account profiles and manual verification: see [Phase 3A API guide](docs/b2b-business-verification-api.md).

View File

@ -0,0 +1,21 @@
# B2B business verification (Phase 3A)
Business accounts belong to a merchant organization. Staff manage profiles and manually review submissions. A business account is not a staff user or a separate tenant. A decision records a staff attestation based on the submitted details; this phase does not check a government registry or collect evidence documents.
All routes require a bearer session and are available in Swagger UI under `/api/v1/b2b/accounts`.
| Method | Route | Permission | Purpose |
| ------ | ----------------------------------- | ------------ | ------------------------------------------------------------ |
| GET | `/api/v1/b2b/accounts` | `b2b.read` | List profiles, with `limit`, `offset`, and optional `search` |
| POST | `/api/v1/b2b/accounts` | `b2b.manage` | Create a draft profile |
| GET | `/api/v1/b2b/accounts/:id` | `b2b.read` | Read a profile and its current state |
| PATCH | `/api/v1/b2b/accounts/:id` | `b2b.manage` | Update draft or rejected profile fields |
| GET | `/api/v1/b2b/accounts/:id/events` | `b2b.read` | Read immutable review history |
| POST | `/api/v1/b2b/accounts/:id/submit` | `b2b.manage` | Submit a profile snapshot for review |
| POST | `/api/v1/b2b/accounts/:id/decision` | `b2b.verify` | Approve or reject a pending submission |
Create requires `code`, `legalName`, `tradingName` (nullable), `registrationNumber`, `taxIdentifier` (nullable), `countryCode`, `contactEmail`, `contactPhone` (nullable), `billingLine1`, `billingCity`, `billingRegion`, and `billingPostalCode`. Codes and country codes normalize to uppercase; email normalizes to lowercase. The code cannot change after creation. Country plus registration number is unique within an organization.
Submit takes `{ "idempotencyKey": "<UUID>" }`. Decision takes `{ "decision": "APPROVED", "note": "Registry details checked", "idempotencyKey": "<UUID>" }`, where decision can also be `REJECTED`. A different staff user must decide than the one who submitted. The states are `DRAFT → PENDING → VERIFIED`, or `PENDING → REJECTED → PENDING` after correction and resubmission. A submitted or verified profile cannot be edited. Each submission stores a fixed profile snapshot and each decision stores its reviewer and note. Repeating an identical command with the same key returns the original event; reusing the key for different content returns a conflict.
Apply migrations with `pnpm db:deploy` before starting the updated API. Existing system Owner roles gain the three B2B permissions through the migration; custom roles must be granted them explicitly.

View File

@ -38,6 +38,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.
## Phase 4: Growth channels
Wishlist, verified reviews/moderation, seasonal campaigns, discounts, cart recovery, consent-aware messaging, Instagram, Etsy, WhatsApp, blogs/SEO and segmentation.

55
prisma/b2b.prisma Normal file
View File

@ -0,0 +1,55 @@
enum BusinessVerificationKind {
SUBMITTED
APPROVED
REJECTED
}
model BusinessAccount {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
createdById String @map("created_by_id") @db.Uuid
code String @db.VarChar(32)
legalName String @map("legal_name") @db.VarChar(160)
tradingName String? @map("trading_name") @db.VarChar(160)
registrationNumber String @map("registration_number") @db.VarChar(64)
taxIdentifier String? @map("tax_identifier") @db.VarChar(64)
countryCode String @map("country_code") @db.Char(2)
contactEmail String @map("contact_email") @db.VarChar(254)
contactPhone String? @map("contact_phone") @db.VarChar(24)
billingLine1 String @map("billing_line1") @db.VarChar(200)
billingCity String @map("billing_city") @db.VarChar(100)
billingRegion String @map("billing_region") @db.VarChar(100)
billingPostalCode String @map("billing_postal_code") @db.VarChar(20)
profileVersion Int @default(1) @map("profile_version")
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)
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
events BusinessVerificationEvent[]
@@unique([organizationId, code])
@@unique([organizationId, countryCode, registrationNumber])
@@unique([id, organizationId])
@@index([organizationId, createdAt, id])
@@map("business_accounts")
}
model BusinessVerificationEvent {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
accountId String @map("account_id") @db.Uuid
actorId String @map("actor_id") @db.Uuid
sequence Int
kind BusinessVerificationKind
profileSnapshot Json? @map("profile_snapshot") @db.JsonB
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)
account BusinessAccount @relation(fields: [accountId, organizationId], references: [id, organizationId], onDelete: Restrict)
actor User @relation(fields: [actorId, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([accountId, sequence])
@@unique([organizationId, idempotencyKey])
@@index([organizationId, accountId, sequence])
@@map("business_verification_events")
}

View File

@ -32,5 +32,6 @@
"20260929195800_packaging_material_stock": "2b11c19499d917bcdd53ade20175235ef83cc64cdafda2118ea2dac2096a6f8d",
"20260929203400_finished_goods_receipt": "7745c23f9037d7bb0de7bdfaf94610794b83213f041583c0f9678c4e837f53f0",
"20260930002200_material_warehouse_transfers": "0f193ecd186971e19fdc823944312be70646b348a1a846ab41703d269936e21a",
"20260930003800_material_stock_adjustments": "2002d6826f34da5a999a0098a7191aa00f5fdc4ca54446b776270021d48ef5eb"
"20260930003800_material_stock_adjustments": "2002d6826f34da5a999a0098a7191aa00f5fdc4ca54446b776270021d48ef5eb",
"20260930010000_b2b_business_verification": "1ab6537ff21436ce3421024f6f61e647c2c82a35a09a769833c6b82cdccca32b"
}

View File

@ -0,0 +1,82 @@
CREATE TYPE "BusinessVerificationKind" AS ENUM ('SUBMITTED', 'APPROVED', 'REJECTED');
CREATE TABLE "business_accounts" (
"id" UUID NOT NULL PRIMARY KEY, "organization_id" UUID NOT NULL, "created_by_id" UUID NOT NULL,
"code" VARCHAR(32) NOT NULL, "legal_name" VARCHAR(160) NOT NULL, "trading_name" VARCHAR(160),
"registration_number" VARCHAR(64) NOT NULL, "tax_identifier" VARCHAR(64), "country_code" CHAR(2) NOT NULL,
"contact_email" VARCHAR(254) NOT NULL, "contact_phone" VARCHAR(24), "billing_line1" VARCHAR(200) NOT NULL,
"billing_city" VARCHAR(100) NOT NULL, "billing_region" VARCHAR(100) NOT NULL,
"billing_postal_code" VARCHAR(20) NOT NULL, "profile_version" INTEGER NOT NULL DEFAULT 1,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updated_at" TIMESTAMPTZ(3) NOT NULL,
CONSTRAINT "business_accounts_profile_version" CHECK ("profile_version" > 0),
CONSTRAINT "business_accounts_code" CHECK ("code" ~ '^[A-Z0-9][A-Z0-9_-]*$'),
CONSTRAINT "business_accounts_country" CHECK ("country_code" ~ '^[A-Z]{2}$')
);
CREATE UNIQUE INDEX "business_accounts_organization_id_code_key" ON "business_accounts"("organization_id", "code");
CREATE UNIQUE INDEX "business_accounts_organization_id_country_code_registration_key" ON "business_accounts"("organization_id", "country_code", "registration_number");
CREATE UNIQUE INDEX "business_accounts_id_organization_id_key" ON "business_accounts"("id", "organization_id");
CREATE INDEX "business_accounts_organization_id_created_at_id_idx" ON "business_accounts"("organization_id", "created_at", "id");
ALTER TABLE "business_accounts" ADD CONSTRAINT "business_accounts_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "business_accounts" ADD CONSTRAINT "business_accounts_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 "business_verification_events" (
"id" UUID NOT NULL PRIMARY KEY, "organization_id" UUID NOT NULL, "account_id" UUID NOT NULL,
"actor_id" UUID NOT NULL, "sequence" INTEGER NOT NULL, "kind" "BusinessVerificationKind" NOT NULL,
"profile_snapshot" JSONB, "note" VARCHAR(500), "idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL, "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "business_verification_events_sequence" CHECK ("sequence" > 0),
CONSTRAINT "business_verification_events_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$'),
CONSTRAINT "business_verification_events_shape" CHECK (
("kind" = 'SUBMITTED' AND "profile_snapshot" IS NOT NULL AND "note" IS NULL)
OR ("kind" IN ('APPROVED', 'REJECTED') AND "profile_snapshot" IS NULL AND char_length(btrim("note")) BETWEEN 3 AND 500)
)
);
CREATE UNIQUE INDEX "business_verification_events_account_id_sequence_key" ON "business_verification_events"("account_id", "sequence");
CREATE UNIQUE INDEX "business_verification_events_organization_id_idempotency_ke_key" ON "business_verification_events"("organization_id", "idempotency_key");
CREATE INDEX "business_verification_events_organization_id_account_id_seq_idx" ON "business_verification_events"("organization_id", "account_id", "sequence");
ALTER TABLE "business_verification_events" ADD CONSTRAINT "business_verification_events_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "business_verification_events" ADD CONSTRAINT "business_verification_events_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 "business_verification_events" ADD CONSTRAINT "business_verification_events_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_business_account() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE latest "BusinessVerificationKind";
BEGIN
IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Business accounts cannot be deleted'; END IF;
IF (NEW.id, NEW.organization_id, NEW.created_by_id, NEW.code, NEW.created_at)
IS DISTINCT FROM (OLD.id, OLD.organization_id, OLD.created_by_id, OLD.code, OLD.created_at)
THEN RAISE EXCEPTION 'Business account identity is immutable'; END IF;
SELECT kind INTO latest FROM business_verification_events WHERE account_id = OLD.id ORDER BY sequence DESC LIMIT 1;
IF latest IN ('SUBMITTED', 'APPROVED') THEN RAISE EXCEPTION 'Submitted or approved business profiles cannot be edited'; END IF;
IF NEW.profile_version <> OLD.profile_version + 1 THEN RAISE EXCEPTION 'Business profile version must advance by one'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER business_accounts_guard BEFORE UPDATE OR DELETE ON business_accounts FOR EACH ROW EXECUTE FUNCTION guard_business_account();
CREATE FUNCTION guard_business_verification_event() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE previous business_verification_events%ROWTYPE;
DECLARE account business_accounts%ROWTYPE;
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Business verification history is immutable'; END IF;
SELECT * INTO account FROM business_accounts WHERE id = NEW.account_id AND organization_id = NEW.organization_id;
SELECT * INTO previous FROM business_verification_events WHERE account_id = NEW.account_id ORDER BY sequence DESC LIMIT 1;
IF NEW.sequence <> COALESCE(previous.sequence, 0) + 1 THEN RAISE EXCEPTION 'Business verification sequence invalid'; END IF;
IF NEW.kind = 'SUBMITTED' THEN
IF previous.kind IS NOT NULL AND previous.kind <> 'REJECTED' THEN RAISE EXCEPTION 'Business verification submission state invalid'; END IF;
IF NEW.profile_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 'Business verification snapshot does not match current profile'; END IF;
ELSIF previous.kind IS DISTINCT FROM 'SUBMITTED' OR previous.actor_id = NEW.actor_id THEN
RAISE EXCEPTION 'Business verification decision state or reviewer invalid';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER business_verification_events_guard BEFORE INSERT OR UPDATE OR DELETE ON business_verification_events FOR EACH ROW EXECUTE FUNCTION guard_business_verification_event();
UPDATE "roles" SET "permissions" = ARRAY(SELECT DISTINCT unnest("permissions" || ARRAY['b2b.read', 'b2b.manage', 'b2b.verify']))
WHERE "is_system" = true AND "name" = 'Owner';

View File

@ -51,6 +51,8 @@ model Organization {
finishedGoodsReceipts FinishedGoodsReceipt[]
materialStockTransfers MaterialStockTransfer[]
materialStockAdjustments MaterialStockAdjustment[]
businessAccounts BusinessAccount[]
businessVerificationEvents BusinessVerificationEvent[]
@@map("organizations")
}
model User {
@ -92,6 +94,8 @@ model User {
finishedGoodsReceipts FinishedGoodsReceipt[]
materialStockTransfers MaterialStockTransfer[]
materialStockAdjustments MaterialStockAdjustment[]
businessAccounts BusinessAccount[]
businessVerificationEvents BusinessVerificationEvent[]
stockEntries StockLedger[]
stockReservations StockReservation[]
carts Cart[]

View File

@ -10,6 +10,7 @@ import { Module } from '@nestjs/common';
import { EnvironmentModule } from './config/environment.module';
import { IdentityModule } from './identity/identity.module';
import { HealthModule } from './health/health.module';
import { B2bModule } from './b2b/b2b.module';
@Module({
imports: [
@ -22,6 +23,7 @@ import { HealthModule } from './health/health.module';
ProcurementModule,
ProductionModule,
CostingModule,
B2bModule,
CheckoutModule,
OperationsModule,
],

13
src/b2b/b2b.module.ts Normal file
View File

@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { DatabaseModule } from '../database/database.module';
import { IdentityModule } from '../identity/identity.module';
import { BusinessController } from './business.controller';
import { BusinessStore } from './business.store';
import { VerificationStore } from './verification.store';
@Module({
imports: [DatabaseModule, IdentityModule],
controllers: [BusinessController],
providers: [BusinessStore, VerificationStore],
})
export class B2bModule {}

View File

@ -0,0 +1,59 @@
import type {
BusinessAccount,
BusinessVerificationEvent,
} from '../generated/prisma/client';
export function profileSnapshot(account: BusinessAccount) {
const {
legalName,
tradingName,
registrationNumber,
taxIdentifier,
countryCode,
contactEmail,
contactPhone,
billingLine1,
billingCity,
billingRegion,
billingPostalCode,
profileVersion,
} = account;
return {
legalName,
tradingName,
registrationNumber,
taxIdentifier,
countryCode,
contactEmail,
contactPhone,
billingLine1,
billingCity,
billingRegion,
billingPostalCode,
profileVersion,
};
}
export function businessStatus(
event?: Pick<BusinessVerificationEvent, 'kind'>,
) {
if (!event) return 'DRAFT' as const;
return (
{
SUBMITTED: 'PENDING',
APPROVED: 'VERIFIED',
REJECTED: 'REJECTED',
} as const
)[event.kind];
}
export function presentBusiness(
account: BusinessAccount & { events: BusinessVerificationEvent[] },
) {
const { events, ...profile } = account;
return {
...profile,
status: businessStatus(events[0]),
latestEvent: events[0] ?? null,
};
}

View File

@ -0,0 +1,104 @@
import {
Body,
Controller,
Get,
Param,
ParseUUIDPipe,
Patch,
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 { BusinessStore } from './business.store';
import { VerificationStore } from './verification.store';
import {
businessQuerySchema,
createBusinessSchema,
updateBusinessSchema,
submitBusinessSchema,
decideBusinessSchema,
type BusinessQuery,
type CreateBusinessInput,
type UpdateBusinessInput,
type SubmitBusinessInput,
type DecideBusinessInput,
} from './business.schemas';
@Controller('b2b/accounts')
export class BusinessController {
constructor(
private readonly accounts: BusinessStore,
private readonly verification: VerificationStore,
) {}
@Get()
@RequirePermission('b2b.read')
list(
@CurrentPrincipal() actor: Principal,
@Query(new SchemaPipe(businessQuerySchema)) query: BusinessQuery,
) {
return this.accounts.list(actor, query);
}
@Post()
@RequirePermission('b2b.manage')
create(
@CurrentPrincipal() actor: Principal,
@Body(new SchemaPipe(createBusinessSchema)) input: CreateBusinessInput,
) {
return this.accounts.create(actor, input);
}
@Get(':id')
@RequirePermission('b2b.read')
get(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
) {
return this.accounts.get(actor, id);
}
@Patch(':id')
@RequirePermission('b2b.manage')
update(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@Body(new SchemaPipe(updateBusinessSchema)) input: UpdateBusinessInput,
) {
return this.accounts.update(actor, id, input);
}
@Get(':id/events')
@RequirePermission('b2b.read')
events(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
) {
return this.verification.list(actor, id);
}
@Post(':id/submit')
@RequirePermission('b2b.manage')
submit(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@Body(new SchemaPipe(submitBusinessSchema)) input: SubmitBusinessInput,
) {
return this.verification.submit(actor, id, input);
}
@Post(':id/decision')
@RequirePermission('b2b.verify')
decide(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@Body(new SchemaPipe(decideBusinessSchema)) input: DecideBusinessInput,
) {
return this.verification.decide(actor, id, input);
}
}

View File

@ -0,0 +1,63 @@
import { z } from 'zod';
import { text } from '../common/input';
import { pageSchema } from '../identity/identity.schemas';
const optionalText = (max: number) => text(max).nullable();
export const businessProfileSchema = z
.object({
legalName: text(160),
tradingName: optionalText(160),
registrationNumber: text(64, 3),
taxIdentifier: optionalText(64),
countryCode: z
.string()
.trim()
.toUpperCase()
.regex(/^[A-Z]{2}$/),
contactEmail: z
.email()
.max(254)
.transform((value) => value.toLowerCase()),
contactPhone: z
.string()
.trim()
.regex(/^\+?[0-9 ()-]{7,24}$/)
.nullable(),
billingLine1: text(200),
billingCity: text(100),
billingRegion: text(100),
billingPostalCode: text(20),
})
.strict();
export const createBusinessSchema = businessProfileSchema
.extend({
code: z
.string()
.trim()
.toUpperCase()
.max(32)
.regex(/^[A-Z0-9][A-Z0-9_-]*$/),
})
.strict();
export const updateBusinessSchema = businessProfileSchema
.partial()
.refine((value) => Object.keys(value).length > 0);
export const businessQuerySchema = pageSchema
.extend({
search: text(100).optional(),
})
.strict();
export const submitBusinessSchema = z
.object({ idempotencyKey: z.uuid() })
.strict();
export const decideBusinessSchema = submitBusinessSchema
.extend({
decision: z.enum(['APPROVED', 'REJECTED']),
note: text(500, 3),
})
.strict();
export type CreateBusinessInput = z.infer<typeof createBusinessSchema>;
export type UpdateBusinessInput = z.infer<typeof updateBusinessSchema>;
export type BusinessQuery = z.infer<typeof businessQuerySchema>;
export type SubmitBusinessInput = z.infer<typeof submitBusinessSchema>;
export type DecideBusinessInput = z.infer<typeof decideBusinessSchema>;

128
src/b2b/business.store.ts Normal file
View File

@ -0,0 +1,128 @@
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 { businessStatus, presentBusiness } from './business-profile';
import type {
BusinessQuery,
CreateBusinessInput,
UpdateBusinessInput,
} from './business.schemas';
const latest = { events: { orderBy: { sequence: 'desc' as const }, take: 1 } };
@Injectable()
export class BusinessStore {
constructor(
private readonly db: DatabaseService,
private readonly access: AccessStore,
) {}
async list(actor: Principal, query: BusinessQuery) {
const accounts = await this.db.businessAccount.findMany({
where: {
organizationId: actor.organizationId,
...(query.search
? {
OR: [
{ code: { contains: query.search, mode: 'insensitive' } },
{ legalName: { contains: query.search, mode: 'insensitive' } },
],
}
: {}),
},
include: latest,
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
take: query.limit,
skip: query.offset,
});
return accounts.map(presentBusiness);
}
async get(actor: Principal, id: string) {
const account = await this.db.businessAccount.findFirst({
where: { id, organizationId: actor.organizationId },
include: latest,
});
if (!account) throw new AppError('BUSINESS_ACCOUNT_NOT_FOUND');
return presentBusiness(account);
}
create(actor: Principal, input: CreateBusinessInput) {
return this.access.mutate(actor, 'b2b.manage', async (tx) => {
if (
await tx.businessAccount.findFirst({
where: { organizationId: actor.organizationId, code: input.code },
})
)
throw new AppError('BUSINESS_CODE_CONFLICT');
if (
await tx.businessAccount.findFirst({
where: {
organizationId: actor.organizationId,
countryCode: input.countryCode,
registrationNumber: input.registrationNumber,
},
})
)
throw new AppError('BUSINESS_REGISTRATION_CONFLICT');
const account = await tx.businessAccount.create({
data: {
...input,
organizationId: actor.organizationId,
createdById: actor.userId,
},
include: latest,
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'business_account.created',
account.id,
);
return presentBusiness(account);
});
}
update(actor: Principal, id: string, input: UpdateBusinessInput) {
return this.access.mutate(actor, 'b2b.manage', async (tx) => {
const account = await tx.businessAccount.findFirst({
where: { id, organizationId: actor.organizationId },
include: latest,
});
if (!account) throw new AppError('BUSINESS_ACCOUNT_NOT_FOUND');
if (!['DRAFT', 'REJECTED'].includes(businessStatus(account.events[0])))
throw new AppError('BUSINESS_EDIT_STATE');
const countryCode = input.countryCode ?? account.countryCode;
const registrationNumber =
input.registrationNumber ?? account.registrationNumber;
if (
await tx.businessAccount.findFirst({
where: {
organizationId: actor.organizationId,
countryCode,
registrationNumber,
id: { not: id },
},
})
)
throw new AppError('BUSINESS_REGISTRATION_CONFLICT');
const updated = await tx.businessAccount.update({
where: { id },
data: { ...input, profileVersion: { increment: 1 } },
include: latest,
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'business_account.updated',
id,
);
return presentBusiness(updated);
});
}
}

View File

@ -0,0 +1,134 @@
import { Injectable } from '@nestjs/common';
import { AppError } from '../common/errors/app-error';
import { commandHash } from '../common/idempotency';
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 type {
DecideBusinessInput,
SubmitBusinessInput,
} from './business.schemas';
import type { Prisma } from '../generated/prisma/client';
@Injectable()
export class VerificationStore {
constructor(
private readonly db: DatabaseService,
private readonly access: AccessStore,
) {}
async list(actor: Principal, accountId: string) {
await this.requireAccount(this.db, actor, accountId);
return this.db.businessVerificationEvent.findMany({
where: { organizationId: actor.organizationId, accountId },
orderBy: { sequence: 'asc' },
});
}
submit(actor: Principal, accountId: string, input: SubmitBusinessInput) {
return this.access.mutate(actor, 'b2b.manage', async (tx) => {
const account = await this.requireAccount(tx, actor, accountId);
const snapshot = profileSnapshot(account);
const hash = commandHash(accountId, JSON.stringify(snapshot));
const replay = await this.replay(tx, actor, input.idempotencyKey, hash);
if (replay) return replay;
const previous = await this.latest(tx, accountId);
if (previous && previous.kind !== 'REJECTED')
throw new AppError('BUSINESS_SUBMIT_STATE');
const event = await tx.businessVerificationEvent.create({
data: {
organizationId: actor.organizationId,
accountId,
actorId: actor.userId,
sequence: (previous?.sequence ?? 0) + 1,
kind: 'SUBMITTED',
profileSnapshot: snapshot,
idempotencyKey: input.idempotencyKey,
requestHash: hash,
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'business_verification.submitted',
accountId,
);
return event;
});
}
decide(actor: Principal, accountId: string, input: DecideBusinessInput) {
return this.access.mutate(actor, 'b2b.verify', async (tx) => {
await this.requireAccount(tx, actor, accountId);
const hash = commandHash(accountId, input.decision, input.note);
const replay = await this.replay(tx, actor, input.idempotencyKey, hash);
if (replay) return replay;
const previous = await this.latest(tx, accountId);
if (previous?.kind !== 'SUBMITTED')
throw new AppError('BUSINESS_DECISION_STATE');
if (previous.actorId === actor.userId)
throw new AppError('BUSINESS_SELF_REVIEW');
const event = await tx.businessVerificationEvent.create({
data: {
organizationId: actor.organizationId,
accountId,
actorId: actor.userId,
sequence: previous.sequence + 1,
kind: input.decision,
note: input.note,
idempotencyKey: input.idempotencyKey,
requestHash: hash,
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
`business_verification.${input.decision.toLowerCase()}`,
accountId,
);
return event;
});
}
private async requireAccount(
db: Prisma.TransactionClient | DatabaseService,
actor: Principal,
accountId: string,
) {
const account = await db.businessAccount.findFirst({
where: { id: accountId, organizationId: actor.organizationId },
});
if (!account) throw new AppError('BUSINESS_ACCOUNT_NOT_FOUND');
return account;
}
private latest(tx: Prisma.TransactionClient, accountId: string) {
return tx.businessVerificationEvent.findFirst({
where: { accountId },
orderBy: { sequence: 'desc' },
});
}
private async replay(
tx: Prisma.TransactionClient,
actor: Principal,
key: string,
hash: string,
) {
const event = await tx.businessVerificationEvent.findUnique({
where: {
organizationId_idempotencyKey: {
organizationId: actor.organizationId,
idempotencyKey: key,
},
},
});
if (event && event.requestHash !== hash)
throw new AppError('BUSINESS_REPLAY_CONFLICT');
return event;
}
}

View File

@ -0,0 +1,42 @@
export const B2B_ERRORS = {
BUSINESS_ACCOUNT_NOT_FOUND: [
404,
'Business account not found',
'Scoped business account lookup failed',
],
BUSINESS_CODE_CONFLICT: [
409,
'Business account code already exists',
'Business account code duplicate',
],
BUSINESS_REGISTRATION_CONFLICT: [
409,
'Business registration already exists',
'Business registration duplicate in country',
],
BUSINESS_EDIT_STATE: [
409,
'This business profile cannot be edited in its current state',
'Business profile edit rejected by verification state',
],
BUSINESS_SUBMIT_STATE: [
409,
'This business profile cannot be submitted in its current state',
'Business verification submission state invalid',
],
BUSINESS_DECISION_STATE: [
409,
'This business profile is not awaiting review',
'Business verification decision state invalid',
],
BUSINESS_SELF_REVIEW: [
403,
'A different staff member must review this submission',
'Business verification self-review rejected',
],
BUSINESS_REPLAY_CONFLICT: [
409,
'Idempotency key was used for a different business action',
'Business verification replay payload mismatch',
],
} as const;

View File

@ -2,10 +2,12 @@ import { CHECKOUT_ERRORS } from './checkout-errors';
import { OPERATIONS_ERRORS } from './operations-errors';
import { PLATFORM_ERRORS } from './platform-errors';
import { COMMERCE_ERRORS } from './commerce-errors';
import { B2B_ERRORS } from './b2b-errors';
export const ERRORS = {
...PLATFORM_ERRORS,
...COMMERCE_ERRORS,
...CHECKOUT_ERRORS,
...OPERATIONS_ERRORS,
...B2B_ERRORS,
} as const;
export type ErrorCode = keyof typeof ERRORS;

View File

@ -36,5 +36,8 @@ export const PERMISSIONS = [
'production.read',
'production.manage',
'production.material.record',
'b2b.read',
'b2b.manage',
'b2b.verify',
] as const;
export type Permission = (typeof PERMISSIONS)[number];

View File

@ -0,0 +1,221 @@
import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { secondActor } from './helpers/commerce';
describe('B2B business verification', () => {
let ctx: IdentityApp;
const auth = { type: 'bearer' as const };
const profile = () => ({
code: `B-${randomUUID().slice(0, 8)}`,
legalName: 'Candle Partner Private Limited',
tradingName: null,
registrationNumber: randomUUID(),
taxIdentifier: null,
countryCode: 'IN',
contactEmail: 'partner@example.com',
contactPhone: null,
billingLine1: '12 Market Road',
billingCity: 'Pune',
billingRegion: 'Maharashtra',
billingPostalCode: '411001',
});
const create = (input = profile()) =>
ctx.api().post('/api/v1/b2b/accounts').auth(ctx.token, auth).send(input);
const route = (id: string, suffix = '') =>
`/api/v1/b2b/accounts/${id}${suffix}`;
beforeAll(async () => {
ctx = await identityApp();
}, 60000);
afterAll(async () => {
await ctx?.close();
});
beforeEach(async () => {
await ctx.clearLimits();
});
it('creates, lists and scopes profiles; distinguishes duplicate identifiers', async () => {
const input = profile();
const account = await create(input).expect(201);
expect(account.body).toMatchObject({
code: input.code.toUpperCase(),
status: 'DRAFT',
profileVersion: 1,
});
expect((await create(input).expect(409)).body.code).toBe(
'BUSINESS_CODE_CONFLICT',
);
expect(
(
await create({
...input,
code: `B-${randomUUID().slice(0, 8)}`,
}).expect(409)
).body.code,
).toBe('BUSINESS_REGISTRATION_CONFLICT');
const other = await secondActor(ctx, false, ['b2b.read']);
await ctx
.api()
.get(route(account.body.id))
.auth(other.token, auth)
.expect(404);
expect(
(
await ctx
.api()
.get('/api/v1/b2b/accounts')
.auth(ctx.token, auth)
.expect(200)
).body,
).toEqual(
expect.arrayContaining([
expect.objectContaining({ id: account.body.id }),
]),
);
});
it('submits an immutable profile snapshot, rejects self-review, and approves with a second reviewer', async () => {
const account = await create().expect(201);
const id = account.body.id as string;
const submission = { idempotencyKey: randomUUID() };
const submit = () =>
ctx
.api()
.post(route(id, '/submit'))
.auth(ctx.token, auth)
.send(submission);
const submitted = await submit().expect(201);
expect(submitted.body.profileSnapshot).toMatchObject({
legalName: account.body.legalName,
profileVersion: 1,
});
expect((await submit().expect(201)).body.id).toBe(submitted.body.id);
expect(
(
await ctx
.api()
.patch(route(id))
.auth(ctx.token, auth)
.send({ legalName: 'Changed' })
.expect(409)
).body.code,
).toBe('BUSINESS_EDIT_STATE');
const decision = {
decision: 'APPROVED',
note: 'Registry details checked by staff',
idempotencyKey: randomUUID(),
};
expect(
(
await ctx
.api()
.post(route(id, '/decision'))
.auth(ctx.token, auth)
.send(decision)
.expect(403)
).body.code,
).toBe('BUSINESS_SELF_REVIEW');
const reviewer = await secondActor(ctx, true, ['b2b.verify']);
const approve = () =>
ctx
.api()
.post(route(id, '/decision'))
.auth(reviewer.token, auth)
.send(decision);
const approved = await approve().expect(201);
expect((await approve().expect(201)).body.id).toBe(approved.body.id);
expect(
(await ctx.api().get(route(id)).auth(ctx.token, auth).expect(200)).body
.status,
).toBe('VERIFIED');
const history = await ctx
.api()
.get(route(id, '/events'))
.auth(ctx.token, auth)
.expect(200);
expect(history.body.map((event: { kind: string }) => event.kind)).toEqual([
'SUBMITTED',
'APPROVED',
]);
});
it('allows a rejected profile to be corrected and resubmitted, while enforcing replay payloads', async () => {
const account = await create().expect(201);
const id = account.body.id as string;
const reviewer = await secondActor(ctx, true, ['b2b.verify']);
await ctx
.api()
.post(route(id, '/submit'))
.auth(ctx.token, auth)
.send({ idempotencyKey: randomUUID() })
.expect(201);
const decision = {
decision: 'REJECTED',
note: 'Registration number needs correction',
idempotencyKey: randomUUID(),
};
await ctx
.api()
.post(route(id, '/decision'))
.auth(reviewer.token, auth)
.send(decision)
.expect(201);
const updated = await ctx
.api()
.patch(route(id))
.auth(ctx.token, auth)
.send({ registrationNumber: randomUUID() })
.expect(200);
expect(updated.body).toMatchObject({
status: 'REJECTED',
profileVersion: 2,
});
const key = randomUUID();
await ctx
.api()
.post(route(id, '/submit'))
.auth(ctx.token, auth)
.send({ idempotencyKey: key })
.expect(201);
const history = await ctx
.api()
.get(route(id, '/events'))
.auth(ctx.token, auth)
.expect(200);
expect(history.body.map((event: { kind: string }) => event.kind)).toEqual([
'SUBMITTED',
'REJECTED',
'SUBMITTED',
]);
expect(history.body[2].profileSnapshot.profileVersion).toBe(2);
expect(
(
await ctx
.api()
.post(route(id, '/decision'))
.auth(reviewer.token, auth)
.send({ ...decision, idempotencyKey: key })
.expect(409)
).body.code,
).toBe('BUSINESS_REPLAY_CONFLICT');
});
it('requires permissions and rejects malformed profiles without recording them', async () => {
const reader = await secondActor(ctx, true, ['b2b.read']);
await ctx
.api()
.post('/api/v1/b2b/accounts')
.auth(reader.token, auth)
.send(profile())
.expect(403);
const before = await ctx.db.businessAccount.count({
where: { organizationId: ctx.owner.organizationId },
});
await create({ ...profile(), legalName: '<script>' }).expect(400);
expect(
await ctx.db.businessAccount.count({
where: { organizationId: ctx.owner.organizationId },
}),
).toBe(before);
});
});