feat(procurement): add private versioned supplier documents #12

Merged
mihir merged 1 commits from feat/private-documents into main 2026-09-28 15:41:24 +05:30
17 changed files with 944 additions and 1 deletions

View File

@ -37,6 +37,7 @@ Phase 2B adds [purchase-order drafts and issuance](docs/purchase-orders-api.md).
Phase 2C adds [partial goods receipts and quality inspection](docs/goods-receipts-api.md).
Phase 2D adds [supplier invoice matching and voids](docs/supplier-invoices-api.md).
Phase 2E adds [supplier payment records and reversals](docs/supplier-payments-api.md). Material stock movements and production remain later milestones.
Phase 2F adds [private versioned supplier documents and review](docs/supplier-documents-api.md).
### Swagger UI

View File

@ -19,6 +19,7 @@ Suppliers, material/urli classification and compatibility, procurement, purchase
- 2C (implemented): partial goods receipts and QC decisions.
- 2D (implemented): supplier invoice matching and auditable voids. Tax rules, payments, and documents remain separate milestones.
- 2E (implemented): external supplier payment records, partial balances, idempotent retries, and auditable reversals. Bank reconciliation and proof documents remain separate milestones.
- 2F (implemented): private PDF versions for supplier documents, independent validation, and gated downloads. Retention and malware scanning remain deployment decisions.
## Phase 3: B2B and white label

View File

@ -0,0 +1,21 @@
# Phase 2F: private supplier documents
Supplier documents are stored as PostgreSQL `bytea` with a strict 2 MiB PDF limit. The API has no public file URL. Metadata responses never contain file bytes.
All routes are under `/api/v1` and require a bearer token. `supplier_document.read` permits metadata reads and approved downloads. `supplier_document.manage` permits creating document records and uploading versions. `supplier_document.validate` permits an independent reviewer to approve or reject a version and to download pending versions for review. A reviewer also needs `supplier_document.read` to use the review download route. Records are organization scoped.
| Method | Route | Purpose |
| ------ | ------------------------------------------ | -------------------------------------------------- |
| GET | `/suppliers/:supplierId/documents` | Page through a supplier's document records |
| POST | `/suppliers/:supplierId/documents` | Create a document identity |
| GET | `/supplier-documents/:id` | Read metadata and all versions, newest first |
| POST | `/supplier-documents/:id/versions` | Upload a new PDF version as multipart field `file` |
| GET | `/supplier-document-versions/:id` | Read version metadata and decision |
| GET | `/supplier-document-versions/:id/download` | Download approved PDF or review a pending version |
| POST | `/supplier-document-versions/:id/decision` | Approve or reject a version exactly once |
Create a document with `{"code":"TAX-CERT","kind":"TAX_CERTIFICATE","title":"Supplier tax certificate"}`. Kinds are `REGISTRATION`, `TAX_CERTIFICATE`, `COMPLIANCE_CERTIFICATE`, and `OTHER`. The code is normalized to uppercase and unique per supplier. Up to 100 documents per supplier and 20 sequential versions per document are supported. Lists use `limit` (default 25, maximum 100) and `offset` (default 0).
Upload a PDF with a simple ASCII `.pdf` filename. The server checks filename, MIME type, PDF signature, EOF marker, and byte size, then records SHA-256, uploader, and version number. Each version and validation decision is immutable. Reject with `{"outcome":"REJECTED","reason":"Expired"}` or approve with `{"outcome":"APPROVED"}`. The uploader cannot validate their own version. General readers can download only approved versions. Downloads are checksum-verified and sent with `Content-Disposition: attachment`, `nosniff`, `no-store`, and a sandbox content-security policy.
Validation is a human review step, not an antivirus scan or a legal certification. Operators should review files in an isolated environment. PostgreSQL backup access and retention need the same controls as the API; the product retention policy and automated malware scanning remain deployment decisions. A later storage adapter can move bytes to private object storage without changing document identities or version decisions.

66
prisma/documents.prisma Normal file
View File

@ -0,0 +1,66 @@
enum SupplierDocumentKind {
REGISTRATION
TAX_CERTIFICATE
COMPLIANCE_CERTIFICATE
OTHER
}
enum SupplierDocumentOutcome {
APPROVED
REJECTED
}
model SupplierDocument {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
supplierId String @map("supplier_id") @db.Uuid
createdById String @map("created_by_id") @db.Uuid
code String @db.VarChar(32)
kind SupplierDocumentKind
title String @db.VarChar(160)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
supplier Supplier @relation(fields: [supplierId, organizationId], references: [id, organizationId], onDelete: Restrict)
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
versions SupplierDocumentVersion[]
@@unique([organizationId, supplierId, code])
@@unique([id, organizationId])
@@index([organizationId, supplierId, createdAt, id], map: "supplier_documents_supplier_created_idx")
@@map("supplier_documents")
}
model SupplierDocumentVersion {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
documentId String @map("document_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)
document SupplierDocument @relation(fields: [documentId, organizationId], references: [id, organizationId], onDelete: Restrict)
uploadedBy User @relation(fields: [uploadedById, organizationId], references: [id, organizationId], onDelete: Restrict)
decision SupplierDocumentDecision?
@@unique([documentId, version])
@@unique([id, organizationId])
@@index([organizationId, documentId, version])
@@map("supplier_document_versions")
}
model SupplierDocumentDecision {
versionId String @id @map("version_id") @db.Uuid
organizationId String @map("organization_id") @db.Uuid
validatedById String @map("validated_by_id") @db.Uuid
outcome SupplierDocumentOutcome
reason String? @db.VarChar(500)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
version SupplierDocumentVersion @relation(fields: [versionId, organizationId], references: [id, organizationId], onDelete: Restrict, map: "supplier_document_decision_version_scope_fkey")
validatedBy User @relation(fields: [validatedById, organizationId], references: [id, organizationId], onDelete: Restrict, map: "supplier_document_decision_actor_scope_fkey")
@@unique([versionId, organizationId])
@@map("supplier_document_decisions")
}

View File

@ -18,5 +18,6 @@
"20260923001040_purchase_order_reconciliation": "63ddf7618ff14916512597cc16af2de07e0c093d345bb35e607ed830d3ef067e",
"20260928123638_goods_receipts_qc": "a09646d8a3a1f520495ddbe611c61437ddfcec4585486f94fc383d9b1312006c",
"20260928130714_supplier_invoices": "63945cff1725929e90fe73ade79348480e04a36976dbdb2a021a574569c35049",
"20260928145745_supplier_payments": "012ff1c33c1afa8e6fd883925616f014e7cfdac258fac37ac2ae56739e95bf6d"
"20260928145745_supplier_payments": "012ff1c33c1afa8e6fd883925616f014e7cfdac258fac37ac2ae56739e95bf6d",
"20260928151912_supplier_documents": "65ec974aa6bd0e8f85dc0dbde00f5ef5d9ab81811aba17d89299b6464d4ee6c1"
}

View File

@ -0,0 +1,86 @@
CREATE TYPE "SupplierDocumentKind" AS ENUM ('REGISTRATION', 'TAX_CERTIFICATE', 'COMPLIANCE_CERTIFICATE', 'OTHER');
CREATE TYPE "SupplierDocumentOutcome" AS ENUM ('APPROVED', 'REJECTED');
CREATE TABLE "supplier_documents" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"supplier_id" UUID NOT NULL,
"created_by_id" UUID NOT NULL,
"code" VARCHAR(32) NOT NULL,
"kind" "SupplierDocumentKind" NOT NULL,
"title" VARCHAR(160) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "supplier_documents_pkey" PRIMARY KEY ("id"),
CONSTRAINT "supplier_documents_code" CHECK ("code" ~ '^[A-Z0-9][A-Z0-9_-]{0,31}$' AND LENGTH(TRIM("title")) > 0)
);
CREATE UNIQUE INDEX "supplier_documents_organization_id_supplier_id_code_key" ON "supplier_documents"("organization_id", "supplier_id", "code");
CREATE UNIQUE INDEX "supplier_documents_id_organization_id_key" ON "supplier_documents"("id", "organization_id");
CREATE INDEX "supplier_documents_supplier_created_idx" ON "supplier_documents"("organization_id", "supplier_id", "created_at", "id");
ALTER TABLE "supplier_documents" ADD CONSTRAINT "supplier_documents_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_documents" ADD CONSTRAINT "supplier_documents_supplier_id_organization_id_fkey" FOREIGN KEY ("supplier_id", "organization_id") REFERENCES "suppliers"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_documents" ADD CONSTRAINT "supplier_documents_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 "supplier_document_versions" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"document_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 "supplier_document_versions_pkey" PRIMARY KEY ("id"),
CONSTRAINT "supplier_document_versions_valid" CHECK (
"version" BETWEEN 1 AND 20 AND "size" BETWEEN 1 AND 2097152
AND OCTET_LENGTH("content") = "size"
AND SUBSTRING("content" FROM 1 FOR 5) = decode('255044462d', 'hex')
AND "mime_type" = 'application/pdf'
AND "sha256" ~ '^[a-f0-9]{64}$'
AND "filename" ~ '^[A-Za-z0-9][A-Za-z0-9._-]{0,115}[.]pdf$'
)
);
CREATE UNIQUE INDEX "supplier_document_versions_document_id_version_key" ON "supplier_document_versions"("document_id", "version");
CREATE UNIQUE INDEX "supplier_document_versions_id_organization_id_key" ON "supplier_document_versions"("id", "organization_id");
CREATE INDEX "supplier_document_versions_organization_id_document_id_vers_idx" ON "supplier_document_versions"("organization_id", "document_id", "version");
ALTER TABLE "supplier_document_versions" ADD CONSTRAINT "supplier_document_versions_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_document_versions" ADD CONSTRAINT "supplier_document_versions_document_id_organization_id_fkey" FOREIGN KEY ("document_id", "organization_id") REFERENCES "supplier_documents"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_document_versions" ADD CONSTRAINT "supplier_document_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 "supplier_document_decisions" (
"version_id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"validated_by_id" UUID NOT NULL,
"outcome" "SupplierDocumentOutcome" NOT NULL,
"reason" VARCHAR(500),
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "supplier_document_decisions_pkey" PRIMARY KEY ("version_id"),
CONSTRAINT "supplier_document_decisions_reason" CHECK ("outcome" <> 'REJECTED' OR ("reason" IS NOT NULL AND LENGTH(TRIM("reason")) > 0))
);
CREATE UNIQUE INDEX "supplier_document_decisions_version_id_organization_id_key" ON "supplier_document_decisions"("version_id", "organization_id");
ALTER TABLE "supplier_document_decisions" ADD CONSTRAINT "supplier_document_decisions_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_document_decisions" ADD CONSTRAINT "supplier_document_decision_version_scope_fkey" FOREIGN KEY ("version_id", "organization_id") REFERENCES "supplier_document_versions"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_document_decisions" ADD CONSTRAINT "supplier_document_decision_actor_scope_fkey" FOREIGN KEY ("validated_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
UPDATE "roles" SET "permissions" = array_append(array_append(array_append("permissions", 'supplier_document.read'), 'supplier_document.manage'), 'supplier_document.validate')
WHERE "is_system" = true AND "name" = 'Owner' AND NOT ('supplier_document.read' = ANY("permissions"));
CREATE FUNCTION check_supplier_document_version() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE previous_version INTEGER;
BEGIN
PERFORM id FROM supplier_documents WHERE id = NEW.document_id FOR UPDATE;
SELECT COALESCE(MAX(version), 0) INTO previous_version FROM supplier_document_versions WHERE document_id = NEW.document_id;
IF NEW.version <> previous_version + 1 THEN RAISE EXCEPTION 'Supplier document version must be sequential'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER supplier_document_version_sequence BEFORE INSERT ON supplier_document_versions FOR EACH ROW EXECUTE FUNCTION check_supplier_document_version();
CREATE FUNCTION reject_supplier_document_mutation() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'Supplier document records are immutable'; END;
$$;
CREATE TRIGGER supplier_documents_immutable BEFORE UPDATE OR DELETE ON supplier_documents FOR EACH ROW EXECUTE FUNCTION reject_supplier_document_mutation();
CREATE TRIGGER supplier_document_versions_immutable BEFORE UPDATE OR DELETE ON supplier_document_versions FOR EACH ROW EXECUTE FUNCTION reject_supplier_document_mutation();
CREATE TRIGGER supplier_document_decisions_immutable BEFORE UPDATE OR DELETE ON supplier_document_decisions FOR EACH ROW EXECUTE FUNCTION reject_supplier_document_mutation();

View File

@ -47,6 +47,7 @@ model Supplier {
materials SupplierMaterial[]
purchaseOrders PurchaseOrder[]
invoices SupplierInvoice[]
documents SupplierDocument[]
@@unique([organizationId, code])
@@unique([id, organizationId])

View File

@ -33,6 +33,9 @@ model Organization {
supplierInvoiceVoids SupplierInvoiceVoid[]
supplierPayments SupplierPayment[]
supplierPaymentReversals SupplierPaymentReversal[]
supplierDocuments SupplierDocument[]
supplierDocumentVersions SupplierDocumentVersion[]
supplierDocumentDecisions SupplierDocumentDecision[]
@@map("organizations")
}
model User {
@ -57,6 +60,9 @@ model User {
supplierInvoiceVoids SupplierInvoiceVoid[]
supplierPayments SupplierPayment[]
supplierPaymentReversals SupplierPaymentReversal[]
supplierDocuments SupplierDocument[]
supplierDocumentVersions SupplierDocumentVersion[]
supplierDocumentDecisions SupplierDocumentDecision[]
stockEntries StockLedger[]
stockReservations StockReservation[]
carts Cart[]

View File

@ -231,4 +231,79 @@ export const COMMERCE_ERRORS = {
'Supplier payment is already reversed',
'Duplicate supplier payment reversal rejected',
],
DOCUMENT_NOT_FOUND: [
404,
'Supplier document not found',
'Scoped supplier document lookup failed',
],
DOCUMENT_VERSION_NOT_FOUND: [
404,
'Document version not found',
'Scoped document version lookup failed',
],
DOCUMENT_CODE_CONFLICT: [
409,
'Document code is already used for this supplier',
'Supplier document code duplicate',
],
DOCUMENT_LIMIT: [
409,
'Supplier document limit reached',
'Supplier document resource quota exceeded',
],
DOCUMENT_VERSION_LIMIT: [
409,
'Document version limit reached',
'Supplier document version quota exceeded',
],
DOCUMENT_FILE_REQUIRED: [
400,
'PDF file is required',
'Supplier document upload lacked file',
],
DOCUMENT_FILE_TOO_LARGE: [
413,
'PDF exceeds the 2 MiB limit',
'Supplier document byte limit exceeded',
],
DOCUMENT_FILENAME_INVALID: [
400,
'Use a simple .pdf filename',
'Supplier document filename rejected',
],
DOCUMENT_FILE_INVALID: [
400,
'Upload a valid PDF file',
'Supplier document MIME or signature rejected',
],
DOCUMENT_DECISION_EXISTS: [
409,
'Document version was already validated',
'Duplicate supplier document validation rejected',
],
DOCUMENT_REJECTION_REASON_REQUIRED: [
400,
'Give a reason for rejecting the document',
'Supplier document rejection lacked reason',
],
DOCUMENT_SELF_VALIDATION_DENIED: [
403,
'Another reviewer must validate this document',
'Supplier document self-validation rejected',
],
DOCUMENT_PENDING_REVIEW: [
403,
'Document is awaiting validation',
'Pending supplier document download rejected',
],
DOCUMENT_REJECTED: [
403,
'Document was rejected',
'Rejected supplier document download rejected',
],
DOCUMENT_INTEGRITY_FAILURE: [
500,
'Document is temporarily unavailable',
'Supplier document checksum verification failed',
],
} as const;

View File

@ -23,5 +23,8 @@ export const PERMISSIONS = [
'procurement.read',
'procurement.manage',
'supplier_payment.manage',
'supplier_document.read',
'supplier_document.manage',
'supplier_document.validate',
] as const;
export type Permission = (typeof PERMISSIONS)[number];

View File

@ -8,6 +8,12 @@ import { PurchaseOrderStore } from './purchase-order.store';
import { GoodsReceiptStore } from './goods-receipt.store';
import { SupplierInvoiceStore } from './supplier-invoice.store';
import { SupplierPaymentStore } from './supplier-payment.store';
import { SupplierDocumentStore } from './supplier-document.store';
import {
SupplierDocumentsController,
SupplierDocumentController,
SupplierDocumentVersionsController,
} from './supplier-documents.controller';
import {
InvoicePaymentsController,
SupplierPaymentsController,
@ -29,6 +35,7 @@ import {
GoodsReceiptStore,
SupplierInvoiceStore,
SupplierPaymentStore,
SupplierDocumentStore,
],
controllers: [
ProcurementController,
@ -39,6 +46,9 @@ import {
SupplierInvoicesController,
InvoicePaymentsController,
SupplierPaymentsController,
SupplierDocumentsController,
SupplierDocumentController,
SupplierDocumentVersionsController,
],
})
export class ProcurementModule {}

View File

@ -0,0 +1,41 @@
import { createHash } from 'node:crypto';
import { AppError } from '../common/errors/app-error';
export const MAX_DOCUMENT_BYTES = 2 * 1024 * 1024;
export type UploadedDocument = {
buffer: Buffer;
size: number;
mimetype: string;
originalname: string;
};
export function inspectPdf(file?: UploadedDocument) {
if (!file) throw new AppError('DOCUMENT_FILE_REQUIRED');
if (file.buffer.length > MAX_DOCUMENT_BYTES)
throw new AppError('DOCUMENT_FILE_TOO_LARGE');
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,115}\.pdf$/.test(file.originalname))
throw new AppError('DOCUMENT_FILENAME_INVALID');
if (
file.size !== file.buffer.length ||
file.buffer.length === 0 ||
file.mimetype !== 'application/pdf' ||
!file.buffer.subarray(0, 5).equals(Buffer.from('%PDF-')) ||
!file.buffer.subarray(-1024).includes(Buffer.from('%%EOF'))
)
throw new AppError('DOCUMENT_FILE_INVALID');
return {
filename: file.originalname,
mimeType: 'application/pdf',
size: file.buffer.length,
sha256: createHash('sha256').update(file.buffer).digest('hex'),
content: Uint8Array.from(file.buffer),
};
}
export function verifiedContent(
content: Uint8Array,
expectedHash: string,
): Buffer {
const bytes = Buffer.from(content);
if (createHash('sha256').update(bytes).digest('hex') !== expectedHash)
throw new AppError('DOCUMENT_INTEGRITY_FAILURE');
return bytes;
}

View File

@ -0,0 +1,28 @@
import { z } from 'zod';
export const supplierDocumentSchema = z
.object({
code: z
.string()
.trim()
.min(1)
.max(32)
.regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/)
.transform((value) => value.toUpperCase()),
kind: z.enum([
'REGISTRATION',
'TAX_CERTIFICATE',
'COMPLIANCE_CERTIFICATE',
'OTHER',
]),
title: z.string().trim().min(1).max(160),
})
.strict();
export const documentDecisionSchema = z
.object({
outcome: z.enum(['APPROVED', 'REJECTED']),
reason: z.string().trim().min(1).max(500).optional(),
})
.strict();
export type SupplierDocumentInput = z.infer<typeof supplierDocumentSchema>;
export type DocumentDecisionInput = z.infer<typeof documentDecisionSchema>;

View File

@ -0,0 +1,205 @@
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 { PageInput } from '../identity/identity.schemas';
import type { Principal } from '../identity/identity.types';
import {
inspectPdf,
verifiedContent,
type UploadedDocument,
} from './supplier-document-file';
import type {
DocumentDecisionInput,
SupplierDocumentInput,
} from './supplier-document.schemas';
const versionSelect = {
id: true,
organizationId: true,
documentId: true,
uploadedById: true,
version: true,
filename: true,
mimeType: true,
sha256: true,
size: true,
createdAt: true,
decision: true,
} as const;
const documentView = {
versions: { select: versionSelect, orderBy: { version: 'desc' as const } },
};
@Injectable()
export class SupplierDocumentStore {
constructor(
private readonly db: DatabaseService,
private readonly access: AccessStore,
) {}
async list(actor: Principal, supplierId: string, query: PageInput) {
const supplier = await this.db.supplier.findFirst({
where: { id: supplierId, organizationId: actor.organizationId },
select: { id: true },
});
if (!supplier) throw new AppError('SUPPLIER_NOT_FOUND');
return this.db.supplierDocument.findMany({
where: { organizationId: actor.organizationId, supplierId },
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
take: query.limit,
skip: query.offset,
});
}
async find(actor: Principal, id: string) {
const document = await this.db.supplierDocument.findFirst({
where: { id, organizationId: actor.organizationId },
include: documentView,
});
if (!document) throw new AppError('DOCUMENT_NOT_FOUND');
return document;
}
async findVersion(actor: Principal, id: string) {
const version = await this.db.supplierDocumentVersion.findFirst({
where: { id, organizationId: actor.organizationId },
select: versionSelect,
});
if (!version) throw new AppError('DOCUMENT_VERSION_NOT_FOUND');
return version;
}
create(actor: Principal, supplierId: string, input: SupplierDocumentInput) {
return this.access.mutate(actor, 'supplier_document.manage', async (tx) => {
const supplier = await tx.supplier.findFirst({
where: { id: supplierId, organizationId: actor.organizationId },
select: { id: true },
});
if (!supplier) throw new AppError('SUPPLIER_NOT_FOUND');
const duplicate = await tx.supplierDocument.findFirst({
where: {
organizationId: actor.organizationId,
supplierId,
code: input.code,
},
select: { id: true },
});
if (duplicate) throw new AppError('DOCUMENT_CODE_CONFLICT');
if (
(await tx.supplierDocument.count({
where: { organizationId: actor.organizationId, supplierId },
})) >= 100
)
throw new AppError('DOCUMENT_LIMIT');
const document = await tx.supplierDocument.create({
data: {
...input,
organizationId: actor.organizationId,
supplierId,
createdById: actor.userId,
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'supplier_document.created',
document.id,
);
return document;
});
}
addVersion(actor: Principal, documentId: string, file?: UploadedDocument) {
const inspected = inspectPdf(file);
return this.access.mutate(actor, 'supplier_document.manage', async (tx) => {
const document = await tx.supplierDocument.findFirst({
where: { id: documentId, organizationId: actor.organizationId },
select: { id: true },
});
if (!document) throw new AppError('DOCUMENT_NOT_FOUND');
const count = await tx.supplierDocumentVersion.count({
where: { organizationId: actor.organizationId, documentId },
});
if (count >= 20) throw new AppError('DOCUMENT_VERSION_LIMIT');
const version = await tx.supplierDocumentVersion.create({
data: {
...inspected,
organizationId: actor.organizationId,
documentId,
uploadedById: actor.userId,
version: count + 1,
},
select: versionSelect,
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'supplier_document.version_uploaded',
version.id,
);
return version;
});
}
decide(actor: Principal, id: string, input: DocumentDecisionInput) {
return this.access.mutate(
actor,
'supplier_document.validate',
async (tx) => {
const version = await tx.supplierDocumentVersion.findFirst({
where: { id, organizationId: actor.organizationId },
select: { id: true, uploadedById: true, decision: true },
});
if (!version) throw new AppError('DOCUMENT_VERSION_NOT_FOUND');
if (version.decision) throw new AppError('DOCUMENT_DECISION_EXISTS');
if (version.uploadedById === actor.userId)
throw new AppError('DOCUMENT_SELF_VALIDATION_DENIED');
if (input.outcome === 'REJECTED' && !input.reason)
throw new AppError('DOCUMENT_REJECTION_REASON_REQUIRED');
await tx.supplierDocumentDecision.create({
data: {
versionId: id,
organizationId: actor.organizationId,
validatedById: actor.userId,
outcome: input.outcome,
reason: input.reason,
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
input.outcome === 'APPROVED'
? 'supplier_document.approved'
: 'supplier_document.rejected',
id,
);
return tx.supplierDocumentVersion.findUniqueOrThrow({
where: { id },
select: versionSelect,
});
},
);
}
async download(actor: Principal, id: string) {
const version = await this.db.supplierDocumentVersion.findFirst({
where: { id, organizationId: actor.organizationId },
include: { decision: true },
});
if (!version) throw new AppError('DOCUMENT_VERSION_NOT_FOUND');
if (!actor.permissions.includes('supplier_document.validate')) {
if (!version.decision) throw new AppError('DOCUMENT_PENDING_REVIEW');
if (version.decision.outcome === 'REJECTED')
throw new AppError('DOCUMENT_REJECTED');
}
return {
filename: version.filename,
content: verifiedContent(version.content, version.sha256),
};
}
}

View File

@ -0,0 +1,132 @@
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 { pageSchema, type PageInput } from '../identity/identity.schemas';
import type { Principal } from '../identity/identity.types';
import {
MAX_DOCUMENT_BYTES,
type UploadedDocument,
} from './supplier-document-file';
import { SupplierDocumentStore } from './supplier-document.store';
import {
supplierDocumentSchema,
documentDecisionSchema,
type SupplierDocumentInput,
type DocumentDecisionInput,
} from './supplier-document.schemas';
@Controller('suppliers/:supplierId/documents')
export class SupplierDocumentsController {
constructor(private readonly documents: SupplierDocumentStore) {}
@Get()
@RequirePermission('supplier_document.read')
list(
@CurrentPrincipal() actor: Principal,
@Param('supplierId', ParseUUIDPipe) supplierId: string,
@Query(new SchemaPipe(pageSchema)) query: PageInput,
) {
return this.documents.list(actor, supplierId, query);
}
@Post()
@RequirePermission('supplier_document.manage')
create(
@CurrentPrincipal() actor: Principal,
@Param('supplierId', ParseUUIDPipe) supplierId: string,
@Body(new SchemaPipe(supplierDocumentSchema)) input: SupplierDocumentInput,
) {
return this.documents.create(actor, supplierId, input);
}
}
@Controller('supplier-documents')
export class SupplierDocumentController {
constructor(private readonly documents: SupplierDocumentStore) {}
@Get(':id')
@RequirePermission('supplier_document.read')
get(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
) {
return this.documents.find(actor, id);
}
@Post(':id/versions')
@RequirePermission('supplier_document.manage')
@ApiConsumes('multipart/form-data')
@ApiBody({
schema: {
type: 'object',
required: ['file'],
properties: { file: { type: 'string', format: 'binary' } },
},
})
@UseInterceptors(
FileInterceptor('file', {
limits: { fileSize: MAX_DOCUMENT_BYTES + 1, files: 1, fields: 0 },
}),
)
upload(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@UploadedFile() file?: UploadedDocument,
) {
return this.documents.addVersion(actor, id, file);
}
}
@Controller('supplier-document-versions')
export class SupplierDocumentVersionsController {
constructor(private readonly documents: SupplierDocumentStore) {}
@Get(':id')
@RequirePermission('supplier_document.read')
get(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
) {
return this.documents.findVersion(actor, id);
}
@Get(':id/download')
@RequirePermission('supplier_document.read')
@ApiProduces('application/pdf')
async download(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@Res() response: Response,
) {
const file = await this.documents.download(actor, id);
response.setHeader('Content-Type', 'application/pdf');
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('supplier_document.validate')
decide(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@Body(new SchemaPipe(documentDecisionSchema)) input: DocumentDecisionInput,
) {
return this.documents.decide(actor, id, input);
}
}

View File

@ -0,0 +1,37 @@
import {
inspectPdf,
MAX_DOCUMENT_BYTES,
verifiedContent,
} from '../src/procurement/supplier-document-file';
const pdf = Buffer.from('%PDF-1.4\n1 0 obj\n<<>>\nendobj\n%%EOF');
const file = (
buffer: Buffer,
name = 'certificate.pdf',
mimetype = 'application/pdf',
) => ({ buffer, size: buffer.length, originalname: name, mimetype });
describe('supplier document file policy', () => {
it('accepts bounded PDFs and verifies their digest', () => {
const inspected = inspectPdf(file(pdf));
expect(inspected.size).toBe(pdf.length);
expect(verifiedContent(inspected.content, inspected.sha256)).toEqual(pdf);
});
it('rejects invalid bytes, names, and oversize files', () => {
expect(() => inspectPdf()).toThrow(
expect.objectContaining({ code: 'DOCUMENT_FILE_REQUIRED' }),
);
expect(() => inspectPdf(file(Buffer.from('hello')))).toThrow(
expect.objectContaining({ code: 'DOCUMENT_FILE_INVALID' }),
);
expect(() => inspectPdf(file(pdf, '../bad.pdf'))).toThrow(
expect.objectContaining({ code: 'DOCUMENT_FILENAME_INVALID' }),
);
expect(() =>
inspectPdf(file(Buffer.alloc(MAX_DOCUMENT_BYTES + 1))),
).toThrow(expect.objectContaining({ code: 'DOCUMENT_FILE_TOO_LARGE' }));
expect(() => verifiedContent(pdf, '0'.repeat(64))).toThrow(
expect.objectContaining({ code: 'DOCUMENT_INTEGRITY_FAILURE' }),
);
});
});

View File

@ -0,0 +1,229 @@
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('supplier document API', () => {
let ctx: IdentityApp;
const auth = { type: 'bearer' as const };
beforeAll(async () => {
ctx = await identityApp();
}, 60000);
afterAll(async () => {
await ctx?.close();
});
beforeEach(async () => {
await ctx.clearLimits();
});
async function supplier() {
const code = randomUUID().slice(0, 8);
return (
await ctx
.api()
.post('/api/v1/suppliers')
.auth(ctx.token, auth)
.send({
name: `Supplier ${code}`,
code: `S-${code}`,
contactName: 'Asha Shah',
email: `${code}@example.com`,
phone: '+919876543210',
})
.expect(201)
).body as { id: string };
}
async function document() {
const source = await supplier();
const path = `/api/v1/suppliers/${source.id}/documents`;
const created = await ctx
.api()
.post(path)
.auth(ctx.token, auth)
.send({
code: 'tax-cert',
kind: 'TAX_CERTIFICATE',
title: 'Supplier tax certificate',
})
.expect(201);
return { supplierId: source.id, id: created.body.id as string, path };
}
const upload = (id: string, token: string, bytes = pdf) =>
ctx
.api()
.post(`/api/v1/supplier-documents/${id}/versions`)
.auth(token, auth)
.attach('file', bytes, {
filename: 'certificate.pdf',
contentType: 'application/pdf',
});
it('keeps bytes private, versions immutable, and requires another reviewer', async () => {
const source = await document();
const first = await upload(source.id, ctx.token).expect(201);
expect(first.body).toMatchObject({
version: 1,
size: pdf.length,
filename: 'certificate.pdf',
decision: null,
});
expect(first.body.content).toBeUndefined();
const detail = await ctx
.api()
.get(`/api/v1/supplier-documents/${source.id}`)
.auth(ctx.token, auth)
.expect(200);
expect(detail.body.versions[0].content).toBeUndefined();
const reader = await secondActor(ctx, true, ['supplier_document.read']);
const download = `/api/v1/supplier-document-versions/${first.body.id}/download`;
expect(
(await ctx.api().get(download).auth(reader.token, auth).expect(403)).body
.code,
).toBe('DOCUMENT_PENDING_REVIEW');
const decide = `/api/v1/supplier-document-versions/${first.body.id}/decision`;
expect(
(
await ctx
.api()
.post(decide)
.auth(ctx.token, auth)
.send({ outcome: 'APPROVED' })
.expect(403)
).body.code,
).toBe('DOCUMENT_SELF_VALIDATION_DENIED');
const validator = await secondActor(ctx, true, [
'supplier_document.read',
'supplier_document.validate',
]);
const approved = await ctx
.api()
.post(decide)
.auth(validator.token, auth)
.send({ outcome: 'APPROVED' })
.expect(201);
expect(approved.body.decision.outcome).toBe('APPROVED');
expect(
(await ctx.api().get(download).auth(reader.token, auth).expect(200)).body,
).toEqual(pdf);
expect(
(
await ctx
.api()
.post(decide)
.auth(validator.token, auth)
.send({ outcome: 'REJECTED', reason: 'Again' })
.expect(409)
).body.code,
).toBe('DOCUMENT_DECISION_EXISTS');
const second = await upload(
source.id,
ctx.token,
Buffer.from('%PDF-1.5\n%%EOF'),
).expect(201);
expect(second.body.version).toBe(2);
const reject = `/api/v1/supplier-document-versions/${second.body.id}/decision`;
expect(
(
await ctx
.api()
.post(reject)
.auth(validator.token, auth)
.send({ outcome: 'REJECTED' })
.expect(400)
).body.code,
).toBe('DOCUMENT_REJECTION_REASON_REQUIRED');
await ctx
.api()
.post(reject)
.auth(validator.token, auth)
.send({ outcome: 'REJECTED', reason: 'Expired' })
.expect(201);
expect(
(
await ctx
.api()
.get(`/api/v1/supplier-document-versions/${second.body.id}/download`)
.auth(reader.token, auth)
.expect(403)
).body.code,
).toBe('DOCUMENT_REJECTED');
expect(
(await ctx.api().get(source.path).auth(reader.token, auth).expect(200))
.body,
).toHaveLength(1);
});
it('rejects unsafe uploads and duplicate document codes', async () => {
const source = await document();
expect(
(
await ctx
.api()
.post(source.path)
.auth(ctx.token, auth)
.send({
code: 'TAX-CERT',
kind: 'TAX_CERTIFICATE',
title: 'Duplicate',
})
.expect(409)
).body.code,
).toBe('DOCUMENT_CODE_CONFLICT');
expect(
(await upload(source.id, ctx.token, Buffer.from('not a pdf')).expect(400))
.body.code,
).toBe('DOCUMENT_FILE_INVALID');
expect(
(
await ctx
.api()
.post(`/api/v1/supplier-documents/${source.id}/versions`)
.auth(ctx.token, auth)
.expect(400)
).body.code,
).toBe('DOCUMENT_FILE_REQUIRED');
});
it('separates permissions and organization scope', async () => {
const source = await document();
const reader = await secondActor(ctx, true, ['supplier_document.read']);
await ctx.api().get(source.path).auth(reader.token, auth).expect(200);
await ctx
.api()
.post(source.path)
.auth(reader.token, auth)
.send({ code: 'NEW', kind: 'OTHER', title: 'No access' })
.expect(403);
const foreign = await secondActor(ctx, false, [
'supplier_document.read',
'supplier_document.manage',
]);
expect(
(
await ctx
.api()
.get(`/api/v1/supplier-documents/${source.id}`)
.auth(foreign.token, auth)
.expect(404)
).body.code,
).toBe('DOCUMENT_NOT_FOUND');
await upload(source.id, foreign.token).expect(404);
});
it('caps version history without replacing prior bytes', async () => {
const source = await document();
for (let version = 1; version <= 20; version += 1) {
expect(
(await upload(source.id, ctx.token).expect(201)).body.version,
).toBe(version);
}
expect((await upload(source.id, ctx.token).expect(409)).body.code).toBe(
'DOCUMENT_VERSION_LIMIT',
);
const detail = await ctx
.api()
.get(`/api/v1/supplier-documents/${source.id}`)
.auth(ctx.token, auth)
.expect(200);
expect(detail.body.versions).toHaveLength(20);
});
});