Merge pull request 'feat(b2b): add custom candle requests and independent review' (#35) from feat/b2b-custom-candle-requests into main
continuous-integration/drone/push Build is failing Details

Reviewed-on: #35
This commit is contained in:
Mihir Motiyani 2026-10-04 00:46:51 +05:30
commit 424d9d0c56
19 changed files with 863 additions and 1 deletions

View File

@ -66,3 +66,5 @@ B2B sample requests, review, and dispatch records: see [Phase 3E API guide](docs
B2B branding and artwork approvals: see [Phase 3F API guide](docs/b2b-artwork-api.md).
B2B partner purchase orders: see [Phase 3G API guide](docs/b2b-partner-orders-api.md).
B2B partner partial payments: see [Phase 3H API guide](docs/b2b-partner-payments-api.md).
B2B custom candle requests and staff review: see [Phase 3I API guide](docs/b2b-custom-candles-api.md).

View File

@ -0,0 +1,34 @@
# B2B custom candle requests (Phase 3I)
Staff capture requests for verified business accounts under `/api/v1/b2b/custom-candles`. All endpoints require a bearer session and are scoped to its organization.
| Method | Path | Permission | Purpose |
| ------ | --------------- | -------------------- | ----------------------------------------------------------- |
| GET | `/` | `b2b.custom.read` | List with optional `accountId`, `status`, `limit`, `offset` |
| GET | `/:id` | `b2b.custom.read` | Read specifications and decision |
| POST | `/` | `b2b.custom.request` | Capture immutable specifications |
| POST | `/:id/decision` | `b2b.custom.review` | Independently approve or reject |
Request example:
```json
{
"accountId": "b92c23e5-794d-47e7-a7f4-428b84543fa1",
"quantity": 500,
"waxType": "Soy",
"fragrance": "Rose",
"container": "Glass jar, 200g fill",
"color": "Ivory",
"brandingRequirements": "Printed logo label",
"specifications": "Cotton wick; individual gift boxes",
"idempotencyKey": "10fc5585-34a6-4ead-b5ce-d83418eb50df"
}
```
Quantity must be an integer from 1 to 1,000,000. Wax type and color allow 100 characters; fragrance and container 160; branding requirements 1,000; specifications 2,000 (minimum three). Text is trimmed and required; use `None` or `Unscented` where appropriate. Unknown fields are rejected.
Decision body: `{ "decision": "APPROVED", "note": "Feasibility reviewed", "idempotencyKey": "<uuid>" }`, or `REJECTED`. Notes require 3–1,000 characters. The requester cannot review their own request. Approval rechecks business verification. Each request permits one decision, enforced by a unique constraint; request and decision updates/deletes are blocked by database triggers.
Responses include the decision (initially null) and computed `status`: `REQUESTED`, `APPROVED`, or `REJECTED`. Request and decision idempotency keys each have their own organization-scoped namespace. Identical retries return the current representation; different content using the same key returns 409. Unauthorized commands return 403, out-of-scope resources 404, unverified accounts and repeat decisions 409. Audit events record request capture and the decision in the same transaction.
Approval means staff accepted the specifications for further commercial work. It creates no quotation, price, order, credit exposure, BOM, stock reservation, production batch, or artwork approval. Revised specifications require a new request and review. Existing system Owner roles receive permissions through the migration; custom roles require explicit grants through RBAC.

View File

@ -46,6 +46,7 @@ Business verification, price lists, MOQ, quotations, credit policies, samples, b
- 3F (implemented): verified-account branding/artwork projects with private PostgreSQL file versions, independent per-version review, restricted downloads, and immutable approval history. Trademark clearance, malware scanning, and production linkage remain separate work.
- 3G (implemented): partner purchase orders captured from accepted, unexpired quotations with immutable merchandise snapshots, idempotent creation, unique partner references, and auditable cancellation. Fulfillment, stock reservation, tax, shipping, payments, and credit utilization remain separate milestones.
- 3H (implemented): manual, partial external receipt records for partner orders with exact merchandise-balance checks, idempotent reversals, and cancellation protection. Gateway collection, refunds, tax, shipping, and credit utilization remain separate milestones.
- 3I (implemented): verified-account custom candle specifications with immutable request capture, independent one-time staff review, scoped permissions, and idempotent retries. Quotation, artwork approval, BOM, and production linkage remain separate milestones.
## Phase 4: Growth channels

View File

@ -41,6 +41,7 @@ model BusinessAccount {
priceLists B2bPriceList[]
quotes B2bQuote[]
creditPolicies B2bCreditPolicy[]
customCandleRequests B2bCustomCandleRequest[]
sampleRequests B2bSampleRequest[]
artworks B2bArtwork[]
partnerOrders B2bPartnerOrder[]

View File

@ -0,0 +1,47 @@
enum B2bCustomCandleDecisionKind {
APPROVED
REJECTED
}
model B2bCustomCandleRequest {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
accountId String @map("account_id") @db.Uuid
requestedById String @map("requested_by_id") @db.Uuid
quantity Int
waxType String @map("wax_type") @db.VarChar(100)
fragrance String @db.VarChar(160)
container String @db.VarChar(160)
color String @db.VarChar(100)
brandingRequirements String @map("branding_requirements") @db.VarChar(1000)
specifications String @db.VarChar(2000)
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)
requestedBy User @relation(fields: [requestedById, organizationId], references: [id, organizationId], onDelete: Restrict)
decision B2bCustomCandleDecision?
@@unique([id, organizationId])
@@unique([organizationId, idempotencyKey])
@@index([organizationId, accountId, createdAt, id])
@@map("b2b_custom_candle_requests")
}
model B2bCustomCandleDecision {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
requestId String @unique @map("request_id") @db.Uuid
actorId String @map("actor_id") @db.Uuid
kind B2bCustomCandleDecisionKind
note String @db.VarChar(1000)
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)
request B2bCustomCandleRequest @relation(fields: [requestId, organizationId], references: [id, organizationId], onDelete: Restrict)
actor User @relation(fields: [actorId, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([requestId, organizationId])
@@unique([organizationId, idempotencyKey])
@@map("b2b_custom_candle_decisions")
}

View File

@ -40,5 +40,6 @@
"20261001234900_b2b_sample_requests": "f4fb334341d996188dbea3fb85dbe5166bffd35bc8872f2c8404b6458bc7c142",
"20261003000100_b2b_artwork_approvals": "1359390fc3692bdc2dea8a4cc12223d97c7c15b0cdd2181b082b5e5acbe33677",
"20261003151400_b2b_partner_orders": "ffbba39ed98a16c122b0756a97d721adde9268904f9a7d9770407f341ef848ba",
"20261003183000_b2b_partner_payments": "bc43c5a713c62aa201affa2f2595156a2fc68882774504cdf12ac4cf0f641452"
"20261003183000_b2b_partner_payments": "bc43c5a713c62aa201affa2f2595156a2fc68882774504cdf12ac4cf0f641452",
"20261004003000_b2b_custom_candle_requests": "ab78d0a7e214ab226e042f29b42e961ddbae3a3e338fd65983d5aa87e2c736ac"
}

View File

@ -0,0 +1,109 @@
-- CreateEnum
CREATE TYPE "B2bCustomCandleDecisionKind" AS ENUM ('APPROVED', 'REJECTED');
-- CreateTable
CREATE TABLE "b2b_custom_candle_requests" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"account_id" UUID NOT NULL,
"requested_by_id" UUID NOT NULL,
"quantity" INTEGER NOT NULL,
"wax_type" VARCHAR(100) NOT NULL,
"fragrance" VARCHAR(160) NOT NULL,
"container" VARCHAR(160) NOT NULL,
"color" VARCHAR(100) NOT NULL,
"branding_requirements" VARCHAR(1000) NOT NULL,
"specifications" VARCHAR(2000) NOT NULL,
"idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "b2b_custom_candle_requests_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "b2b_custom_candle_decisions" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"request_id" UUID NOT NULL,
"actor_id" UUID NOT NULL,
"kind" "B2bCustomCandleDecisionKind" NOT NULL,
"note" VARCHAR(1000) NOT NULL,
"idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "b2b_custom_candle_decisions_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "b2b_custom_candle_requests_organization_id_account_id_creat_idx" ON "b2b_custom_candle_requests"("organization_id", "account_id", "created_at", "id");
-- CreateIndex
CREATE UNIQUE INDEX "b2b_custom_candle_requests_id_organization_id_key" ON "b2b_custom_candle_requests"("id", "organization_id");
-- CreateIndex
CREATE UNIQUE INDEX "b2b_custom_candle_requests_organization_id_idempotency_key_key" ON "b2b_custom_candle_requests"("organization_id", "idempotency_key");
-- CreateIndex
CREATE UNIQUE INDEX "b2b_custom_candle_decisions_request_id_key" ON "b2b_custom_candle_decisions"("request_id");
-- CreateIndex
CREATE UNIQUE INDEX "b2b_custom_candle_decisions_request_id_organization_id_key" ON "b2b_custom_candle_decisions"("request_id", "organization_id");
-- CreateIndex
CREATE UNIQUE INDEX "b2b_custom_candle_decisions_organization_id_idempotency_key_key" ON "b2b_custom_candle_decisions"("organization_id", "idempotency_key");
-- AddForeignKey
ALTER TABLE "b2b_custom_candle_requests" ADD CONSTRAINT "b2b_custom_candle_requests_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "b2b_custom_candle_requests" ADD CONSTRAINT "b2b_custom_candle_requests_account_id_organization_id_fkey" FOREIGN KEY ("account_id", "organization_id") REFERENCES "business_accounts"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "b2b_custom_candle_requests" ADD CONSTRAINT "b2b_custom_candle_requests_requested_by_id_organization_id_fkey" FOREIGN KEY ("requested_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "b2b_custom_candle_decisions" ADD CONSTRAINT "b2b_custom_candle_decisions_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "b2b_custom_candle_decisions" ADD CONSTRAINT "b2b_custom_candle_decisions_request_id_organization_id_fkey" FOREIGN KEY ("request_id", "organization_id") REFERENCES "b2b_custom_candle_requests"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "b2b_custom_candle_decisions" ADD CONSTRAINT "b2b_custom_candle_decisions_actor_id_organization_id_fkey" FOREIGN KEY ("actor_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE b2b_custom_candle_requests
ADD CONSTRAINT custom_candle_quantity CHECK (quantity BETWEEN 1 AND 1000000),
ADD CONSTRAINT custom_candle_text CHECK (
char_length(btrim(wax_type)) >= 1 AND char_length(btrim(fragrance)) >= 1
AND char_length(btrim(container)) >= 1 AND char_length(btrim(color)) >= 1
AND char_length(btrim(branding_requirements)) >= 1 AND char_length(btrim(specifications)) >= 3),
ADD CONSTRAINT custom_candle_request_hash CHECK (request_hash ~ '^[a-f0-9]{64}$');
ALTER TABLE b2b_custom_candle_decisions
ADD CONSTRAINT custom_candle_decision_note CHECK (char_length(btrim(note)) >= 3),
ADD CONSTRAINT custom_candle_decision_hash CHECK (request_hash ~ '^[a-f0-9]{64}$');
CREATE FUNCTION guard_b2b_custom_candle_immutable() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION 'Custom candle requests and decisions are immutable';
END;
$$;
CREATE TRIGGER b2b_custom_candle_requests_immutable BEFORE UPDATE OR DELETE ON b2b_custom_candle_requests
FOR EACH ROW EXECUTE FUNCTION guard_b2b_custom_candle_immutable();
CREATE TRIGGER b2b_custom_candle_decisions_immutable BEFORE UPDATE OR DELETE ON b2b_custom_candle_decisions
FOR EACH ROW EXECUTE FUNCTION guard_b2b_custom_candle_immutable();
CREATE FUNCTION guard_b2b_custom_candle_reviewer() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE requester UUID;
BEGIN
SELECT requested_by_id INTO requester FROM b2b_custom_candle_requests
WHERE id = NEW.request_id AND organization_id = NEW.organization_id;
IF requester = NEW.actor_id THEN RAISE EXCEPTION 'Custom candle review requires an independent reviewer'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER b2b_custom_candle_decisions_reviewer BEFORE INSERT ON b2b_custom_candle_decisions
FOR EACH ROW EXECUTE FUNCTION guard_b2b_custom_candle_reviewer();
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['b2b.custom.read', 'b2b.custom.request', 'b2b.custom.review']))
WHERE is_system = true AND name = 'Owner';

View File

@ -60,6 +60,8 @@ model Organization {
b2bQuoteResponses B2bQuoteResponse[]
b2bCreditPolicies B2bCreditPolicy[]
b2bCreditEvents B2bCreditEvent[]
b2bCustomCandleRequests B2bCustomCandleRequest[]
b2bCustomCandleDecisions B2bCustomCandleDecision[]
b2bSampleRequests B2bSampleRequest[]
b2bSampleEvents B2bSampleEvent[]
b2bArtworks B2bArtwork[]
@ -118,6 +120,8 @@ model User {
b2bQuoteResponses B2bQuoteResponse[]
b2bCreditPolicies B2bCreditPolicy[]
b2bCreditEvents B2bCreditEvent[]
b2bCustomCandleRequests B2bCustomCandleRequest[]
b2bCustomCandleDecisions B2bCustomCandleDecision[]
b2bSampleRequests B2bSampleRequest[]
b2bSampleEvents B2bSampleEvent[]
b2bArtworks B2bArtwork[]

View File

@ -1,3 +1,6 @@
import { CustomCandlesController } from './custom-candles.controller';
import { CustomCandleStore } from './custom-candle.store';
import { CustomCandleReviewStore } from './custom-candle-review.store';
import { Module } from '@nestjs/common';
import { DatabaseModule } from '../database/database.module';
import { IdentityModule } from '../identity/identity.module';
@ -33,6 +36,7 @@ import { PartnerPaymentWriteStore } from './partner-payment-write.store';
@Module({
imports: [DatabaseModule, IdentityModule],
controllers: [
CustomCandlesController,
BusinessController,
PriceListsController,
PriceListItemsController,
@ -45,6 +49,8 @@ import { PartnerPaymentWriteStore } from './partner-payment-write.store';
PartnerPaymentsController,
],
providers: [
CustomCandleStore,
CustomCandleReviewStore,
BusinessStore,
VerificationStore,
PriceListStore,

View File

@ -0,0 +1,22 @@
import { AppError } from '../common/errors/app-error';
import type { DatabaseService } from '../database/database.service';
import type { Prisma } from '../generated/prisma/client';
export const customCandleInclude = { decision: true } as const;
export function customCandleView<
T extends { decision: { kind: string } | null },
>(request: T) {
return { ...request, status: request.decision?.kind ?? 'REQUESTED' };
}
export async function requireCustomCandle(
db: DatabaseService | Prisma.TransactionClient,
organizationId: string,
id: string,
) {
const request = await db.b2bCustomCandleRequest.findFirst({
where: { id, organizationId },
include: customCandleInclude,
});
if (!request) throw new AppError('B2B_CUSTOM_CANDLE_NOT_FOUND');
return request;
}

View File

@ -0,0 +1,68 @@
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 { isVerifiedBusinessAccount } from './business-verification';
import { customCandleView, requireCustomCandle } from './custom-candle-lookup';
import type { CustomCandleDecisionInput } from './custom-candle.schemas';
@Injectable()
export class CustomCandleReviewStore {
constructor(private readonly access: AccessStore) {}
decide(actor: Principal, id: string, input: CustomCandleDecisionInput) {
const hash = commandHash(id, input.decision, input.note);
return this.access.mutate(actor, 'b2b.custom.review', async (tx) => {
const request = await requireCustomCandle(tx, actor.organizationId, id);
const replay = await tx.b2bCustomCandleDecision.findUnique({
where: {
organizationId_idempotencyKey: {
organizationId: actor.organizationId,
idempotencyKey: input.idempotencyKey,
},
},
});
if (replay) {
if (replay.requestHash !== hash)
throw new AppError('B2B_CUSTOM_CANDLE_DECISION_REPLAY_CONFLICT');
return customCandleView(request);
}
if (request.decision)
throw new AppError('B2B_CUSTOM_CANDLE_REVIEW_STATE');
if (request.requestedById === actor.userId)
throw new AppError('B2B_CUSTOM_CANDLE_SELF_REVIEW');
if (
input.decision === 'APPROVED' &&
!(await isVerifiedBusinessAccount(
tx,
actor.organizationId,
request.accountId,
))
)
throw new AppError('B2B_CUSTOM_CANDLE_ACCOUNT_UNVERIFIED');
await tx.b2bCustomCandleDecision.create({
data: {
organizationId: actor.organizationId,
requestId: id,
actorId: actor.userId,
kind: input.decision,
note: input.note,
idempotencyKey: input.idempotencyKey,
requestHash: hash,
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
`b2b_custom_candle.${input.decision.toLowerCase()}`,
id,
);
return customCandleView(
await requireCustomCandle(tx, actor.organizationId, id),
);
});
}
}

View File

@ -0,0 +1,37 @@
import { z } from 'zod';
import { text } from '../common/input';
import { pageSchema } from '../identity/identity.schemas';
export const customCandleRequestSchema = z
.object({
accountId: z.uuid(),
quantity: z.number().int().min(1).max(1_000_000),
waxType: text(100, 1),
fragrance: text(160, 1),
container: text(160, 1),
color: text(100, 1),
brandingRequirements: text(1000, 1),
specifications: text(2000, 3),
idempotencyKey: z.uuid(),
})
.strict();
export const customCandleDecisionSchema = z
.object({
decision: z.enum(['APPROVED', 'REJECTED']),
note: text(1000, 3),
idempotencyKey: z.uuid(),
})
.strict();
export const customCandleQuerySchema = pageSchema
.extend({
accountId: z.uuid().optional(),
status: z.enum(['REQUESTED', 'APPROVED', 'REJECTED']).optional(),
})
.strict();
export type CustomCandleRequestInput = z.infer<
typeof customCandleRequestSchema
>;
export type CustomCandleDecisionInput = z.infer<
typeof customCandleDecisionSchema
>;
export type CustomCandleQuery = z.infer<typeof customCandleQuerySchema>;

View File

@ -0,0 +1,102 @@
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 { isVerifiedBusinessAccount } from './business-verification';
import { requireBusinessAccount } from './price-list.helpers';
import {
customCandleInclude,
customCandleView,
requireCustomCandle,
} from './custom-candle-lookup';
import type {
CustomCandleQuery,
CustomCandleRequestInput,
} from './custom-candle.schemas';
@Injectable()
export class CustomCandleStore {
constructor(
private readonly db: DatabaseService,
private readonly access: AccessStore,
) {}
async list(actor: Principal, query: CustomCandleQuery) {
const requests = await this.db.b2bCustomCandleRequest.findMany({
where: {
organizationId: actor.organizationId,
...(query.accountId ? { accountId: query.accountId } : {}),
...(query.status
? {
decision:
query.status === 'REQUESTED'
? { is: null }
: { is: { kind: query.status } },
}
: {}),
},
include: customCandleInclude,
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
take: query.limit,
skip: query.offset,
});
return requests.map(customCandleView);
}
async get(actor: Principal, id: string) {
return customCandleView(
await requireCustomCandle(this.db, actor.organizationId, id),
);
}
request(actor: Principal, input: CustomCandleRequestInput) {
const { idempotencyKey, ...terms } = input;
const hash = commandHash(JSON.stringify(terms));
return this.access.mutate(actor, 'b2b.custom.request', async (tx) => {
const replay = await tx.b2bCustomCandleRequest.findUnique({
where: {
organizationId_idempotencyKey: {
organizationId: actor.organizationId,
idempotencyKey,
},
},
include: customCandleInclude,
});
if (replay) {
if (replay.requestHash !== hash)
throw new AppError('B2B_CUSTOM_CANDLE_REQUEST_REPLAY_CONFLICT');
return customCandleView(replay);
}
await requireBusinessAccount(tx, actor.organizationId, input.accountId);
if (
!(await isVerifiedBusinessAccount(
tx,
actor.organizationId,
input.accountId,
))
)
throw new AppError('B2B_CUSTOM_CANDLE_ACCOUNT_UNVERIFIED');
const request = await tx.b2bCustomCandleRequest.create({
data: {
...terms,
organizationId: actor.organizationId,
requestedById: actor.userId,
idempotencyKey,
requestHash: hash,
},
include: customCandleInclude,
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'b2b_custom_candle.requested',
request.id,
);
return customCandleView(request);
});
}
}

View File

@ -0,0 +1,72 @@
import {
Body,
Controller,
Get,
Param,
ParseUUIDPipe,
Post,
Query,
} from '@nestjs/common';
import { SchemaPipe } from '../common/validation.pipe';
import {
CurrentPrincipal,
RequirePermission,
} from '../identity/access.decorator';
import type { Principal } from '../identity/identity.types';
import { CustomCandleStore } from './custom-candle.store';
import { CustomCandleReviewStore } from './custom-candle-review.store';
import {
customCandleRequestSchema,
customCandleDecisionSchema,
customCandleQuerySchema,
type CustomCandleRequestInput,
type CustomCandleDecisionInput,
type CustomCandleQuery,
} from './custom-candle.schemas';
@Controller('b2b/custom-candles')
export class CustomCandlesController {
constructor(
private readonly requests: CustomCandleStore,
private readonly reviews: CustomCandleReviewStore,
) {}
@Get()
@RequirePermission('b2b.custom.read')
list(
@CurrentPrincipal() actor: Principal,
@Query(new SchemaPipe(customCandleQuerySchema)) query: CustomCandleQuery,
) {
return this.requests.list(actor, query);
}
@Get(':id')
@RequirePermission('b2b.custom.read')
get(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
) {
return this.requests.get(actor, id);
}
@Post()
@RequirePermission('b2b.custom.request')
request(
@CurrentPrincipal() actor: Principal,
@Body(new SchemaPipe(customCandleRequestSchema))
input: CustomCandleRequestInput,
) {
return this.requests.request(actor, input);
}
@Post(':id/decision')
@RequirePermission('b2b.custom.review')
decide(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@Body(new SchemaPipe(customCandleDecisionSchema))
input: CustomCandleDecisionInput,
) {
return this.reviews.decide(actor, id, input);
}
}

View File

@ -0,0 +1,32 @@
export const B2B_CUSTOM_CANDLE_ERRORS = {
B2B_CUSTOM_CANDLE_NOT_FOUND: [
404,
'Custom candle request not found',
'Scoped request lookup failed',
],
B2B_CUSTOM_CANDLE_ACCOUNT_UNVERIFIED: [
409,
'Business account must be verified',
'Custom candle verification gate failed',
],
B2B_CUSTOM_CANDLE_REQUEST_REPLAY_CONFLICT: [
409,
'Idempotency key was used for a different custom candle request',
'Request replay payload mismatch',
],
B2B_CUSTOM_CANDLE_DECISION_REPLAY_CONFLICT: [
409,
'Idempotency key was used for a different custom candle decision',
'Decision replay payload mismatch',
],
B2B_CUSTOM_CANDLE_REVIEW_STATE: [
409,
'Custom candle request has already been reviewed',
'Decision already exists',
],
B2B_CUSTOM_CANDLE_SELF_REVIEW: [
403,
'A different staff member must review this request',
'Custom candle self-review rejected',
],
} as const;

View File

@ -1,3 +1,4 @@
import { B2B_CUSTOM_CANDLE_ERRORS } from './b2b-custom-candle-errors';
import { CHECKOUT_ERRORS } from './checkout-errors';
import { OPERATIONS_ERRORS } from './operations-errors';
import { PLATFORM_ERRORS } from './platform-errors';
@ -11,6 +12,7 @@ import { B2B_ARTWORK_ERRORS } from './b2b-artwork-errors';
import { B2B_ORDER_ERRORS } from './b2b-order-errors';
import { B2B_PAYMENT_ERRORS } from './b2b-payment-errors';
export const ERRORS = {
...B2B_CUSTOM_CANDLE_ERRORS,
...PLATFORM_ERRORS,
...COMMERCE_ERRORS,
...CHECKOUT_ERRORS,

View File

@ -1,4 +1,7 @@
export const PERMISSIONS = [
'b2b.custom.read',
'b2b.custom.request',
'b2b.custom.review',
'pricing.manage',
'operations.read',
'notifications.retry',

View File

@ -0,0 +1,76 @@
import { randomUUID } from 'node:crypto';
import {
customCandleRequestSchema,
customCandleDecisionSchema,
customCandleQuerySchema,
} from '../src/b2b/custom-candle.schemas';
const input = {
accountId: randomUUID(),
quantity: 500,
waxType: 'Soy',
fragrance: 'Rose',
container: 'Glass jar',
color: 'Ivory',
brandingRequirements: 'Printed logo label',
specifications: '200g fill, cotton wick',
idempotencyKey: randomUUID(),
};
describe('Custom candle validation', () => {
it('normalizes text and accepts quantity boundaries', () => {
expect(
customCandleRequestSchema.parse({ ...input, waxType: ' Soy ' }).waxType,
).toBe('Soy');
for (const quantity of [1, 1_000_000])
expect(
customCandleRequestSchema.safeParse({ ...input, quantity }).success,
).toBe(true);
});
it('rejects invalid quantities, missing specifications and unknown input', () => {
for (const quantity of [0, -1, 1.5, 1_000_001])
expect(
customCandleRequestSchema.safeParse({ ...input, quantity }).success,
).toBe(false);
for (const field of [
'waxType',
'fragrance',
'container',
'color',
'brandingRequirements',
'specifications',
]) {
expect(
customCandleRequestSchema.safeParse({ ...input, [field]: ' ' }).success,
).toBe(false);
}
expect(
customCandleRequestSchema.safeParse({ ...input, price: '100.00' })
.success,
).toBe(false);
expect(
customCandleRequestSchema.safeParse({
...input,
specifications: 'a'.repeat(2001),
}).success,
).toBe(false);
});
it('validates decisions and filters', () => {
expect(
customCandleDecisionSchema.safeParse({
decision: 'APPROVED',
note: 'Feasible',
idempotencyKey: randomUUID(),
}).success,
).toBe(true);
expect(
customCandleDecisionSchema.safeParse({
decision: 'REQUESTED',
note: 'Feasible',
idempotencyKey: randomUUID(),
}).success,
).toBe(false);
expect(
customCandleQuerySchema.safeParse({ status: 'DISPATCHED' }).success,
).toBe(false);
});
});

View File

@ -0,0 +1,243 @@
import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { secondActor } from './helpers/commerce';
import { seedPartnerQuote } from './helpers/b2b-partner-order';
import { businessProfileSchema } from '../src/b2b/business.schemas';
describe('B2B custom candle requests', () => {
let ctx: IdentityApp;
let accountId: string;
const auth = { type: 'bearer' as const };
const url = '/api/v1/b2b/custom-candles';
const input = () => ({
accountId,
quantity: 500,
waxType: 'Soy',
fragrance: 'Rose',
container: 'Glass jar',
color: 'Ivory',
brandingRequirements: 'Logo label',
specifications: '200g fill and cotton wick',
idempotencyKey: randomUUID(),
});
const decision = (kind = 'APPROVED') => ({
decision: kind,
note: 'Feasibility reviewed',
idempotencyKey: randomUUID(),
});
beforeAll(async () => {
ctx = await identityApp(true);
accountId = (await seedPartnerQuote(ctx)).accountId;
}, 60000);
afterAll(async () => {
await ctx?.close();
});
beforeEach(async () => {
await ctx.clearLimits();
});
const create = (body = input()) =>
ctx.api().post(url).auth(ctx.token, auth).send(body);
it('creates immutable terms, filters requests and detects conflicting retries', async () => {
const body = input();
const created = await create(body).expect(201);
expect(created.body).toMatchObject({
...body,
status: 'REQUESTED',
decision: null,
});
expect((await create(body).expect(201)).body.id).toBe(created.body.id);
expect(
(await create({ ...body, quantity: 501 }).expect(409)).body.code,
).toBe('B2B_CUSTOM_CANDLE_REQUEST_REPLAY_CONFLICT');
const listed = await ctx
.api()
.get(`${url}?accountId=${accountId}&status=REQUESTED`)
.auth(ctx.token, auth)
.expect(200);
expect(listed.body.map((row: { id: string }) => row.id)).toContain(
created.body.id,
);
await expect(
ctx.db.b2bCustomCandleRequest.update({
where: { id: created.body.id },
data: { fragrance: 'Lavender' },
}),
).rejects.toThrow();
await expect(
ctx.db.b2bCustomCandleRequest.delete({ where: { id: created.body.id } }),
).rejects.toThrow();
});
it('requires an independent reviewer and permits exactly one auditable decision', async () => {
const id = (await create().expect(201)).body.id as string;
const approve = decision();
expect(
(
await ctx
.api()
.post(`${url}/${id}/decision`)
.auth(ctx.token, auth)
.send(approve)
.expect(403)
).body.code,
).toBe('B2B_CUSTOM_CANDLE_SELF_REVIEW');
const reviewer = await secondActor(ctx, true, ['b2b.custom.review']);
const review = (body = approve) =>
ctx
.api()
.post(`${url}/${id}/decision`)
.auth(reviewer.token, auth)
.send(body);
const result = await review().expect(201);
expect(result.body).toMatchObject({
status: 'APPROVED',
decision: {
kind: 'APPROVED',
actorId: reviewer.userId,
note: approve.note,
},
});
expect((await review().expect(201)).body.decision.id).toBe(
result.body.decision.id,
);
expect(
(await review({ ...approve, note: 'Different note' }).expect(409)).body
.code,
).toBe('B2B_CUSTOM_CANDLE_DECISION_REPLAY_CONFLICT');
expect((await review(decision('REJECTED')).expect(409)).body.code).toBe(
'B2B_CUSTOM_CANDLE_REVIEW_STATE',
);
const listed = await ctx
.api()
.get(`${url}?status=APPROVED`)
.auth(ctx.token, auth)
.expect(200);
expect(listed.body.map((row: { id: string }) => row.id)).toContain(id);
await expect(
ctx.db.b2bCustomCandleDecision.update({
where: { id: result.body.decision.id },
data: { note: 'Changed note' },
}),
).rejects.toThrow();
await expect(
ctx.db.b2bCustomCandleDecision.delete({
where: { id: result.body.decision.id },
}),
).rejects.toThrow();
expect(
await ctx.db.auditEvent.count({
where: { targetId: id, action: { startsWith: 'b2b_custom_candle.' } },
}),
).toBe(2);
});
it('records rejection and returns the current representation on request retry', async () => {
const body = input();
const id = (await create(body).expect(201)).body.id as string;
const reviewer = await secondActor(ctx, true, ['b2b.custom.review']);
await ctx
.api()
.post(`${url}/${id}/decision`)
.auth(reviewer.token, auth)
.send(decision('REJECTED'))
.expect(201);
expect((await create(body).expect(201)).body.status).toBe('REJECTED');
});
it('rejects unverified accounts and blocks self-review at the database boundary', async () => {
const profile = await ctx.db.businessAccount.findUniqueOrThrow({
where: { id: accountId },
});
const unverified = await ctx
.api()
.post('/api/v1/b2b/accounts')
.auth(ctx.token, auth)
.send({
...businessProfileSchema.strip().parse(profile),
code: 'CC-' + randomUUID().slice(0, 8),
registrationNumber: randomUUID(),
})
.expect(201);
expect(
(await create({ ...input(), accountId: unverified.body.id }).expect(409))
.body.code,
).toBe('B2B_CUSTOM_CANDLE_ACCOUNT_UNVERIFIED');
const id = (await create().expect(201)).body.id as string;
await expect(
ctx.executeSql(`INSERT INTO b2b_custom_candle_decisions
(id, organization_id, request_id, actor_id, kind, note, idempotency_key, request_hash)
VALUES ('${randomUUID()}', '${ctx.owner.organizationId}', '${id}', '${ctx.owner.userId}',
'APPROVED', 'Self approval', '${randomUUID()}', '${'a'.repeat(64)}')`),
).rejects.toThrow('independent reviewer');
});
it('serializes concurrent retries without duplicate requests or decisions', async () => {
const body = input();
const requests = await Promise.all([
create(body).expect(201),
create(body).expect(201),
]);
expect(requests[0].body.id).toBe(requests[1].body.id);
const reviewer = await secondActor(ctx, true, ['b2b.custom.review']);
const approve = decision();
const review = () =>
ctx
.api()
.post(`${url}/${requests[0].body.id}/decision`)
.auth(reviewer.token, auth)
.send(approve)
.expect(201);
const decisions = await Promise.all([review(), review()]);
expect(decisions[0].body.decision.id).toBe(decisions[1].body.decision.id);
const otherId = (await create().expect(201)).body.id as string;
expect(
(
await ctx
.api()
.post(`${url}/${otherId}/decision`)
.auth(reviewer.token, auth)
.send(approve)
.expect(409)
).body.code,
).toBe('B2B_CUSTOM_CANDLE_DECISION_REPLAY_CONFLICT');
});
it('enforces permission, organization scope and request validation', async () => {
await ctx.api().get(url).expect(401);
const denied = await secondActor(ctx, true);
await ctx.api().get(url).auth(denied.token, auth).expect(403);
await ctx
.api()
.post(url)
.auth(denied.token, auth)
.send(input())
.expect(403);
const foreign = await identityApp();
try {
const id = (await create().expect(201)).body.id as string;
await foreign
.api()
.get(`${url}/${id}`)
.auth(foreign.token, auth)
.expect(404);
await foreign
.api()
.post(`${url}/${id}/decision`)
.auth(foreign.token, auth)
.send(decision())
.expect(404);
await foreign
.api()
.post(url)
.auth(foreign.token, auth)
.send(input())
.expect(404);
} finally {
await foreign.close();
}
await create({ ...input(), quantity: 0 }).expect(400);
const docs = await ctx.api().get('/api/docs-json').expect(200);
expect(docs.body.paths[url]).toBeDefined();
});
});