feat/b2b-artwork-approvals #31
|
|
@ -37,4 +37,4 @@ steps:
|
|||
branch:
|
||||
- main
|
||||
event:
|
||||
- push
|
||||
- push
|
||||
|
|
|
|||
|
|
@ -61,3 +61,4 @@ Partner price lists and minimum quantities: see [Phase 3B API guide](docs/b2b-pr
|
|||
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 sample requests, review, and dispatch records: see [Phase 3E API guide](docs/b2b-samples-api.md).
|
||||
B2B branding and artwork approvals: see [Phase 3F API guide](docs/b2b-artwork-api.md).
|
||||
|
|
|
|||
|
|
@ -0,0 +1,19 @@
|
|||
# B2B branding and artwork approvals (Phase 3F)
|
||||
|
||||
Staff can create an artwork project for a verified business account, upload private versions, and review the latest version independently. All endpoints use a bearer session under `/api/v1/b2b`. Records and decisions are organization-scoped and immutable.
|
||||
|
||||
| Method | Path | Permission | Purpose |
|
||||
| ------ | -------------------------------- | -------------------- | ------------------------------------------------------ |
|
||||
| GET | `/artworks` | `b2b.artwork.read` | List projects; optional `accountId`, `limit`, `offset` |
|
||||
| POST | `/artworks` | `b2b.artwork.manage` | Create a project |
|
||||
| GET | `/artworks/:id` | `b2b.artwork.read` | Read project and version metadata |
|
||||
| POST | `/artworks/:id/versions` | `b2b.artwork.manage` | Upload the next private version |
|
||||
| GET | `/artwork-versions/:id` | `b2b.artwork.read` | Read version metadata and decision |
|
||||
| GET | `/artwork-versions/:id/download` | `b2b.artwork.read` | Download allowed version |
|
||||
| POST | `/artwork-versions/:id/decision` | `b2b.artwork.review` | Approve or reject latest version |
|
||||
|
||||
Create a project with `{ "accountId": "<uuid>", "name": "Seasonal gift branding", "placement": "PACKAGING", "brief": "Use the supplied mark on a matte kraft box" }`. Placement is `LABEL`, `PACKAGING`, `CANDLE`, or `OTHER`. Upload a file in multipart field `file`. Supported attachments are PDF, PNG, and JPEG, up to 2 MiB, with a safe filename and content signature matching the declared media type. File bytes live in PostgreSQL; metadata responses never include them. Downloads are attachments with `nosniff`, sandbox CSP, and `no-store` headers.
|
||||
|
||||
Review with `{ "outcome": "APPROVED", "note": "Brand mark is legible" }` or `REJECTED` and a concrete note. The uploader cannot review their own version. Approval rechecks business verification. Only the newest version may be reviewed, and a new version can be uploaded only after the previous one receives a decision. The version limit is 20 per project; each account may have up to 100 projects. A reader can download an approved version. A reviewer or the uploader can download pending or rejected versions for work and review. A later approved version does not mutate earlier approvals; downstream production must reference a specific approved version ID.
|
||||
|
||||
This approval covers the submitted file only. It does not establish trademark rights, clear third-party content, run malware scanning, reserve inventory, or authorize production. Production integration must verify the selected version has an `APPROVED` decision and must pin its immutable version ID and digest. Set a retention and malware-scanning policy before accepting untrusted artwork in production.
|
||||
|
|
@ -43,6 +43,7 @@ Business verification, price lists, MOQ, quotations, credit policies, samples, b
|
|||
- 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.
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
## Phase 4: Growth channels
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,65 @@
|
|||
enum B2bArtworkPlacement {
|
||||
LABEL
|
||||
PACKAGING
|
||||
CANDLE
|
||||
OTHER
|
||||
}
|
||||
|
||||
enum B2bArtworkOutcome {
|
||||
APPROVED
|
||||
REJECTED
|
||||
}
|
||||
|
||||
model B2bArtwork {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
accountId String @map("account_id") @db.Uuid
|
||||
createdById String @map("created_by_id") @db.Uuid
|
||||
name String @db.VarChar(160)
|
||||
placement B2bArtworkPlacement
|
||||
brief String @db.VarChar(1000)
|
||||
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)
|
||||
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
versions B2bArtworkVersion[]
|
||||
@@unique([id, organizationId])
|
||||
@@index([organizationId, accountId, createdAt, id])
|
||||
@@map("b2b_artworks")
|
||||
}
|
||||
|
||||
model B2bArtworkVersion {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
artworkId String @map("artwork_id") @db.Uuid
|
||||
uploadedById String @map("uploaded_by_id") @db.Uuid
|
||||
version Int
|
||||
filename String @db.VarChar(120)
|
||||
mimeType String @map("mime_type") @db.VarChar(32)
|
||||
sha256 String @db.Char(64)
|
||||
size Int
|
||||
content Bytes @db.ByteA
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
|
||||
artwork B2bArtwork @relation(fields: [artworkId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
uploadedBy User @relation(fields: [uploadedById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
decision B2bArtworkDecision?
|
||||
@@unique([artworkId, version])
|
||||
@@unique([id, organizationId])
|
||||
@@index([organizationId, artworkId, version])
|
||||
@@map("b2b_artwork_versions")
|
||||
}
|
||||
|
||||
model B2bArtworkDecision {
|
||||
versionId String @id @map("version_id") @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
reviewerId String @map("reviewer_id") @db.Uuid
|
||||
outcome B2bArtworkOutcome
|
||||
note String @db.VarChar(500)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
|
||||
version B2bArtworkVersion @relation(fields: [versionId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
reviewer User @relation(fields: [reviewerId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
@@unique([versionId, organizationId])
|
||||
@@map("b2b_artwork_decisions")
|
||||
}
|
||||
|
|
@ -42,6 +42,7 @@ model BusinessAccount {
|
|||
quotes B2bQuote[]
|
||||
creditPolicies B2bCreditPolicy[]
|
||||
sampleRequests B2bSampleRequest[]
|
||||
artworks B2bArtwork[]
|
||||
@@unique([organizationId, code])
|
||||
@@unique([organizationId, countryCode, registrationNumber])
|
||||
@@unique([id, organizationId])
|
||||
|
|
|
|||
|
|
@ -37,5 +37,6 @@
|
|||
"20260930011800_b2b_price_lists": "c2f29a61c6fee93cbffb9d67654c323b2894b3aad7bb296b514f46b623db62d9",
|
||||
"20260930190500_b2b_quotations": "0497ece6cb035687548773ce265842125fa1a655e5951e8d958290d664f5c3f0",
|
||||
"20261001124700_b2b_credit_policies": "a831dc4568c19d8856be27dcb60ae4a7f8155dbeeb797cec2c2dd9f80b392837",
|
||||
"20261001234900_b2b_sample_requests": "f4fb334341d996188dbea3fb85dbe5166bffd35bc8872f2c8404b6458bc7c142"
|
||||
"20261001234900_b2b_sample_requests": "f4fb334341d996188dbea3fb85dbe5166bffd35bc8872f2c8404b6458bc7c142",
|
||||
"20261003000100_b2b_artwork_approvals": "1359390fc3692bdc2dea8a4cc12223d97c7c15b0cdd2181b082b5e5acbe33677"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,98 @@
|
|||
CREATE TYPE "B2bArtworkPlacement" AS ENUM ('LABEL', 'PACKAGING', 'CANDLE', 'OTHER');
|
||||
CREATE TYPE "B2bArtworkOutcome" AS ENUM ('APPROVED', 'REJECTED');
|
||||
|
||||
CREATE TABLE "b2b_artworks" (
|
||||
"id" UUID NOT NULL PRIMARY KEY,
|
||||
"organization_id" UUID NOT NULL,
|
||||
"account_id" UUID NOT NULL,
|
||||
"created_by_id" UUID NOT NULL,
|
||||
"name" VARCHAR(160) NOT NULL,
|
||||
"placement" "B2bArtworkPlacement" NOT NULL,
|
||||
"brief" VARCHAR(1000) NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "b2b_artworks_text" CHECK (char_length(btrim("name")) BETWEEN 3 AND 160 AND char_length(btrim("brief")) BETWEEN 3 AND 1000)
|
||||
);
|
||||
CREATE UNIQUE INDEX "b2b_artworks_id_organization_id_key" ON "b2b_artworks"("id", "organization_id");
|
||||
CREATE INDEX "b2b_artworks_organization_id_account_id_created_at_id_idx" ON "b2b_artworks"("organization_id", "account_id", "created_at", "id");
|
||||
ALTER TABLE "b2b_artworks" ADD CONSTRAINT "b2b_artworks_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
ALTER TABLE "b2b_artworks" ADD CONSTRAINT "b2b_artworks_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_artworks" ADD CONSTRAINT "b2b_artworks_created_by_id_organization_id_fkey" FOREIGN KEY ("created_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
CREATE TABLE "b2b_artwork_versions" (
|
||||
"id" UUID NOT NULL PRIMARY KEY,
|
||||
"organization_id" UUID NOT NULL,
|
||||
"artwork_id" UUID NOT NULL,
|
||||
"uploaded_by_id" UUID NOT NULL,
|
||||
"version" INTEGER NOT NULL,
|
||||
"filename" VARCHAR(120) NOT NULL,
|
||||
"mime_type" VARCHAR(32) NOT NULL,
|
||||
"sha256" CHAR(64) NOT NULL,
|
||||
"size" INTEGER NOT NULL,
|
||||
"content" BYTEA NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "b2b_artwork_versions_file" CHECK (
|
||||
"version" BETWEEN 1 AND 20 AND "size" BETWEEN 1 AND 2097152
|
||||
AND octet_length("content") = "size" AND "sha256" ~ '^[a-f0-9]{64}$'
|
||||
AND "filename" ~ '^[A-Za-z0-9][A-Za-z0-9._-]{0,115}[.](pdf|png|jpg|jpeg)$'
|
||||
AND (("mime_type" = 'application/pdf' AND substring("content" FROM 1 FOR 5) = decode('255044462d','hex'))
|
||||
OR ("mime_type" = 'image/png' AND substring("content" FROM 1 FOR 8) = decode('89504e470d0a1a0a','hex'))
|
||||
OR ("mime_type" = 'image/jpeg' AND substring("content" FROM 1 FOR 3) = decode('ffd8ff','hex')))
|
||||
)
|
||||
);
|
||||
CREATE UNIQUE INDEX "b2b_artwork_versions_artwork_id_version_key" ON "b2b_artwork_versions"("artwork_id", "version");
|
||||
CREATE UNIQUE INDEX "b2b_artwork_versions_id_organization_id_key" ON "b2b_artwork_versions"("id", "organization_id");
|
||||
CREATE INDEX "b2b_artwork_versions_organization_id_artwork_id_version_idx" ON "b2b_artwork_versions"("organization_id", "artwork_id", "version");
|
||||
ALTER TABLE "b2b_artwork_versions" ADD CONSTRAINT "b2b_artwork_versions_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
ALTER TABLE "b2b_artwork_versions" ADD CONSTRAINT "b2b_artwork_versions_artwork_id_organization_id_fkey" FOREIGN KEY ("artwork_id", "organization_id") REFERENCES "b2b_artworks"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
ALTER TABLE "b2b_artwork_versions" ADD CONSTRAINT "b2b_artwork_versions_uploaded_by_id_organization_id_fkey" FOREIGN KEY ("uploaded_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
CREATE TABLE "b2b_artwork_decisions" (
|
||||
"version_id" UUID NOT NULL PRIMARY KEY,
|
||||
"organization_id" UUID NOT NULL,
|
||||
"reviewer_id" UUID NOT NULL,
|
||||
"outcome" "B2bArtworkOutcome" NOT NULL,
|
||||
"note" VARCHAR(500) NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "b2b_artwork_decisions_note" CHECK (char_length(btrim("note")) BETWEEN 3 AND 500)
|
||||
);
|
||||
CREATE UNIQUE INDEX "b2b_artwork_decisions_version_id_organization_id_key" ON "b2b_artwork_decisions"("version_id", "organization_id");
|
||||
ALTER TABLE "b2b_artwork_decisions" ADD CONSTRAINT "b2b_artwork_decisions_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
ALTER TABLE "b2b_artwork_decisions" ADD CONSTRAINT "b2b_artwork_decisions_version_id_organization_id_fkey" FOREIGN KEY ("version_id", "organization_id") REFERENCES "b2b_artwork_versions"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
ALTER TABLE "b2b_artwork_decisions" ADD CONSTRAINT "b2b_artwork_decisions_reviewer_id_organization_id_fkey" FOREIGN KEY ("reviewer_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
CREATE FUNCTION guard_b2b_artwork_version() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE previous_version INTEGER; previous_decided BOOLEAN;
|
||||
BEGIN
|
||||
PERFORM id FROM b2b_artworks WHERE id = NEW.artwork_id FOR UPDATE;
|
||||
SELECT COALESCE(MAX(version), 0) INTO previous_version FROM b2b_artwork_versions WHERE artwork_id = NEW.artwork_id;
|
||||
IF NEW.version <> previous_version + 1 THEN RAISE EXCEPTION 'Artwork version must be sequential'; END IF;
|
||||
IF previous_version > 0 THEN
|
||||
SELECT EXISTS(SELECT 1 FROM b2b_artwork_decisions d JOIN b2b_artwork_versions v ON v.id = d.version_id WHERE v.artwork_id = NEW.artwork_id AND v.version = previous_version) INTO previous_decided;
|
||||
IF NOT previous_decided THEN RAISE EXCEPTION 'Previous artwork version requires a decision'; END IF;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER b2b_artwork_version_sequence BEFORE INSERT ON b2b_artwork_versions FOR EACH ROW EXECUTE FUNCTION guard_b2b_artwork_version();
|
||||
|
||||
CREATE FUNCTION guard_b2b_artwork_decision() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE version_row b2b_artwork_versions%ROWTYPE; latest_version INTEGER;
|
||||
BEGIN
|
||||
SELECT * INTO version_row FROM b2b_artwork_versions WHERE id = NEW.version_id AND organization_id = NEW.organization_id;
|
||||
SELECT MAX(version) INTO latest_version FROM b2b_artwork_versions WHERE artwork_id = version_row.artwork_id;
|
||||
IF NEW.reviewer_id = version_row.uploaded_by_id OR version_row.version <> latest_version
|
||||
THEN RAISE EXCEPTION 'Artwork review requires an independent reviewer and latest version'; END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER b2b_artwork_decision_guard BEFORE INSERT ON b2b_artwork_decisions FOR EACH ROW EXECUTE FUNCTION guard_b2b_artwork_decision();
|
||||
|
||||
CREATE FUNCTION reject_b2b_artwork_mutation() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN RAISE EXCEPTION 'Artwork records are immutable'; END;
|
||||
$$;
|
||||
CREATE TRIGGER b2b_artworks_immutable BEFORE UPDATE OR DELETE ON b2b_artworks FOR EACH ROW EXECUTE FUNCTION reject_b2b_artwork_mutation();
|
||||
CREATE TRIGGER b2b_artwork_versions_immutable BEFORE UPDATE OR DELETE ON b2b_artwork_versions FOR EACH ROW EXECUTE FUNCTION reject_b2b_artwork_mutation();
|
||||
CREATE TRIGGER b2b_artwork_decisions_immutable BEFORE UPDATE OR DELETE ON b2b_artwork_decisions FOR EACH ROW EXECUTE FUNCTION reject_b2b_artwork_mutation();
|
||||
|
||||
UPDATE "roles" SET "permissions" = ARRAY(SELECT DISTINCT unnest("permissions" || ARRAY['b2b.artwork.read', 'b2b.artwork.manage', 'b2b.artwork.review']))
|
||||
WHERE "is_system" = true AND "name" = 'Owner';
|
||||
|
|
@ -62,6 +62,9 @@ model Organization {
|
|||
b2bCreditEvents B2bCreditEvent[]
|
||||
b2bSampleRequests B2bSampleRequest[]
|
||||
b2bSampleEvents B2bSampleEvent[]
|
||||
b2bArtworks B2bArtwork[]
|
||||
b2bArtworkVersions B2bArtworkVersion[]
|
||||
b2bArtworkDecisions B2bArtworkDecision[]
|
||||
@@map("organizations")
|
||||
}
|
||||
model User {
|
||||
|
|
@ -112,6 +115,9 @@ model User {
|
|||
b2bCreditEvents B2bCreditEvent[]
|
||||
b2bSampleRequests B2bSampleRequest[]
|
||||
b2bSampleEvents B2bSampleEvent[]
|
||||
b2bArtworks B2bArtwork[]
|
||||
b2bArtworkVersions B2bArtworkVersion[]
|
||||
b2bArtworkDecisions B2bArtworkDecision[]
|
||||
stockEntries StockLedger[]
|
||||
stockReservations StockReservation[]
|
||||
carts Cart[]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,52 @@
|
|||
import { AppError } from '../common/errors/app-error';
|
||||
import { fileDigest } from '../common/file-digest';
|
||||
import type { UploadedDocument } from '../procurement/supplier-document-file';
|
||||
|
||||
export const MAX_ARTWORK_BYTES = 2 * 1024 * 1024;
|
||||
const TYPES = {
|
||||
pdf: 'application/pdf',
|
||||
png: 'image/png',
|
||||
jpg: 'image/jpeg',
|
||||
jpeg: 'image/jpeg',
|
||||
} as const;
|
||||
|
||||
export function inspectArtwork(file?: UploadedDocument) {
|
||||
if (!file) throw new AppError('B2B_ARTWORK_FILE_REQUIRED');
|
||||
if (file.buffer.length > MAX_ARTWORK_BYTES)
|
||||
throw new AppError('B2B_ARTWORK_FILE_TOO_LARGE');
|
||||
const name = file.originalname;
|
||||
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,115}\.(pdf|png|jpg|jpeg)$/.test(name))
|
||||
throw new AppError('B2B_ARTWORK_FILENAME_INVALID');
|
||||
const extension = name.split('.').at(-1) as keyof typeof TYPES;
|
||||
const bytes = file.buffer;
|
||||
const valid =
|
||||
extension === 'pdf'
|
||||
? bytes.subarray(0, 5).equals(Buffer.from('%PDF-')) &&
|
||||
bytes.subarray(-1024).includes(Buffer.from('%%EOF'))
|
||||
: extension === 'png'
|
||||
? bytes.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex')) &&
|
||||
bytes.subarray(-8, -4).equals(Buffer.from('IEND'))
|
||||
: bytes.subarray(0, 3).equals(Buffer.from('ffd8ff', 'hex')) &&
|
||||
bytes.subarray(-2).equals(Buffer.from('ffd9', 'hex'));
|
||||
if (
|
||||
file.size !== bytes.length ||
|
||||
!bytes.length ||
|
||||
file.mimetype !== TYPES[extension] ||
|
||||
!valid
|
||||
)
|
||||
throw new AppError('B2B_ARTWORK_FILE_INVALID');
|
||||
return {
|
||||
filename: name,
|
||||
mimeType: TYPES[extension],
|
||||
sha256: fileDigest(bytes),
|
||||
size: bytes.length,
|
||||
content: Uint8Array.from(bytes),
|
||||
};
|
||||
}
|
||||
|
||||
export function verifiedArtwork(content: Uint8Array, expectedHash: string) {
|
||||
const bytes = Buffer.from(content);
|
||||
if (fileDigest(bytes) !== expectedHash)
|
||||
throw new AppError('B2B_ARTWORK_INTEGRITY_FAILURE');
|
||||
return bytes;
|
||||
}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
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 artworkVersionSelect = {
|
||||
id: true,
|
||||
organizationId: true,
|
||||
artworkId: true,
|
||||
uploadedById: true,
|
||||
version: true,
|
||||
filename: true,
|
||||
mimeType: true,
|
||||
sha256: true,
|
||||
size: true,
|
||||
createdAt: true,
|
||||
decision: true,
|
||||
} as const;
|
||||
export const artworkInclude = {
|
||||
versions: {
|
||||
select: artworkVersionSelect,
|
||||
orderBy: { version: 'desc' as const },
|
||||
},
|
||||
};
|
||||
|
||||
export async function requireArtwork(
|
||||
db: Db,
|
||||
organizationId: string,
|
||||
id: string,
|
||||
) {
|
||||
const artwork = await db.b2bArtwork.findFirst({
|
||||
where: { id, organizationId },
|
||||
include: artworkInclude,
|
||||
});
|
||||
if (!artwork) throw new AppError('B2B_ARTWORK_NOT_FOUND');
|
||||
return artwork;
|
||||
}
|
||||
|
||||
export async function requireArtworkVersion(
|
||||
db: Db,
|
||||
organizationId: string,
|
||||
id: string,
|
||||
) {
|
||||
const version = await db.b2bArtworkVersion.findFirst({
|
||||
where: { id, organizationId },
|
||||
select: artworkVersionSelect,
|
||||
});
|
||||
if (!version) throw new AppError('B2B_ARTWORK_VERSION_NOT_FOUND');
|
||||
return version;
|
||||
}
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import { AccessStore } from '../identity/access.store';
|
||||
import { recordAudit } from '../identity/audit';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import { isVerifiedBusinessAccount } from './business-verification';
|
||||
import {
|
||||
artworkVersionSelect,
|
||||
requireArtwork,
|
||||
requireArtworkVersion,
|
||||
} from './artwork-lookup';
|
||||
import type { ArtworkDecisionInput } from './artwork.schemas';
|
||||
|
||||
@Injectable()
|
||||
export class ArtworkReviewStore {
|
||||
constructor(private readonly access: AccessStore) {}
|
||||
|
||||
decide(actor: Principal, versionId: string, input: ArtworkDecisionInput) {
|
||||
return this.access.mutate(actor, 'b2b.artwork.review', async (tx) => {
|
||||
const version = await requireArtworkVersion(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
versionId,
|
||||
);
|
||||
if (version.decision) throw new AppError('B2B_ARTWORK_DECISION_EXISTS');
|
||||
if (version.uploadedById === actor.userId)
|
||||
throw new AppError('B2B_ARTWORK_SELF_REVIEW');
|
||||
const artwork = await requireArtwork(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
version.artworkId,
|
||||
);
|
||||
if (artwork.versions[0]?.id !== versionId)
|
||||
throw new AppError('B2B_ARTWORK_OLD_VERSION');
|
||||
if (
|
||||
input.outcome === 'APPROVED' &&
|
||||
!(await isVerifiedBusinessAccount(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
artwork.accountId,
|
||||
))
|
||||
)
|
||||
throw new AppError('B2B_ARTWORK_ACCOUNT_UNVERIFIED');
|
||||
await tx.b2bArtworkDecision.create({
|
||||
data: {
|
||||
versionId,
|
||||
organizationId: actor.organizationId,
|
||||
reviewerId: actor.userId,
|
||||
outcome: input.outcome,
|
||||
note: input.note,
|
||||
},
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
`b2b_artwork.${input.outcome.toLowerCase()}`,
|
||||
versionId,
|
||||
);
|
||||
return tx.b2bArtworkVersion.findUniqueOrThrow({
|
||||
where: { id: versionId },
|
||||
select: artworkVersionSelect,
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
import { z } from 'zod';
|
||||
import { text } from '../common/input';
|
||||
import { pageSchema } from '../identity/identity.schemas';
|
||||
|
||||
export const createArtworkSchema = z
|
||||
.object({
|
||||
accountId: z.uuid(),
|
||||
name: text(160, 3),
|
||||
placement: z.enum(['LABEL', 'PACKAGING', 'CANDLE', 'OTHER']),
|
||||
brief: text(1000, 3),
|
||||
})
|
||||
.strict();
|
||||
export const artworkDecisionSchema = z
|
||||
.object({
|
||||
outcome: z.enum(['APPROVED', 'REJECTED']),
|
||||
note: text(500, 3),
|
||||
})
|
||||
.strict();
|
||||
export const artworkQuerySchema = pageSchema
|
||||
.extend({ accountId: z.uuid().optional() })
|
||||
.strict();
|
||||
export type CreateArtworkInput = z.infer<typeof createArtworkSchema>;
|
||||
export type ArtworkDecisionInput = z.infer<typeof artworkDecisionSchema>;
|
||||
export type ArtworkQuery = z.infer<typeof artworkQuerySchema>;
|
||||
|
|
@ -0,0 +1,141 @@
|
|||
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 { isVerifiedBusinessAccount } from './business-verification';
|
||||
import { requireBusinessAccount } from './price-list.helpers';
|
||||
import {
|
||||
artworkVersionSelect,
|
||||
requireArtwork,
|
||||
requireArtworkVersion,
|
||||
} from './artwork-lookup';
|
||||
import { inspectArtwork, verifiedArtwork } from './artwork-file';
|
||||
import type { ArtworkQuery, CreateArtworkInput } from './artwork.schemas';
|
||||
import type { UploadedDocument } from '../procurement/supplier-document-file';
|
||||
|
||||
@Injectable()
|
||||
export class ArtworkStore {
|
||||
constructor(
|
||||
private readonly db: DatabaseService,
|
||||
private readonly access: AccessStore,
|
||||
) {}
|
||||
|
||||
list(actor: Principal, query: ArtworkQuery) {
|
||||
return this.db.b2bArtwork.findMany({
|
||||
where: {
|
||||
organizationId: actor.organizationId,
|
||||
...(query.accountId ? { accountId: query.accountId } : {}),
|
||||
},
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
take: query.limit,
|
||||
skip: query.offset,
|
||||
});
|
||||
}
|
||||
|
||||
get(actor: Principal, id: string) {
|
||||
return requireArtwork(this.db, actor.organizationId, id);
|
||||
}
|
||||
|
||||
getVersion(actor: Principal, id: string) {
|
||||
return requireArtworkVersion(this.db, actor.organizationId, id);
|
||||
}
|
||||
|
||||
create(actor: Principal, input: CreateArtworkInput) {
|
||||
return this.access.mutate(actor, 'b2b.artwork.manage', async (tx) => {
|
||||
await requireBusinessAccount(tx, actor.organizationId, input.accountId);
|
||||
if (
|
||||
!(await isVerifiedBusinessAccount(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
input.accountId,
|
||||
))
|
||||
)
|
||||
throw new AppError('B2B_ARTWORK_ACCOUNT_UNVERIFIED');
|
||||
if (
|
||||
(await tx.b2bArtwork.count({
|
||||
where: {
|
||||
organizationId: actor.organizationId,
|
||||
accountId: input.accountId,
|
||||
},
|
||||
})) >= 100
|
||||
)
|
||||
throw new AppError('B2B_ARTWORK_PROJECT_LIMIT');
|
||||
const artwork = await tx.b2bArtwork.create({
|
||||
data: {
|
||||
...input,
|
||||
organizationId: actor.organizationId,
|
||||
createdById: actor.userId,
|
||||
},
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
'b2b_artwork.created',
|
||||
artwork.id,
|
||||
);
|
||||
return artwork;
|
||||
});
|
||||
}
|
||||
|
||||
addVersion(actor: Principal, artworkId: string, file?: UploadedDocument) {
|
||||
const inspected = inspectArtwork(file);
|
||||
return this.access.mutate(actor, 'b2b.artwork.manage', async (tx) => {
|
||||
const artwork = await requireArtwork(tx, actor.organizationId, artworkId);
|
||||
if (
|
||||
!(await isVerifiedBusinessAccount(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
artwork.accountId,
|
||||
))
|
||||
)
|
||||
throw new AppError('B2B_ARTWORK_ACCOUNT_UNVERIFIED');
|
||||
const latest = artwork.versions[0];
|
||||
if (latest && !latest.decision)
|
||||
throw new AppError('B2B_ARTWORK_VERSION_PENDING');
|
||||
if ((latest?.version ?? 0) >= 20)
|
||||
throw new AppError('B2B_ARTWORK_VERSION_LIMIT');
|
||||
const version = await tx.b2bArtworkVersion.create({
|
||||
data: {
|
||||
...inspected,
|
||||
organizationId: actor.organizationId,
|
||||
artworkId,
|
||||
uploadedById: actor.userId,
|
||||
version: (latest?.version ?? 0) + 1,
|
||||
},
|
||||
select: artworkVersionSelect,
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
'b2b_artwork.version_uploaded',
|
||||
version.id,
|
||||
);
|
||||
return version;
|
||||
});
|
||||
}
|
||||
|
||||
async download(actor: Principal, id: string) {
|
||||
const version = await this.db.b2bArtworkVersion.findFirst({
|
||||
where: { id, organizationId: actor.organizationId },
|
||||
include: { decision: true },
|
||||
});
|
||||
if (!version) throw new AppError('B2B_ARTWORK_VERSION_NOT_FOUND');
|
||||
if (
|
||||
!actor.permissions.includes('b2b.artwork.review') &&
|
||||
version.uploadedById !== actor.userId
|
||||
) {
|
||||
if (!version.decision) throw new AppError('B2B_ARTWORK_DOWNLOAD_PENDING');
|
||||
if (version.decision.outcome === 'REJECTED')
|
||||
throw new AppError('B2B_ARTWORK_DOWNLOAD_REJECTED');
|
||||
}
|
||||
return {
|
||||
filename: version.filename,
|
||||
mimeType: version.mimeType,
|
||||
content: verifiedArtwork(version.content, version.sha256),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,139 @@
|
|||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Post,
|
||||
Query,
|
||||
Res,
|
||||
UploadedFile,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { ApiBody, ApiConsumes, ApiProduces } from '@nestjs/swagger';
|
||||
import type { Response } from 'express';
|
||||
import { SchemaPipe } from '../common/validation.pipe';
|
||||
import {
|
||||
CurrentPrincipal,
|
||||
RequirePermission,
|
||||
} from '../identity/access.decorator';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import type { UploadedDocument } from '../procurement/supplier-document-file';
|
||||
import { MAX_ARTWORK_BYTES } from './artwork-file';
|
||||
import { ArtworkReviewStore } from './artwork-review.store';
|
||||
import { ArtworkStore } from './artwork.store';
|
||||
import {
|
||||
artworkDecisionSchema,
|
||||
artworkQuerySchema,
|
||||
createArtworkSchema,
|
||||
type ArtworkDecisionInput,
|
||||
type ArtworkQuery,
|
||||
type CreateArtworkInput,
|
||||
} from './artwork.schemas';
|
||||
|
||||
@Controller('b2b/artworks')
|
||||
export class ArtworksController {
|
||||
constructor(private readonly artworks: ArtworkStore) {}
|
||||
|
||||
@Get()
|
||||
@RequirePermission('b2b.artwork.read')
|
||||
list(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Query(new SchemaPipe(artworkQuerySchema)) query: ArtworkQuery,
|
||||
) {
|
||||
return this.artworks.list(actor, query);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@RequirePermission('b2b.artwork.manage')
|
||||
create(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Body(new SchemaPipe(createArtworkSchema)) input: CreateArtworkInput,
|
||||
) {
|
||||
return this.artworks.create(actor, input);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@RequirePermission('b2b.artwork.read')
|
||||
get(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
) {
|
||||
return this.artworks.get(actor, id);
|
||||
}
|
||||
|
||||
@Post(':id/versions')
|
||||
@RequirePermission('b2b.artwork.manage')
|
||||
@ApiConsumes('multipart/form-data')
|
||||
@ApiBody({
|
||||
schema: {
|
||||
type: 'object',
|
||||
required: ['file'],
|
||||
properties: { file: { type: 'string', format: 'binary' } },
|
||||
},
|
||||
})
|
||||
@UseInterceptors(
|
||||
FileInterceptor('file', {
|
||||
limits: {
|
||||
fileSize: MAX_ARTWORK_BYTES + 1,
|
||||
files: 1,
|
||||
fields: 0,
|
||||
},
|
||||
}),
|
||||
)
|
||||
upload(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@UploadedFile() file?: UploadedDocument,
|
||||
) {
|
||||
return this.artworks.addVersion(actor, id, file);
|
||||
}
|
||||
}
|
||||
|
||||
@Controller('b2b/artwork-versions')
|
||||
export class ArtworkVersionsController {
|
||||
constructor(
|
||||
private readonly artworks: ArtworkStore,
|
||||
private readonly reviews: ArtworkReviewStore,
|
||||
) {}
|
||||
|
||||
@Get(':id')
|
||||
@RequirePermission('b2b.artwork.read')
|
||||
get(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
) {
|
||||
return this.artworks.getVersion(actor, id);
|
||||
}
|
||||
|
||||
@Get(':id/download')
|
||||
@RequirePermission('b2b.artwork.read')
|
||||
@ApiProduces('application/pdf', 'image/png', 'image/jpeg')
|
||||
async download(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Res() response: Response,
|
||||
) {
|
||||
const file = await this.artworks.download(actor, id);
|
||||
response.setHeader('Content-Type', file.mimeType);
|
||||
response.setHeader(
|
||||
'Content-Disposition',
|
||||
`attachment; filename="${file.filename}"`,
|
||||
);
|
||||
response.setHeader('Content-Security-Policy', 'sandbox');
|
||||
response.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
response.setHeader('Cache-Control', 'no-store');
|
||||
response.send(file.content);
|
||||
}
|
||||
|
||||
@Post(':id/decision')
|
||||
@RequirePermission('b2b.artwork.review')
|
||||
decide(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body(new SchemaPipe(artworkDecisionSchema)) input: ArtworkDecisionInput,
|
||||
) {
|
||||
return this.reviews.decide(actor, id, input);
|
||||
}
|
||||
}
|
||||
|
|
@ -17,6 +17,12 @@ import { CreditReviewStore } from './credit-review.store';
|
|||
import { SamplesController } from './samples.controller';
|
||||
import { SampleStore } from './sample.store';
|
||||
import { SampleActionStore } from './sample-action.store';
|
||||
import {
|
||||
ArtworksController,
|
||||
ArtworkVersionsController,
|
||||
} from './artworks.controller';
|
||||
import { ArtworkStore } from './artwork.store';
|
||||
import { ArtworkReviewStore } from './artwork-review.store';
|
||||
|
||||
@Module({
|
||||
imports: [DatabaseModule, IdentityModule],
|
||||
|
|
@ -27,6 +33,8 @@ import { SampleActionStore } from './sample-action.store';
|
|||
QuotesController,
|
||||
CreditPoliciesController,
|
||||
SamplesController,
|
||||
ArtworksController,
|
||||
ArtworkVersionsController,
|
||||
],
|
||||
providers: [
|
||||
BusinessStore,
|
||||
|
|
@ -39,6 +47,8 @@ import { SampleActionStore } from './sample-action.store';
|
|||
CreditReviewStore,
|
||||
SampleStore,
|
||||
SampleActionStore,
|
||||
ArtworkStore,
|
||||
ArtworkReviewStore,
|
||||
],
|
||||
})
|
||||
export class B2bModule {}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,82 @@
|
|||
export const B2B_ARTWORK_ERRORS = {
|
||||
B2B_ARTWORK_NOT_FOUND: [
|
||||
404,
|
||||
'Artwork project not found',
|
||||
'Scoped B2B artwork project lookup failed',
|
||||
],
|
||||
B2B_ARTWORK_VERSION_NOT_FOUND: [
|
||||
404,
|
||||
'Artwork version not found',
|
||||
'Scoped B2B artwork version lookup failed',
|
||||
],
|
||||
B2B_ARTWORK_ACCOUNT_UNVERIFIED: [
|
||||
409,
|
||||
'Business account must be verified for artwork',
|
||||
'B2B artwork verification gate failed',
|
||||
],
|
||||
B2B_ARTWORK_VERSION_PENDING: [
|
||||
409,
|
||||
'Current artwork version awaits a decision',
|
||||
'B2B artwork pending version blocks upload',
|
||||
],
|
||||
B2B_ARTWORK_VERSION_LIMIT: [
|
||||
409,
|
||||
'Artwork project reached its version limit',
|
||||
'B2B artwork version limit reached',
|
||||
],
|
||||
B2B_ARTWORK_PROJECT_LIMIT: [
|
||||
409,
|
||||
'Business account reached its artwork project limit',
|
||||
'B2B artwork project limit reached',
|
||||
],
|
||||
B2B_ARTWORK_DECISION_EXISTS: [
|
||||
409,
|
||||
'Artwork version already has a decision',
|
||||
'B2B artwork duplicate decision',
|
||||
],
|
||||
B2B_ARTWORK_OLD_VERSION: [
|
||||
409,
|
||||
'Only the latest artwork version can be reviewed',
|
||||
'B2B artwork stale version review',
|
||||
],
|
||||
B2B_ARTWORK_SELF_REVIEW: [
|
||||
403,
|
||||
'A different staff member must review this artwork',
|
||||
'B2B artwork self-review rejected',
|
||||
],
|
||||
B2B_ARTWORK_DOWNLOAD_PENDING: [
|
||||
403,
|
||||
'Artwork is awaiting approval',
|
||||
'B2B artwork pending download denied',
|
||||
],
|
||||
B2B_ARTWORK_DOWNLOAD_REJECTED: [
|
||||
403,
|
||||
'Rejected artwork cannot be downloaded with read access',
|
||||
'B2B artwork rejected download denied',
|
||||
],
|
||||
B2B_ARTWORK_FILE_REQUIRED: [
|
||||
400,
|
||||
'Artwork file is required',
|
||||
'B2B artwork upload missing',
|
||||
],
|
||||
B2B_ARTWORK_FILE_TOO_LARGE: [
|
||||
400,
|
||||
'Artwork file exceeds the size limit',
|
||||
'B2B artwork upload over size',
|
||||
],
|
||||
B2B_ARTWORK_FILENAME_INVALID: [
|
||||
400,
|
||||
'Artwork filename is invalid',
|
||||
'B2B artwork upload filename rejected',
|
||||
],
|
||||
B2B_ARTWORK_FILE_INVALID: [
|
||||
400,
|
||||
'Artwork file content or type is invalid',
|
||||
'B2B artwork upload bytes or type rejected',
|
||||
],
|
||||
B2B_ARTWORK_INTEGRITY_FAILURE: [
|
||||
500,
|
||||
'Artwork file integrity check failed',
|
||||
'B2B artwork stored digest mismatch',
|
||||
],
|
||||
} as const;
|
||||
|
|
@ -7,6 +7,7 @@ import { B2B_PRICE_ERRORS } from './b2b-price-errors';
|
|||
import { B2B_QUOTE_ERRORS } from './b2b-quote-errors';
|
||||
import { B2B_CREDIT_ERRORS } from './b2b-credit-errors';
|
||||
import { B2B_SAMPLE_ERRORS } from './b2b-sample-errors';
|
||||
import { B2B_ARTWORK_ERRORS } from './b2b-artwork-errors';
|
||||
export const ERRORS = {
|
||||
...PLATFORM_ERRORS,
|
||||
...COMMERCE_ERRORS,
|
||||
|
|
@ -17,5 +18,6 @@ export const ERRORS = {
|
|||
...B2B_QUOTE_ERRORS,
|
||||
...B2B_CREDIT_ERRORS,
|
||||
...B2B_SAMPLE_ERRORS,
|
||||
...B2B_ARTWORK_ERRORS,
|
||||
} as const;
|
||||
export type ErrorCode = keyof typeof ERRORS;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,5 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
|
||||
export function fileDigest(content: Uint8Array): string {
|
||||
return createHash('sha256').update(content).digest('hex');
|
||||
}
|
||||
|
|
@ -50,5 +50,8 @@ export const PERMISSIONS = [
|
|||
'b2b.sample.request',
|
||||
'b2b.sample.review',
|
||||
'b2b.sample.dispatch',
|
||||
'b2b.artwork.read',
|
||||
'b2b.artwork.manage',
|
||||
'b2b.artwork.review',
|
||||
] as const;
|
||||
export type Permission = (typeof PERMISSIONS)[number];
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import { fileDigest } from '../common/file-digest';
|
||||
|
||||
export const MAX_DOCUMENT_BYTES = 2 * 1024 * 1024;
|
||||
export type UploadedDocument = {
|
||||
|
|
@ -26,7 +26,7 @@ export function inspectPdf(file?: UploadedDocument) {
|
|||
filename: file.originalname,
|
||||
mimeType: 'application/pdf',
|
||||
size: file.buffer.length,
|
||||
sha256: createHash('sha256').update(file.buffer).digest('hex'),
|
||||
sha256: fileDigest(file.buffer),
|
||||
content: Uint8Array.from(file.buffer),
|
||||
};
|
||||
}
|
||||
|
|
@ -35,7 +35,7 @@ export function verifiedContent(
|
|||
expectedHash: string,
|
||||
): Buffer {
|
||||
const bytes = Buffer.from(content);
|
||||
if (createHash('sha256').update(bytes).digest('hex') !== expectedHash)
|
||||
if (fileDigest(bytes) !== expectedHash)
|
||||
throw new AppError('DOCUMENT_INTEGRITY_FAILURE');
|
||||
return bytes;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,52 @@
|
|||
import {
|
||||
inspectArtwork,
|
||||
MAX_ARTWORK_BYTES,
|
||||
verifiedArtwork,
|
||||
} from '../src/b2b/artwork-file';
|
||||
|
||||
const pdf = Buffer.from('%PDF-1.4\n1 0 obj\n<<>>\nendobj\n%%EOF');
|
||||
const png = Buffer.from('89504e470d0a1a0a0000000049454e4400000000', 'hex');
|
||||
const jpeg = Buffer.from('ffd8ffe00000ffd9', 'hex');
|
||||
const file = (buffer: Buffer, originalname: string, mimetype: string) => ({
|
||||
buffer,
|
||||
size: buffer.length,
|
||||
originalname,
|
||||
mimetype,
|
||||
});
|
||||
|
||||
describe('B2B artwork file policy', () => {
|
||||
it.each([
|
||||
['brand.pdf', 'application/pdf', pdf],
|
||||
['brand.png', 'image/png', png],
|
||||
['brand.jpg', 'image/jpeg', jpeg],
|
||||
])('accepts and hashes %s', (name, type, bytes) => {
|
||||
const inspected = inspectArtwork(file(bytes, name, type));
|
||||
expect(inspected.size).toBe(bytes.length);
|
||||
expect(verifiedArtwork(inspected.content, inspected.sha256)).toEqual(bytes);
|
||||
});
|
||||
|
||||
it('rejects missing, oversized, misleading, and malformed files', () => {
|
||||
expect(() => inspectArtwork()).toThrow(
|
||||
expect.objectContaining({ code: 'B2B_ARTWORK_FILE_REQUIRED' }),
|
||||
);
|
||||
expect(() =>
|
||||
inspectArtwork(
|
||||
file(Buffer.alloc(MAX_ARTWORK_BYTES + 1), 'large.png', 'image/png'),
|
||||
),
|
||||
).toThrow(expect.objectContaining({ code: 'B2B_ARTWORK_FILE_TOO_LARGE' }));
|
||||
expect(() =>
|
||||
inspectArtwork(file(pdf, '../bad.pdf', 'application/pdf')),
|
||||
).toThrow(
|
||||
expect.objectContaining({ code: 'B2B_ARTWORK_FILENAME_INVALID' }),
|
||||
);
|
||||
expect(() => inspectArtwork(file(pdf, 'brand.png', 'image/png'))).toThrow(
|
||||
expect.objectContaining({ code: 'B2B_ARTWORK_FILE_INVALID' }),
|
||||
);
|
||||
expect(() =>
|
||||
inspectArtwork(file(png, 'brand.png', 'application/pdf')),
|
||||
).toThrow(expect.objectContaining({ code: 'B2B_ARTWORK_FILE_INVALID' }));
|
||||
expect(() => verifiedArtwork(pdf, '0'.repeat(64))).toThrow(
|
||||
expect.objectContaining({ code: 'B2B_ARTWORK_INTEGRITY_FAILURE' }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,250 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
||||
import { secondActor } from './helpers/commerce';
|
||||
|
||||
const pdf = Buffer.from('%PDF-1.4\n1 0 obj\n<<>>\nendobj\n%%EOF');
|
||||
describe('B2B artwork approvals', () => {
|
||||
let ctx: IdentityApp;
|
||||
const auth = { type: 'bearer' as const };
|
||||
const url = '/api/v1/b2b/artworks';
|
||||
|
||||
async function account(verified = true) {
|
||||
const created = await ctx
|
||||
.api()
|
||||
.post('/api/v1/b2b/accounts')
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
code: `AR-${randomUUID().slice(0, 8)}`,
|
||||
legalName: 'Artwork Partner Limited',
|
||||
tradingName: null,
|
||||
registrationNumber: randomUUID(),
|
||||
taxIdentifier: null,
|
||||
countryCode: 'IN',
|
||||
contactEmail: 'artwork@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;
|
||||
}
|
||||
async function artwork() {
|
||||
const accountId = await account();
|
||||
const created = await ctx
|
||||
.api()
|
||||
.post(url)
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
accountId,
|
||||
name: 'Seasonal gift branding',
|
||||
placement: 'PACKAGING',
|
||||
brief: 'Use the supplied mark on a matte kraft box',
|
||||
})
|
||||
.expect(201);
|
||||
return { id: created.body.id as string, accountId };
|
||||
}
|
||||
const upload = (id: string, token: string, bytes = pdf) =>
|
||||
ctx
|
||||
.api()
|
||||
.post(`${url}/${id}/versions`)
|
||||
.auth(token, auth)
|
||||
.attach('file', bytes, {
|
||||
filename: 'brand.pdf',
|
||||
contentType: 'application/pdf',
|
||||
});
|
||||
|
||||
beforeAll(async () => {
|
||||
ctx = await identityApp();
|
||||
}, 60000);
|
||||
afterAll(async () => {
|
||||
await ctx?.close();
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await ctx.clearLimits();
|
||||
});
|
||||
|
||||
it('requires verification and keeps file bytes out of metadata responses', async () => {
|
||||
const unverified = await account(false);
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.post(url)
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
accountId: unverified,
|
||||
name: 'Unapproved brand',
|
||||
placement: 'LABEL',
|
||||
brief: 'Partner label artwork',
|
||||
})
|
||||
.expect(409)
|
||||
).body.code,
|
||||
).toBe('B2B_ARTWORK_ACCOUNT_UNVERIFIED');
|
||||
const project = await artwork();
|
||||
const first = await upload(project.id, ctx.token).expect(201);
|
||||
expect(first.body).toMatchObject({
|
||||
version: 1,
|
||||
filename: 'brand.pdf',
|
||||
size: pdf.length,
|
||||
decision: null,
|
||||
});
|
||||
expect(first.body.content).toBeUndefined();
|
||||
const detail = await ctx
|
||||
.api()
|
||||
.get(`${url}/${project.id}`)
|
||||
.auth(ctx.token, auth)
|
||||
.expect(200);
|
||||
expect(detail.body.versions[0].content).toBeUndefined();
|
||||
expect((await upload(project.id, ctx.token).expect(409)).body.code).toBe(
|
||||
'B2B_ARTWORK_VERSION_PENDING',
|
||||
);
|
||||
const listed = await ctx
|
||||
.api()
|
||||
.get(`${url}?accountId=${project.accountId}`)
|
||||
.auth(ctx.token, auth)
|
||||
.expect(200);
|
||||
expect(listed.body.map((item: { id: string }) => item.id)).toContain(
|
||||
project.id,
|
||||
);
|
||||
});
|
||||
|
||||
it('requires independent review, protects pending/rejected files, and versions revisions', async () => {
|
||||
const project = await artwork();
|
||||
const first = await upload(project.id, ctx.token).expect(201);
|
||||
const versionUrl = `/api/v1/b2b/artwork-versions/${first.body.id}`;
|
||||
const reader = await secondActor(ctx, true, ['b2b.artwork.read']);
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.get(`${versionUrl}/download`)
|
||||
.auth(reader.token, auth)
|
||||
.expect(403)
|
||||
).body.code,
|
||||
).toBe('B2B_ARTWORK_DOWNLOAD_PENDING');
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.post(`${versionUrl}/decision`)
|
||||
.auth(ctx.token, auth)
|
||||
.send({ outcome: 'APPROVED', note: 'Brand mark is legible' })
|
||||
.expect(403)
|
||||
).body.code,
|
||||
).toBe('B2B_ARTWORK_SELF_REVIEW');
|
||||
const reviewer = await secondActor(ctx, true, [
|
||||
'b2b.artwork.read',
|
||||
'b2b.artwork.review',
|
||||
]);
|
||||
const rejected = await ctx
|
||||
.api()
|
||||
.post(`${versionUrl}/decision`)
|
||||
.auth(reviewer.token, auth)
|
||||
.send({ outcome: 'REJECTED', note: 'Brand mark is too small' })
|
||||
.expect(201);
|
||||
expect(rejected.body.decision.outcome).toBe('REJECTED');
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.get(`${versionUrl}/download`)
|
||||
.auth(reader.token, auth)
|
||||
.expect(403)
|
||||
).body.code,
|
||||
).toBe('B2B_ARTWORK_DOWNLOAD_REJECTED');
|
||||
const second = await upload(
|
||||
project.id,
|
||||
ctx.token,
|
||||
Buffer.from('%PDF-1.5\n%%EOF'),
|
||||
).expect(201);
|
||||
expect(second.body.version).toBe(2);
|
||||
const secondUrl = `/api/v1/b2b/artwork-versions/${second.body.id}`;
|
||||
await ctx
|
||||
.api()
|
||||
.post(`${secondUrl}/decision`)
|
||||
.auth(reviewer.token, auth)
|
||||
.send({ outcome: 'APPROVED', note: 'Corrected brand mark' })
|
||||
.expect(201);
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.get(`${secondUrl}/download`)
|
||||
.auth(reader.token, auth)
|
||||
.expect(200)
|
||||
).body,
|
||||
).toEqual(Buffer.from('%PDF-1.5\n%%EOF'));
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.post(`${secondUrl}/decision`)
|
||||
.auth(reviewer.token, auth)
|
||||
.send({ outcome: 'REJECTED', note: 'Changed mind' })
|
||||
.expect(409)
|
||||
).body.code,
|
||||
).toBe('B2B_ARTWORK_DECISION_EXISTS');
|
||||
});
|
||||
|
||||
it('enforces tenant scope and permission checks', async () => {
|
||||
const project = await artwork();
|
||||
const first = await upload(project.id, ctx.token).expect(201);
|
||||
const outsider = await secondActor(ctx, false, [
|
||||
'b2b.artwork.read',
|
||||
'b2b.artwork.review',
|
||||
]);
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.get(`${url}/${project.id}`)
|
||||
.auth(outsider.token, auth)
|
||||
.expect(404)
|
||||
).body.code,
|
||||
).toBe('B2B_ARTWORK_NOT_FOUND');
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.get(`/api/v1/b2b/artwork-versions/${first.body.id}`)
|
||||
.auth(outsider.token, auth)
|
||||
.expect(404)
|
||||
).body.code,
|
||||
).toBe('B2B_ARTWORK_VERSION_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({
|
||||
accountId: project.accountId,
|
||||
name: 'Restricted brand',
|
||||
placement: 'LABEL',
|
||||
brief: 'Restricted artwork',
|
||||
})
|
||||
.expect(403);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue