feat(b2b): add reviewed sample requests
This commit is contained in:
parent
fcb8b5be6f
commit
9ea8f4ccc3
|
|
@ -60,3 +60,4 @@ Business-account profiles and manual verification: see [Phase 3A API guide](docs
|
||||||
Partner price lists and minimum quantities: see [Phase 3B API guide](docs/b2b-price-lists-api.md).
|
Partner price lists and minimum quantities: see [Phase 3B API guide](docs/b2b-price-lists-api.md).
|
||||||
B2B quotations and response tracking: see [Phase 3C API guide](docs/b2b-quotations-api.md).
|
B2B quotations and response tracking: see [Phase 3C API guide](docs/b2b-quotations-api.md).
|
||||||
B2B credit proposals and independent review: see [Phase 3D API guide](docs/b2b-credit-policies-api.md).
|
B2B credit proposals and independent review: see [Phase 3D API guide](docs/b2b-credit-policies-api.md).
|
||||||
|
B2B sample requests, review, and dispatch records: see [Phase 3E API guide](docs/b2b-samples-api.md).
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,29 @@
|
||||||
|
# B2B sample requests (Phase 3E)
|
||||||
|
|
||||||
|
All endpoints are under `/api/v1/b2b/samples` and require a bearer session. Every request is scoped to the caller's organization. Request fields and event history are immutable; status changes are checked in the database.
|
||||||
|
|
||||||
|
| Method | Path | Permission | Purpose |
|
||||||
|
| ------ | --------------- | --------------------- | ------------------------------------------------------- |
|
||||||
|
| GET | `/` | `b2b.sample.read` | List; optional `accountId`, `status`, `limit`, `offset` |
|
||||||
|
| GET | `/:id` | `b2b.sample.read` | Read request and ordered events |
|
||||||
|
| POST | `/` | `b2b.sample.request` | Request samples for a verified business account |
|
||||||
|
| POST | `/:id/decision` | `b2b.sample.review` | Approve or reject, by a different staff member |
|
||||||
|
| POST | `/:id/dispatch` | `b2b.sample.dispatch` | Record manual dispatch of an approved request |
|
||||||
|
|
||||||
|
Request body example:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"accountId": "b92c23e5-794d-47e7-a7f4-428b84543fa1",
|
||||||
|
"variantId": "842b4658-2c2c-4626-8feb-1842ecf8726a",
|
||||||
|
"quantity": 4,
|
||||||
|
"purpose": "Fragrance evaluation",
|
||||||
|
"idempotencyKey": "10fc5585-34a6-4ead-b5ce-d83418eb50df"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Quantity is 1–100. The variant must be active and its product published. The request stores the variant SKU and name at creation. A decision body contains `decision` (`APPROVED` or `REJECTED`), `note`, and `idempotencyKey`. An approval rechecks business verification. A dispatch body contains `dispatchReference`, `note`, and `idempotencyKey`. Notes and purpose require 3–500 characters; dispatch reference requires 3–100 characters.
|
||||||
|
|
||||||
|
The lifecycle is `REQUESTED → APPROVED → DISPATCHED` or `REQUESTED → REJECTED`. Duplicate requests with the same key and payload return the current request; a changed payload returns a distinct 409 error. Event retries work the same way. The event response includes actor, time, and dispatch reference where applicable. Authorization and tenant boundaries apply to reads as well as writes.
|
||||||
|
|
||||||
|
`DISPATCHED` is a staff-recorded dispatch claim. This phase does not reserve or deduct stock, purchase postage, verify carrier delivery, or bill the partner. Those steps require later inventory/shipping and receivables integration. Operators should only record dispatch after a real handoff.
|
||||||
|
|
@ -42,6 +42,7 @@ Business verification, price lists, MOQ, quotations, credit policies, samples, b
|
||||||
- 3B (implemented): account-specific, currency-scoped variant price lists and minimum quantities, with verified-account activation, immutable active terms, and a merchandise price check. Order integration remains a later milestone.
|
- 3B (implemented): account-specific, currency-scoped variant price lists and minimum quantities, with verified-account activation, immutable active terms, and a merchandise price check. Order integration remains a later milestone.
|
||||||
- 3C (implemented): staff-issued merchandise quotations with immutable account and price snapshots, expiry, idempotent issuance, and one auditable customer response. Tax, shipping, stock reservation, and order conversion remain later milestones.
|
- 3C (implemented): staff-issued merchandise quotations with immutable account and price snapshots, expiry, idempotent issuance, and one auditable customer response. Tax, shipping, stock reservation, and order conversion remain later milestones.
|
||||||
- 3D (implemented): staff-proposed credit limits and net terms with independent review, immutable decision history, suspension, and one active policy per business account and currency. Credit exposure, receivables, payment collection, and order enforcement remain later milestones.
|
- 3D (implemented): staff-proposed credit limits and net terms with independent review, immutable decision history, suspension, and one active policy per business account and currency. Credit exposure, receivables, payment collection, and order enforcement remain later milestones.
|
||||||
|
- 3E (implemented): verified-account sample requests with immutable variant snapshots, independent review, and auditable manual dispatch references. Stock deduction, carrier integration, and sample billing remain later milestones.
|
||||||
|
|
||||||
## Phase 4: Growth channels
|
## Phase 4: Growth channels
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -41,6 +41,7 @@ model BusinessAccount {
|
||||||
priceLists B2bPriceList[]
|
priceLists B2bPriceList[]
|
||||||
quotes B2bQuote[]
|
quotes B2bQuote[]
|
||||||
creditPolicies B2bCreditPolicy[]
|
creditPolicies B2bCreditPolicy[]
|
||||||
|
sampleRequests B2bSampleRequest[]
|
||||||
@@unique([organizationId, code])
|
@@unique([organizationId, code])
|
||||||
@@unique([organizationId, countryCode, registrationNumber])
|
@@unique([organizationId, countryCode, registrationNumber])
|
||||||
@@unique([id, organizationId])
|
@@unique([id, organizationId])
|
||||||
|
|
|
||||||
|
|
@ -40,6 +40,7 @@ model ProductVariant {
|
||||||
boms ProductBom[]
|
boms ProductBom[]
|
||||||
b2bPriceListItems B2bPriceListItem[]
|
b2bPriceListItems B2bPriceListItem[]
|
||||||
b2bQuoteLines B2bQuoteLine[]
|
b2bQuoteLines B2bQuoteLine[]
|
||||||
|
b2bSampleRequests B2bSampleRequest[]
|
||||||
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])
|
||||||
|
|
|
||||||
|
|
@ -36,5 +36,6 @@
|
||||||
"20260930010000_b2b_business_verification": "1ab6537ff21436ce3421024f6f61e647c2c82a35a09a769833c6b82cdccca32b",
|
"20260930010000_b2b_business_verification": "1ab6537ff21436ce3421024f6f61e647c2c82a35a09a769833c6b82cdccca32b",
|
||||||
"20260930011800_b2b_price_lists": "c2f29a61c6fee93cbffb9d67654c323b2894b3aad7bb296b514f46b623db62d9",
|
"20260930011800_b2b_price_lists": "c2f29a61c6fee93cbffb9d67654c323b2894b3aad7bb296b514f46b623db62d9",
|
||||||
"20260930190500_b2b_quotations": "0497ece6cb035687548773ce265842125fa1a655e5951e8d958290d664f5c3f0",
|
"20260930190500_b2b_quotations": "0497ece6cb035687548773ce265842125fa1a655e5951e8d958290d664f5c3f0",
|
||||||
"20261001124700_b2b_credit_policies": "a831dc4568c19d8856be27dcb60ae4a7f8155dbeeb797cec2c2dd9f80b392837"
|
"20261001124700_b2b_credit_policies": "a831dc4568c19d8856be27dcb60ae4a7f8155dbeeb797cec2c2dd9f80b392837",
|
||||||
|
"20261001234900_b2b_sample_requests": "f4fb334341d996188dbea3fb85dbe5166bffd35bc8872f2c8404b6458bc7c142"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,106 @@
|
||||||
|
CREATE TYPE "B2bSampleStatus" AS ENUM ('REQUESTED', 'APPROVED', 'REJECTED', 'DISPATCHED');
|
||||||
|
CREATE TYPE "B2bSampleEventKind" AS ENUM ('APPROVED', 'REJECTED', 'DISPATCHED');
|
||||||
|
CREATE TABLE "b2b_sample_requests" (
|
||||||
|
"id" UUID NOT NULL PRIMARY KEY,
|
||||||
|
"organization_id" UUID NOT NULL,
|
||||||
|
"account_id" UUID NOT NULL,
|
||||||
|
"variant_id" UUID NOT NULL,
|
||||||
|
"requested_by_id" UUID NOT NULL,
|
||||||
|
"sku" VARCHAR(64) NOT NULL,
|
||||||
|
"variant_name" VARCHAR(160) NOT NULL,
|
||||||
|
"quantity" INTEGER NOT NULL,
|
||||||
|
"purpose" VARCHAR(500) NOT NULL,
|
||||||
|
"status" "B2bSampleStatus" NOT NULL DEFAULT 'REQUESTED',
|
||||||
|
"idempotency_key" UUID NOT NULL,
|
||||||
|
"request_hash" CHAR(64) NOT NULL,
|
||||||
|
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMPTZ(3) NOT NULL,
|
||||||
|
CONSTRAINT "b2b_sample_requests_quantity" CHECK ("quantity" BETWEEN 1 AND 100),
|
||||||
|
CONSTRAINT "b2b_sample_requests_purpose" CHECK (char_length(btrim("purpose")) BETWEEN 3 AND 500),
|
||||||
|
CONSTRAINT "b2b_sample_requests_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$')
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX "b2b_sample_requests_id_organization_id_key" ON "b2b_sample_requests"("id", "organization_id");
|
||||||
|
CREATE UNIQUE INDEX "b2b_sample_requests_organization_id_idempotency_key_key" ON "b2b_sample_requests"("organization_id", "idempotency_key");
|
||||||
|
CREATE INDEX "b2b_sample_requests_organization_id_account_id_created_at_i_idx" ON "b2b_sample_requests"("organization_id", "account_id", "created_at", "id");
|
||||||
|
ALTER TABLE "b2b_sample_requests" ADD CONSTRAINT "b2b_sample_requests_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "b2b_sample_requests" ADD CONSTRAINT "b2b_sample_requests_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_sample_requests" ADD CONSTRAINT "b2b_sample_requests_variant_id_organization_id_fkey" FOREIGN KEY ("variant_id", "organization_id") REFERENCES "product_variants"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "b2b_sample_requests" ADD CONSTRAINT "b2b_sample_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;
|
||||||
|
|
||||||
|
CREATE TABLE "b2b_sample_events" (
|
||||||
|
"id" UUID NOT NULL PRIMARY KEY,
|
||||||
|
"organization_id" UUID NOT NULL,
|
||||||
|
"request_id" UUID NOT NULL,
|
||||||
|
"actor_id" UUID NOT NULL,
|
||||||
|
"sequence" INTEGER NOT NULL,
|
||||||
|
"kind" "B2bSampleEventKind" NOT NULL,
|
||||||
|
"note" VARCHAR(500) NOT NULL,
|
||||||
|
"dispatch_reference" VARCHAR(100),
|
||||||
|
"idempotency_key" UUID NOT NULL,
|
||||||
|
"request_hash" CHAR(64) NOT NULL,
|
||||||
|
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
CONSTRAINT "b2b_sample_events_sequence" CHECK ("sequence" BETWEEN 1 AND 2),
|
||||||
|
CONSTRAINT "b2b_sample_events_note" CHECK (char_length(btrim("note")) BETWEEN 3 AND 500),
|
||||||
|
CONSTRAINT "b2b_sample_events_reference" CHECK (("kind" = 'DISPATCHED' AND char_length(btrim("dispatch_reference")) BETWEEN 3 AND 100) OR ("kind" <> 'DISPATCHED' AND "dispatch_reference" IS NULL)),
|
||||||
|
CONSTRAINT "b2b_sample_events_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$')
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX "b2b_sample_events_request_id_sequence_key" ON "b2b_sample_events"("request_id", "sequence");
|
||||||
|
CREATE UNIQUE INDEX "b2b_sample_events_organization_id_idempotency_key_key" ON "b2b_sample_events"("organization_id", "idempotency_key");
|
||||||
|
CREATE INDEX "b2b_sample_events_organization_id_request_id_sequence_idx" ON "b2b_sample_events"("organization_id", "request_id", "sequence");
|
||||||
|
ALTER TABLE "b2b_sample_events" ADD CONSTRAINT "b2b_sample_events_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "b2b_sample_events" ADD CONSTRAINT "b2b_sample_events_request_id_organization_id_fkey" FOREIGN KEY ("request_id", "organization_id") REFERENCES "b2b_sample_requests"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "b2b_sample_events" ADD CONSTRAINT "b2b_sample_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_b2b_sample_request() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE latest "B2bSampleEventKind";
|
||||||
|
BEGIN
|
||||||
|
IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Sample requests cannot be deleted'; END IF;
|
||||||
|
IF TG_OP = 'INSERT' THEN
|
||||||
|
IF NEW.status <> 'REQUESTED' THEN RAISE EXCEPTION 'Sample requests must start requested'; END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END IF;
|
||||||
|
IF (NEW.id, NEW.organization_id, NEW.account_id, NEW.variant_id, NEW.requested_by_id,
|
||||||
|
NEW.sku, NEW.variant_name, NEW.quantity, NEW.purpose, NEW.idempotency_key, NEW.request_hash, NEW.created_at)
|
||||||
|
IS DISTINCT FROM (OLD.id, OLD.organization_id, OLD.account_id, OLD.variant_id, OLD.requested_by_id,
|
||||||
|
OLD.sku, OLD.variant_name, OLD.quantity, OLD.purpose, OLD.idempotency_key, OLD.request_hash, OLD.created_at)
|
||||||
|
THEN RAISE EXCEPTION 'Sample request terms are immutable'; END IF;
|
||||||
|
SELECT kind INTO latest FROM b2b_sample_events WHERE request_id = NEW.id ORDER BY sequence DESC LIMIT 1;
|
||||||
|
IF NOT ((OLD.status = 'REQUESTED' AND NEW.status = 'APPROVED' AND latest = 'APPROVED')
|
||||||
|
OR (OLD.status = 'REQUESTED' AND NEW.status = 'REJECTED' AND latest = 'REJECTED')
|
||||||
|
OR (OLD.status = 'APPROVED' AND NEW.status = 'DISPATCHED' AND latest = 'DISPATCHED'))
|
||||||
|
THEN RAISE EXCEPTION 'Sample transition lacks matching event'; END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
CREATE TRIGGER b2b_sample_requests_guard BEFORE INSERT OR UPDATE OR DELETE ON b2b_sample_requests FOR EACH ROW EXECUTE FUNCTION guard_b2b_sample_request();
|
||||||
|
CREATE FUNCTION guard_b2b_sample_event() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE request b2b_sample_requests%ROWTYPE;
|
||||||
|
BEGIN
|
||||||
|
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Sample events are immutable'; END IF;
|
||||||
|
SELECT * INTO request FROM b2b_sample_requests WHERE id = NEW.request_id AND organization_id = NEW.organization_id;
|
||||||
|
IF NEW.kind IN ('APPROVED', 'REJECTED') THEN
|
||||||
|
IF NEW.sequence <> 1 OR request.status <> 'REQUESTED' OR NEW.actor_id = request.requested_by_id
|
||||||
|
THEN RAISE EXCEPTION 'Sample decision requires an independent reviewer and requested sample'; END IF;
|
||||||
|
ELSIF NEW.kind = 'DISPATCHED' THEN
|
||||||
|
IF NEW.sequence <> 2 OR request.status <> 'APPROVED'
|
||||||
|
THEN RAISE EXCEPTION 'Sample dispatch requires an approved request'; END IF;
|
||||||
|
END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
CREATE TRIGGER b2b_sample_events_guard BEFORE INSERT OR UPDATE OR DELETE ON b2b_sample_events FOR EACH ROW EXECUTE FUNCTION guard_b2b_sample_event();
|
||||||
|
CREATE FUNCTION check_b2b_sample_event_status() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE current_status "B2bSampleStatus";
|
||||||
|
BEGIN
|
||||||
|
SELECT status INTO current_status FROM b2b_sample_requests WHERE id = NEW.request_id;
|
||||||
|
IF (NEW.kind = 'APPROVED' AND current_status <> 'APPROVED')
|
||||||
|
OR (NEW.kind = 'REJECTED' AND current_status <> 'REJECTED')
|
||||||
|
OR (NEW.kind = 'DISPATCHED' AND current_status <> 'DISPATCHED')
|
||||||
|
THEN RAISE EXCEPTION 'Sample event must update request status in the same transaction'; END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
CREATE CONSTRAINT TRIGGER b2b_sample_events_status_guard AFTER INSERT ON b2b_sample_events
|
||||||
|
DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION check_b2b_sample_event_status();
|
||||||
|
UPDATE "roles" SET "permissions" = ARRAY(SELECT DISTINCT unnest("permissions" || ARRAY['b2b.sample.read', 'b2b.sample.request', 'b2b.sample.review', 'b2b.sample.dispatch']))
|
||||||
|
WHERE "is_system" = true AND "name" = 'Owner';
|
||||||
|
|
@ -0,0 +1,59 @@
|
||||||
|
enum B2bSampleStatus {
|
||||||
|
REQUESTED
|
||||||
|
APPROVED
|
||||||
|
REJECTED
|
||||||
|
DISPATCHED
|
||||||
|
}
|
||||||
|
|
||||||
|
enum B2bSampleEventKind {
|
||||||
|
APPROVED
|
||||||
|
REJECTED
|
||||||
|
DISPATCHED
|
||||||
|
}
|
||||||
|
|
||||||
|
model B2bSampleRequest {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
organizationId String @map("organization_id") @db.Uuid
|
||||||
|
accountId String @map("account_id") @db.Uuid
|
||||||
|
variantId String @map("variant_id") @db.Uuid
|
||||||
|
requestedById String @map("requested_by_id") @db.Uuid
|
||||||
|
sku String @db.VarChar(64)
|
||||||
|
variantName String @map("variant_name") @db.VarChar(160)
|
||||||
|
quantity Int
|
||||||
|
purpose String @db.VarChar(500)
|
||||||
|
status B2bSampleStatus @default(REQUESTED)
|
||||||
|
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)
|
||||||
|
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)
|
||||||
|
variant ProductVariant @relation(fields: [variantId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
|
requestedBy User @relation(fields: [requestedById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
|
events B2bSampleEvent[]
|
||||||
|
@@unique([id, organizationId])
|
||||||
|
@@unique([organizationId, idempotencyKey])
|
||||||
|
@@index([organizationId, accountId, createdAt, id])
|
||||||
|
@@map("b2b_sample_requests")
|
||||||
|
}
|
||||||
|
|
||||||
|
model B2bSampleEvent {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
organizationId String @map("organization_id") @db.Uuid
|
||||||
|
requestId String @map("request_id") @db.Uuid
|
||||||
|
actorId String @map("actor_id") @db.Uuid
|
||||||
|
sequence Int
|
||||||
|
kind B2bSampleEventKind
|
||||||
|
note String @db.VarChar(500)
|
||||||
|
dispatchReference String? @map("dispatch_reference") @db.VarChar(100)
|
||||||
|
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 B2bSampleRequest @relation(fields: [requestId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
|
actor User @relation(fields: [actorId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
|
@@unique([requestId, sequence])
|
||||||
|
@@unique([organizationId, idempotencyKey])
|
||||||
|
@@index([organizationId, requestId, sequence])
|
||||||
|
@@map("b2b_sample_events")
|
||||||
|
}
|
||||||
|
|
@ -60,6 +60,8 @@ model Organization {
|
||||||
b2bQuoteResponses B2bQuoteResponse[]
|
b2bQuoteResponses B2bQuoteResponse[]
|
||||||
b2bCreditPolicies B2bCreditPolicy[]
|
b2bCreditPolicies B2bCreditPolicy[]
|
||||||
b2bCreditEvents B2bCreditEvent[]
|
b2bCreditEvents B2bCreditEvent[]
|
||||||
|
b2bSampleRequests B2bSampleRequest[]
|
||||||
|
b2bSampleEvents B2bSampleEvent[]
|
||||||
@@map("organizations")
|
@@map("organizations")
|
||||||
}
|
}
|
||||||
model User {
|
model User {
|
||||||
|
|
@ -108,6 +110,8 @@ model User {
|
||||||
b2bQuoteResponses B2bQuoteResponse[]
|
b2bQuoteResponses B2bQuoteResponse[]
|
||||||
b2bCreditPolicies B2bCreditPolicy[]
|
b2bCreditPolicies B2bCreditPolicy[]
|
||||||
b2bCreditEvents B2bCreditEvent[]
|
b2bCreditEvents B2bCreditEvent[]
|
||||||
|
b2bSampleRequests B2bSampleRequest[]
|
||||||
|
b2bSampleEvents B2bSampleEvent[]
|
||||||
stockEntries StockLedger[]
|
stockEntries StockLedger[]
|
||||||
stockReservations StockReservation[]
|
stockReservations StockReservation[]
|
||||||
carts Cart[]
|
carts Cart[]
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,9 @@ import { QuoteResponseStore } from './quote-response.store';
|
||||||
import { CreditPoliciesController } from './credit-policies.controller';
|
import { CreditPoliciesController } from './credit-policies.controller';
|
||||||
import { CreditStore } from './credit.store';
|
import { CreditStore } from './credit.store';
|
||||||
import { CreditReviewStore } from './credit-review.store';
|
import { CreditReviewStore } from './credit-review.store';
|
||||||
|
import { SamplesController } from './samples.controller';
|
||||||
|
import { SampleStore } from './sample.store';
|
||||||
|
import { SampleActionStore } from './sample-action.store';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [DatabaseModule, IdentityModule],
|
imports: [DatabaseModule, IdentityModule],
|
||||||
|
|
@ -23,6 +26,7 @@ import { CreditReviewStore } from './credit-review.store';
|
||||||
PriceListItemsController,
|
PriceListItemsController,
|
||||||
QuotesController,
|
QuotesController,
|
||||||
CreditPoliciesController,
|
CreditPoliciesController,
|
||||||
|
SamplesController,
|
||||||
],
|
],
|
||||||
providers: [
|
providers: [
|
||||||
BusinessStore,
|
BusinessStore,
|
||||||
|
|
@ -33,6 +37,8 @@ import { CreditReviewStore } from './credit-review.store';
|
||||||
QuoteResponseStore,
|
QuoteResponseStore,
|
||||||
CreditStore,
|
CreditStore,
|
||||||
CreditReviewStore,
|
CreditReviewStore,
|
||||||
|
SampleStore,
|
||||||
|
SampleActionStore,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class B2bModule {}
|
export class B2bModule {}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,125 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { AppError } from '../common/errors/app-error';
|
||||||
|
import { commandHash } from '../common/idempotency';
|
||||||
|
import type { Prisma } from '../generated/prisma/client';
|
||||||
|
import { AccessStore } from '../identity/access.store';
|
||||||
|
import { recordAudit } from '../identity/audit';
|
||||||
|
import type { Principal } from '../identity/identity.types';
|
||||||
|
import { isVerifiedBusinessAccount } from './business-verification';
|
||||||
|
import { requireSample } from './sample-lookup';
|
||||||
|
import type {
|
||||||
|
SampleDecisionInput,
|
||||||
|
SampleDispatchInput,
|
||||||
|
} from './sample.schemas';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SampleActionStore {
|
||||||
|
constructor(private readonly access: AccessStore) {}
|
||||||
|
|
||||||
|
decide(actor: Principal, id: string, input: SampleDecisionInput) {
|
||||||
|
return this.access.mutate(actor, 'b2b.sample.review', async (tx) => {
|
||||||
|
const sample = await requireSample(tx, actor.organizationId, id);
|
||||||
|
const hash = commandHash(id, input.decision, input.note);
|
||||||
|
if (
|
||||||
|
await this.replay(tx, actor.organizationId, input.idempotencyKey, hash)
|
||||||
|
)
|
||||||
|
return sample;
|
||||||
|
if (sample.status !== 'REQUESTED')
|
||||||
|
throw new AppError('B2B_SAMPLE_REVIEW_STATE');
|
||||||
|
if (sample.requestedById === actor.userId)
|
||||||
|
throw new AppError('B2B_SAMPLE_SELF_REVIEW');
|
||||||
|
if (
|
||||||
|
input.decision === 'APPROVED' &&
|
||||||
|
!(await isVerifiedBusinessAccount(
|
||||||
|
tx,
|
||||||
|
actor.organizationId,
|
||||||
|
sample.accountId,
|
||||||
|
))
|
||||||
|
)
|
||||||
|
throw new AppError('B2B_SAMPLE_ACCOUNT_UNVERIFIED');
|
||||||
|
await tx.b2bSampleEvent.create({
|
||||||
|
data: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
requestId: id,
|
||||||
|
actorId: actor.userId,
|
||||||
|
sequence: 1,
|
||||||
|
kind: input.decision,
|
||||||
|
note: input.note,
|
||||||
|
idempotencyKey: input.idempotencyKey,
|
||||||
|
requestHash: hash,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await tx.b2bSampleRequest.update({
|
||||||
|
where: { id },
|
||||||
|
data: { status: input.decision },
|
||||||
|
});
|
||||||
|
await recordAudit(
|
||||||
|
tx,
|
||||||
|
actor.organizationId,
|
||||||
|
actor.userId,
|
||||||
|
`b2b_sample.${input.decision.toLowerCase()}`,
|
||||||
|
id,
|
||||||
|
);
|
||||||
|
return requireSample(tx, actor.organizationId, id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
dispatch(actor: Principal, id: string, input: SampleDispatchInput) {
|
||||||
|
return this.access.mutate(actor, 'b2b.sample.dispatch', async (tx) => {
|
||||||
|
const sample = await requireSample(tx, actor.organizationId, id);
|
||||||
|
const hash = commandHash(
|
||||||
|
id,
|
||||||
|
'DISPATCHED',
|
||||||
|
input.dispatchReference,
|
||||||
|
input.note,
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
await this.replay(tx, actor.organizationId, input.idempotencyKey, hash)
|
||||||
|
)
|
||||||
|
return sample;
|
||||||
|
if (sample.status !== 'APPROVED')
|
||||||
|
throw new AppError('B2B_SAMPLE_DISPATCH_STATE');
|
||||||
|
await tx.b2bSampleEvent.create({
|
||||||
|
data: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
requestId: id,
|
||||||
|
actorId: actor.userId,
|
||||||
|
sequence: 2,
|
||||||
|
kind: 'DISPATCHED',
|
||||||
|
note: input.note,
|
||||||
|
dispatchReference: input.dispatchReference,
|
||||||
|
idempotencyKey: input.idempotencyKey,
|
||||||
|
requestHash: hash,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await tx.b2bSampleRequest.update({
|
||||||
|
where: { id },
|
||||||
|
data: { status: 'DISPATCHED' },
|
||||||
|
});
|
||||||
|
await recordAudit(
|
||||||
|
tx,
|
||||||
|
actor.organizationId,
|
||||||
|
actor.userId,
|
||||||
|
'b2b_sample.dispatched',
|
||||||
|
id,
|
||||||
|
);
|
||||||
|
return requireSample(tx, actor.organizationId, id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async replay(
|
||||||
|
tx: Prisma.TransactionClient,
|
||||||
|
organizationId: string,
|
||||||
|
key: string,
|
||||||
|
hash: string,
|
||||||
|
) {
|
||||||
|
const event = await tx.b2bSampleEvent.findUnique({
|
||||||
|
where: {
|
||||||
|
organizationId_idempotencyKey: { organizationId, idempotencyKey: key },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (event && event.requestHash !== hash)
|
||||||
|
throw new AppError('B2B_SAMPLE_EVENT_REPLAY_CONFLICT');
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,21 @@
|
||||||
|
import { AppError } from '../common/errors/app-error';
|
||||||
|
import type { DatabaseService } from '../database/database.service';
|
||||||
|
import type { Prisma } from '../generated/prisma/client';
|
||||||
|
|
||||||
|
type Db = DatabaseService | Prisma.TransactionClient;
|
||||||
|
export const sampleInclude = {
|
||||||
|
events: { orderBy: { sequence: 'asc' as const } },
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function requireSample(
|
||||||
|
db: Db,
|
||||||
|
organizationId: string,
|
||||||
|
id: string,
|
||||||
|
) {
|
||||||
|
const sample = await db.b2bSampleRequest.findFirst({
|
||||||
|
where: { id, organizationId },
|
||||||
|
include: sampleInclude,
|
||||||
|
});
|
||||||
|
if (!sample) throw new AppError('B2B_SAMPLE_NOT_FOUND');
|
||||||
|
return sample;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,39 @@
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { text } from '../common/input';
|
||||||
|
import { pageSchema } from '../identity/identity.schemas';
|
||||||
|
|
||||||
|
export const sampleRequestSchema = z
|
||||||
|
.object({
|
||||||
|
accountId: z.uuid(),
|
||||||
|
variantId: z.uuid(),
|
||||||
|
quantity: z.number().int().min(1).max(100),
|
||||||
|
purpose: text(500, 3),
|
||||||
|
idempotencyKey: z.uuid(),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
export const sampleDecisionSchema = z
|
||||||
|
.object({
|
||||||
|
decision: z.enum(['APPROVED', 'REJECTED']),
|
||||||
|
note: text(500, 3),
|
||||||
|
idempotencyKey: z.uuid(),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
export const sampleDispatchSchema = z
|
||||||
|
.object({
|
||||||
|
dispatchReference: text(100, 3),
|
||||||
|
note: text(500, 3),
|
||||||
|
idempotencyKey: z.uuid(),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
export const sampleQuerySchema = pageSchema
|
||||||
|
.extend({
|
||||||
|
accountId: z.uuid().optional(),
|
||||||
|
status: z
|
||||||
|
.enum(['REQUESTED', 'APPROVED', 'REJECTED', 'DISPATCHED'])
|
||||||
|
.optional(),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
export type SampleRequestInput = z.infer<typeof sampleRequestSchema>;
|
||||||
|
export type SampleDecisionInput = z.infer<typeof sampleDecisionSchema>;
|
||||||
|
export type SampleDispatchInput = z.infer<typeof sampleDispatchSchema>;
|
||||||
|
export type SampleQuery = z.infer<typeof sampleQuerySchema>;
|
||||||
|
|
@ -0,0 +1,100 @@
|
||||||
|
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 { requireSample, sampleInclude } from './sample-lookup';
|
||||||
|
import type { SampleQuery, SampleRequestInput } from './sample.schemas';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SampleStore {
|
||||||
|
constructor(
|
||||||
|
private readonly db: DatabaseService,
|
||||||
|
private readonly access: AccessStore,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
list(actor: Principal, query: SampleQuery) {
|
||||||
|
return this.db.b2bSampleRequest.findMany({
|
||||||
|
where: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
...(query.accountId ? { accountId: query.accountId } : {}),
|
||||||
|
...(query.status ? { status: query.status } : {}),
|
||||||
|
},
|
||||||
|
include: sampleInclude,
|
||||||
|
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||||
|
take: query.limit,
|
||||||
|
skip: query.offset,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
get(actor: Principal, id: string) {
|
||||||
|
return requireSample(this.db, actor.organizationId, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
request(actor: Principal, input: SampleRequestInput) {
|
||||||
|
const hash = commandHash(
|
||||||
|
input.accountId,
|
||||||
|
input.variantId,
|
||||||
|
input.quantity,
|
||||||
|
input.purpose,
|
||||||
|
);
|
||||||
|
return this.access.mutate(actor, 'b2b.sample.request', async (tx) => {
|
||||||
|
const replay = await tx.b2bSampleRequest.findUnique({
|
||||||
|
where: {
|
||||||
|
organizationId_idempotencyKey: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
idempotencyKey: input.idempotencyKey,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
include: sampleInclude,
|
||||||
|
});
|
||||||
|
if (replay) {
|
||||||
|
if (replay.requestHash !== hash)
|
||||||
|
throw new AppError('B2B_SAMPLE_REQUEST_REPLAY_CONFLICT');
|
||||||
|
return replay;
|
||||||
|
}
|
||||||
|
await requireBusinessAccount(tx, actor.organizationId, input.accountId);
|
||||||
|
if (
|
||||||
|
!(await isVerifiedBusinessAccount(
|
||||||
|
tx,
|
||||||
|
actor.organizationId,
|
||||||
|
input.accountId,
|
||||||
|
))
|
||||||
|
)
|
||||||
|
throw new AppError('B2B_SAMPLE_ACCOUNT_UNVERIFIED');
|
||||||
|
const variant = await tx.productVariant.findFirst({
|
||||||
|
where: { id: input.variantId, organizationId: actor.organizationId },
|
||||||
|
include: { product: true },
|
||||||
|
});
|
||||||
|
if (!variant || !variant.active || variant.product.status !== 'PUBLISHED')
|
||||||
|
throw new AppError('B2B_SAMPLE_VARIANT_INELIGIBLE');
|
||||||
|
const sample = await tx.b2bSampleRequest.create({
|
||||||
|
data: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
accountId: input.accountId,
|
||||||
|
variantId: input.variantId,
|
||||||
|
requestedById: actor.userId,
|
||||||
|
sku: variant.sku,
|
||||||
|
variantName: variant.name,
|
||||||
|
quantity: input.quantity,
|
||||||
|
purpose: input.purpose,
|
||||||
|
idempotencyKey: input.idempotencyKey,
|
||||||
|
requestHash: hash,
|
||||||
|
},
|
||||||
|
include: sampleInclude,
|
||||||
|
});
|
||||||
|
await recordAudit(
|
||||||
|
tx,
|
||||||
|
actor.organizationId,
|
||||||
|
actor.userId,
|
||||||
|
'b2b_sample.requested',
|
||||||
|
sample.id,
|
||||||
|
);
|
||||||
|
return sample;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,82 @@
|
||||||
|
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 { SampleActionStore } from './sample-action.store';
|
||||||
|
import { SampleStore } from './sample.store';
|
||||||
|
import {
|
||||||
|
sampleDecisionSchema,
|
||||||
|
sampleDispatchSchema,
|
||||||
|
sampleQuerySchema,
|
||||||
|
sampleRequestSchema,
|
||||||
|
type SampleDecisionInput,
|
||||||
|
type SampleDispatchInput,
|
||||||
|
type SampleQuery,
|
||||||
|
type SampleRequestInput,
|
||||||
|
} from './sample.schemas';
|
||||||
|
|
||||||
|
@Controller('b2b/samples')
|
||||||
|
export class SamplesController {
|
||||||
|
constructor(
|
||||||
|
private readonly samples: SampleStore,
|
||||||
|
private readonly actions: SampleActionStore,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
@RequirePermission('b2b.sample.read')
|
||||||
|
list(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Query(new SchemaPipe(sampleQuerySchema)) query: SampleQuery,
|
||||||
|
) {
|
||||||
|
return this.samples.list(actor, query);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
@RequirePermission('b2b.sample.request')
|
||||||
|
request(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Body(new SchemaPipe(sampleRequestSchema)) input: SampleRequestInput,
|
||||||
|
) {
|
||||||
|
return this.samples.request(actor, input);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':id')
|
||||||
|
@RequirePermission('b2b.sample.read')
|
||||||
|
get(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
) {
|
||||||
|
return this.samples.get(actor, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post(':id/decision')
|
||||||
|
@RequirePermission('b2b.sample.review')
|
||||||
|
decide(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
@Body(new SchemaPipe(sampleDecisionSchema)) input: SampleDecisionInput,
|
||||||
|
) {
|
||||||
|
return this.actions.decide(actor, id, input);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post(':id/dispatch')
|
||||||
|
@RequirePermission('b2b.sample.dispatch')
|
||||||
|
dispatch(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
@Body(new SchemaPipe(sampleDispatchSchema)) input: SampleDispatchInput,
|
||||||
|
) {
|
||||||
|
return this.actions.dispatch(actor, id, input);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,42 @@
|
||||||
|
export const B2B_SAMPLE_ERRORS = {
|
||||||
|
B2B_SAMPLE_NOT_FOUND: [
|
||||||
|
404,
|
||||||
|
'Sample request not found',
|
||||||
|
'Scoped B2B sample request lookup failed',
|
||||||
|
],
|
||||||
|
B2B_SAMPLE_ACCOUNT_UNVERIFIED: [
|
||||||
|
409,
|
||||||
|
'Business account must be verified before requesting samples',
|
||||||
|
'B2B sample account verification gate failed',
|
||||||
|
],
|
||||||
|
B2B_SAMPLE_VARIANT_INELIGIBLE: [
|
||||||
|
409,
|
||||||
|
'Sample variant must be active and published',
|
||||||
|
'B2B sample variant eligibility failed',
|
||||||
|
],
|
||||||
|
B2B_SAMPLE_REQUEST_REPLAY_CONFLICT: [
|
||||||
|
409,
|
||||||
|
'Idempotency key was used for a different sample request',
|
||||||
|
'B2B sample request replay payload mismatch',
|
||||||
|
],
|
||||||
|
B2B_SAMPLE_EVENT_REPLAY_CONFLICT: [
|
||||||
|
409,
|
||||||
|
'Idempotency key was used for a different sample action',
|
||||||
|
'B2B sample event replay payload mismatch',
|
||||||
|
],
|
||||||
|
B2B_SAMPLE_REVIEW_STATE: [
|
||||||
|
409,
|
||||||
|
'Sample request is no longer awaiting review',
|
||||||
|
'B2B sample review state invalid',
|
||||||
|
],
|
||||||
|
B2B_SAMPLE_SELF_REVIEW: [
|
||||||
|
403,
|
||||||
|
'A different staff member must review this sample request',
|
||||||
|
'B2B sample self-review rejected',
|
||||||
|
],
|
||||||
|
B2B_SAMPLE_DISPATCH_STATE: [
|
||||||
|
409,
|
||||||
|
'Only an approved sample can be dispatched',
|
||||||
|
'B2B sample dispatch state invalid',
|
||||||
|
],
|
||||||
|
} as const;
|
||||||
|
|
@ -6,6 +6,7 @@ import { B2B_ERRORS } from './b2b-errors';
|
||||||
import { B2B_PRICE_ERRORS } from './b2b-price-errors';
|
import { B2B_PRICE_ERRORS } from './b2b-price-errors';
|
||||||
import { B2B_QUOTE_ERRORS } from './b2b-quote-errors';
|
import { B2B_QUOTE_ERRORS } from './b2b-quote-errors';
|
||||||
import { B2B_CREDIT_ERRORS } from './b2b-credit-errors';
|
import { B2B_CREDIT_ERRORS } from './b2b-credit-errors';
|
||||||
|
import { B2B_SAMPLE_ERRORS } from './b2b-sample-errors';
|
||||||
export const ERRORS = {
|
export const ERRORS = {
|
||||||
...PLATFORM_ERRORS,
|
...PLATFORM_ERRORS,
|
||||||
...COMMERCE_ERRORS,
|
...COMMERCE_ERRORS,
|
||||||
|
|
@ -15,5 +16,6 @@ export const ERRORS = {
|
||||||
...B2B_PRICE_ERRORS,
|
...B2B_PRICE_ERRORS,
|
||||||
...B2B_QUOTE_ERRORS,
|
...B2B_QUOTE_ERRORS,
|
||||||
...B2B_CREDIT_ERRORS,
|
...B2B_CREDIT_ERRORS,
|
||||||
|
...B2B_SAMPLE_ERRORS,
|
||||||
} as const;
|
} as const;
|
||||||
export type ErrorCode = keyof typeof ERRORS;
|
export type ErrorCode = keyof typeof ERRORS;
|
||||||
|
|
|
||||||
|
|
@ -46,5 +46,9 @@ export const PERMISSIONS = [
|
||||||
'b2b.credit.read',
|
'b2b.credit.read',
|
||||||
'b2b.credit.propose',
|
'b2b.credit.propose',
|
||||||
'b2b.credit.review',
|
'b2b.credit.review',
|
||||||
|
'b2b.sample.read',
|
||||||
|
'b2b.sample.request',
|
||||||
|
'b2b.sample.review',
|
||||||
|
'b2b.sample.dispatch',
|
||||||
] as const;
|
] as const;
|
||||||
export type Permission = (typeof PERMISSIONS)[number];
|
export type Permission = (typeof PERMISSIONS)[number];
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,38 @@
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import {
|
||||||
|
sampleRequestSchema,
|
||||||
|
sampleDispatchSchema,
|
||||||
|
} from '../src/b2b/sample.schemas';
|
||||||
|
|
||||||
|
describe('B2B sample validation', () => {
|
||||||
|
const request = () => ({
|
||||||
|
accountId: randomUUID(),
|
||||||
|
variantId: randomUUID(),
|
||||||
|
quantity: 1,
|
||||||
|
purpose: 'Product evaluation',
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts one to one hundred samples', () => {
|
||||||
|
expect(sampleRequestSchema.safeParse(request()).success).toBe(true);
|
||||||
|
expect(
|
||||||
|
sampleRequestSchema.safeParse({ ...request(), quantity: 100 }).success,
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([0, 101, 1.5])('rejects invalid quantity %s', (quantity) => {
|
||||||
|
expect(
|
||||||
|
sampleRequestSchema.safeParse({ ...request(), quantity }).success,
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires a meaningful dispatch reference', () => {
|
||||||
|
expect(
|
||||||
|
sampleDispatchSchema.safeParse({
|
||||||
|
dispatchReference: ' ',
|
||||||
|
note: 'Handed to courier',
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
}).success,
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,296 @@
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
||||||
|
import { secondActor, seedProduct } from './helpers/commerce';
|
||||||
|
|
||||||
|
describe('B2B samples', () => {
|
||||||
|
let ctx: IdentityApp;
|
||||||
|
const auth = { type: 'bearer' as const };
|
||||||
|
const url = '/api/v1/b2b/samples';
|
||||||
|
|
||||||
|
async function account(verified = true) {
|
||||||
|
const created = await ctx
|
||||||
|
.api()
|
||||||
|
.post('/api/v1/b2b/accounts')
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({
|
||||||
|
code: `SM-${randomUUID().slice(0, 8)}`,
|
||||||
|
legalName: 'Sample Partner Limited',
|
||||||
|
tradingName: null,
|
||||||
|
registrationNumber: randomUUID(),
|
||||||
|
taxIdentifier: null,
|
||||||
|
countryCode: 'IN',
|
||||||
|
contactEmail: 'samples@example.com',
|
||||||
|
contactPhone: null,
|
||||||
|
billingLine1: '10 Market Lane',
|
||||||
|
billingCity: 'Pune',
|
||||||
|
billingRegion: 'Maharashtra',
|
||||||
|
billingPostalCode: '411001',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
const id = created.body.id as string;
|
||||||
|
if (verified) {
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`/api/v1/b2b/accounts/${id}/submit`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({ idempotencyKey: randomUUID() })
|
||||||
|
.expect(201);
|
||||||
|
const reviewer = await secondActor(ctx, true, ['b2b.verify']);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`/api/v1/b2b/accounts/${id}/decision`)
|
||||||
|
.auth(reviewer.token, auth)
|
||||||
|
.send({
|
||||||
|
decision: 'APPROVED',
|
||||||
|
note: 'Registration checked',
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
}
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
const input = (accountId: string, variantId: string) => ({
|
||||||
|
accountId,
|
||||||
|
variantId,
|
||||||
|
quantity: 4,
|
||||||
|
purpose: 'Fragrance evaluation',
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
});
|
||||||
|
const decision = (kind: 'APPROVED' | 'REJECTED') => ({
|
||||||
|
decision: kind,
|
||||||
|
note: 'Sample request reviewed',
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
ctx = await identityApp();
|
||||||
|
}, 60000);
|
||||||
|
afterAll(async () => {
|
||||||
|
await ctx?.close();
|
||||||
|
});
|
||||||
|
beforeEach(async () => {
|
||||||
|
await ctx.clearLimits();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires verified account and published variant, snapshots the item, and replays safely', async () => {
|
||||||
|
const unverified = await account(false);
|
||||||
|
const { variant } = await seedProduct(ctx, true);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(url)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send(input(unverified, variant.id))
|
||||||
|
.expect(409)
|
||||||
|
).body.code,
|
||||||
|
).toBe('B2B_SAMPLE_ACCOUNT_UNVERIFIED');
|
||||||
|
const accountId = await account();
|
||||||
|
const draft = await seedProduct(ctx);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(url)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send(input(accountId, draft.variant.id))
|
||||||
|
.expect(409)
|
||||||
|
).body.code,
|
||||||
|
).toBe('B2B_SAMPLE_VARIANT_INELIGIBLE');
|
||||||
|
const request = input(accountId, variant.id);
|
||||||
|
const created = await ctx
|
||||||
|
.api()
|
||||||
|
.post(url)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send(request)
|
||||||
|
.expect(201);
|
||||||
|
expect(created.body).toMatchObject({
|
||||||
|
status: 'REQUESTED',
|
||||||
|
sku: variant.sku,
|
||||||
|
variantName: variant.name,
|
||||||
|
quantity: 4,
|
||||||
|
events: [],
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(url)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send(request)
|
||||||
|
.expect(201)
|
||||||
|
).body.id,
|
||||||
|
).toBe(created.body.id);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(url)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({ ...request, quantity: 5 })
|
||||||
|
.expect(409)
|
||||||
|
).body.code,
|
||||||
|
).toBe('B2B_SAMPLE_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,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires independent review and records dispatch exactly once', async () => {
|
||||||
|
const accountId = await account();
|
||||||
|
const { variant } = await seedProduct(ctx, true);
|
||||||
|
const created = await ctx
|
||||||
|
.api()
|
||||||
|
.post(url)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send(input(accountId, variant.id))
|
||||||
|
.expect(201);
|
||||||
|
const id = created.body.id as string;
|
||||||
|
const approve = decision('APPROVED');
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${url}/${id}/decision`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send(approve)
|
||||||
|
.expect(403)
|
||||||
|
).body.code,
|
||||||
|
).toBe('B2B_SAMPLE_SELF_REVIEW');
|
||||||
|
const reviewer = await secondActor(ctx, true, [
|
||||||
|
'b2b.sample.review',
|
||||||
|
'b2b.sample.dispatch',
|
||||||
|
]);
|
||||||
|
const approved = await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${url}/${id}/decision`)
|
||||||
|
.auth(reviewer.token, auth)
|
||||||
|
.send(approve)
|
||||||
|
.expect(201);
|
||||||
|
expect(approved.body).toMatchObject({
|
||||||
|
status: 'APPROVED',
|
||||||
|
events: [{ kind: 'APPROVED', sequence: 1 }],
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${url}/${id}/decision`)
|
||||||
|
.auth(reviewer.token, auth)
|
||||||
|
.send(approve)
|
||||||
|
.expect(201)
|
||||||
|
).body.events,
|
||||||
|
).toHaveLength(1);
|
||||||
|
const dispatch = {
|
||||||
|
dispatchReference: 'MANUAL-123',
|
||||||
|
note: 'Handed to courier',
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
};
|
||||||
|
const sent = await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${url}/${id}/dispatch`)
|
||||||
|
.auth(reviewer.token, auth)
|
||||||
|
.send(dispatch)
|
||||||
|
.expect(201);
|
||||||
|
expect(sent.body).toMatchObject({
|
||||||
|
status: 'DISPATCHED',
|
||||||
|
events: [
|
||||||
|
{ kind: 'APPROVED' },
|
||||||
|
{ kind: 'DISPATCHED', sequence: 2, dispatchReference: 'MANUAL-123' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${url}/${id}/dispatch`)
|
||||||
|
.auth(reviewer.token, auth)
|
||||||
|
.send(dispatch)
|
||||||
|
.expect(201)
|
||||||
|
).body.events,
|
||||||
|
).toHaveLength(2);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${url}/${id}/dispatch`)
|
||||||
|
.auth(reviewer.token, auth)
|
||||||
|
.send({ ...dispatch, dispatchReference: 'CHANGED' })
|
||||||
|
.expect(409)
|
||||||
|
).body.code,
|
||||||
|
).toBe('B2B_SAMPLE_EVENT_REPLAY_CONFLICT');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects requests, enforces transition state, tenant scope, and permissions', async () => {
|
||||||
|
const accountId = await account();
|
||||||
|
const { variant } = await seedProduct(ctx, true);
|
||||||
|
const created = await ctx
|
||||||
|
.api()
|
||||||
|
.post(url)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send(input(accountId, variant.id))
|
||||||
|
.expect(201);
|
||||||
|
const id = created.body.id as string;
|
||||||
|
const reviewer = await secondActor(ctx, true, [
|
||||||
|
'b2b.sample.review',
|
||||||
|
'b2b.sample.dispatch',
|
||||||
|
]);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${url}/${id}/dispatch`)
|
||||||
|
.auth(reviewer.token, auth)
|
||||||
|
.send({
|
||||||
|
dispatchReference: 'EARLY-1',
|
||||||
|
note: 'Not approved',
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
})
|
||||||
|
.expect(409)
|
||||||
|
).body.code,
|
||||||
|
).toBe('B2B_SAMPLE_DISPATCH_STATE');
|
||||||
|
const rejected = await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${url}/${id}/decision`)
|
||||||
|
.auth(reviewer.token, auth)
|
||||||
|
.send(decision('REJECTED'))
|
||||||
|
.expect(201);
|
||||||
|
expect(rejected.body).toMatchObject({
|
||||||
|
status: 'REJECTED',
|
||||||
|
events: [{ kind: 'REJECTED' }],
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`${url}/${id}/decision`)
|
||||||
|
.auth(reviewer.token, auth)
|
||||||
|
.send(decision('APPROVED'))
|
||||||
|
.expect(409)
|
||||||
|
).body.code,
|
||||||
|
).toBe('B2B_SAMPLE_REVIEW_STATE');
|
||||||
|
const outsider = await secondActor(ctx, false, ['b2b.sample.read']);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.get(`${url}/${id}`)
|
||||||
|
.auth(outsider.token, auth)
|
||||||
|
.expect(404)
|
||||||
|
).body.code,
|
||||||
|
).toBe('B2B_SAMPLE_NOT_FOUND');
|
||||||
|
const noPermission = await secondActor(ctx);
|
||||||
|
await ctx.api().get(url).auth(noPermission.token, auth).expect(403);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(url)
|
||||||
|
.auth(noPermission.token, auth)
|
||||||
|
.send(input(accountId, variant.id))
|
||||||
|
.expect(403);
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue