BIZ8-11 增强采购项目关联
这个提交包含在:
@@ -0,0 +1,9 @@
|
||||
-- BIZ8-11: align purchase requests with the existing lightweight project-link pattern.
|
||||
ALTER TABLE "purchase_requests" ADD COLUMN "project_id" UUID;
|
||||
|
||||
CREATE INDEX "idx_purchase_requests_project" ON "purchase_requests"("project_id");
|
||||
|
||||
ALTER TABLE "purchase_requests"
|
||||
ADD CONSTRAINT "purchase_requests_project_id_fkey"
|
||||
FOREIGN KEY ("project_id") REFERENCES "projects"("id")
|
||||
ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -1047,6 +1047,7 @@ model PurchaseRequest {
|
||||
supplier_id String? @db.Uuid
|
||||
document_category_id String? @db.Uuid
|
||||
budget_pool_id String? @db.Uuid
|
||||
project_id String? @db.Uuid
|
||||
title String @default("")
|
||||
reason String?
|
||||
currency_code String @default("CNY") @db.VarChar(8)
|
||||
@@ -1067,6 +1068,7 @@ model PurchaseRequest {
|
||||
supplier Supplier? @relation(fields: [supplier_id], references: [id], onDelete: SetNull)
|
||||
document_category DocumentCategory? @relation(fields: [document_category_id], references: [id], onDelete: SetNull)
|
||||
budget_pool BudgetPool? @relation(fields: [budget_pool_id], references: [id], onDelete: SetNull)
|
||||
project Project? @relation(fields: [project_id], references: [id], onDelete: SetNull)
|
||||
|
||||
items PurchaseRequestItem[]
|
||||
attachments PurchaseAttachment[]
|
||||
@@ -1082,6 +1084,7 @@ model PurchaseRequest {
|
||||
@@index([supplier_id], map: "idx_purchase_requests_supplier")
|
||||
@@index([document_category_id], map: "idx_purchase_requests_document_category")
|
||||
@@index([budget_pool_id], map: "idx_purchase_requests_budget_pool")
|
||||
@@index([project_id], map: "idx_purchase_requests_project")
|
||||
@@index([status], map: "idx_purchase_requests_status")
|
||||
@@map("purchase_requests")
|
||||
}
|
||||
@@ -1991,6 +1994,7 @@ model Project {
|
||||
tasks ProjectTask[]
|
||||
risks ProjectRisk[]
|
||||
reimbursements ReimbursementForm[]
|
||||
purchase_requests PurchaseRequest[]
|
||||
travel_requests TravelRequest[]
|
||||
todo_items TodoItem[]
|
||||
weekly_reports ProjectLinkOnWeeklyReport[]
|
||||
|
||||
@@ -187,6 +187,7 @@ function buildProjectDetailInclude() {
|
||||
tasks: true,
|
||||
risks: true,
|
||||
reimbursements: true,
|
||||
purchase_requests: true,
|
||||
travel_requests: true,
|
||||
todo_items: true,
|
||||
weekly_reports: true,
|
||||
@@ -425,6 +426,7 @@ function mapProjectDetail(project) {
|
||||
tasks: project._count?.tasks ?? 0,
|
||||
risks: project._count?.risks ?? 0,
|
||||
reimbursements: project._count?.reimbursements ?? 0,
|
||||
purchaseRequests: project._count?.purchase_requests ?? 0,
|
||||
travelRequests: project._count?.travel_requests ?? 0,
|
||||
todoItems: project._count?.todo_items ?? 0,
|
||||
weeklyReports: project._count?.weekly_reports ?? 0,
|
||||
@@ -861,6 +863,29 @@ async function projectsRoutes(fastify) {
|
||||
return sendData(reply, request, { totalAmount: totalAmount.toFixed(2), items: items.map((item) => ({ id: item.id, requestNo: item.request_no ?? item.id, status: item.status, estimatedAmount: String(item.estimated_amount ?? 0), startDate: item.start_date?.toISOString?.().slice(0, 10) ?? null, endDate: item.end_date?.toISOString?.().slice(0, 10) ?? null, updatedAt: item.updated_at?.toISOString?.() ?? null })) });
|
||||
});
|
||||
|
||||
fastify.get("/projects/:id/purchase-requests/summary", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||
await ensureFeatureEnabled(fastify, request, FEATURE_FLAG_KEYS.projectLinking);
|
||||
const projectId = parseId(request.params?.id);
|
||||
await ensureReadableProject(fastify, request, projectId);
|
||||
const items = await fastify.prisma.purchaseRequest.findMany({
|
||||
where: { project_id: projectId },
|
||||
orderBy: { updated_at: "desc" },
|
||||
select: { id: true, request_no: true, title: true, status: true, total_amount: true, updated_at: true },
|
||||
});
|
||||
const totalAmount = items.reduce((sum, item) => sum + Number(item.total_amount ?? 0), 0);
|
||||
return sendData(reply, request, {
|
||||
totalAmount: totalAmount.toFixed(2),
|
||||
items: items.map((item) => ({
|
||||
id: item.id,
|
||||
requestNo: item.request_no ?? item.id,
|
||||
title: item.title,
|
||||
status: item.status,
|
||||
totalAmount: String(item.total_amount ?? 0),
|
||||
updatedAt: item.updated_at?.toISOString?.() ?? null,
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
fastify.get("/projects/:id/weekly-reports", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||
await ensureFeatureEnabled(fastify, request, FEATURE_FLAG_KEYS.projectLinking);
|
||||
const projectId = parseId(request.params?.id);
|
||||
|
||||
@@ -48,6 +48,7 @@ const PURCHASE_LIST_QUERY_SCHEMA = z.object({
|
||||
supplierId: UUID_SCHEMA.optional(),
|
||||
legalEntityId: UUID_SCHEMA.optional(),
|
||||
costCenterId: UUID_SCHEMA.optional(),
|
||||
projectId: UUID_SCHEMA.optional(),
|
||||
});
|
||||
|
||||
const PURCHASE_PATCH_SCHEMA = z
|
||||
@@ -60,6 +61,7 @@ const PURCHASE_PATCH_SCHEMA = z
|
||||
supplierId: UUID_SCHEMA.nullable().optional(),
|
||||
documentCategoryId: UUID_SCHEMA.nullable().optional(),
|
||||
budgetPoolId: UUID_SCHEMA.nullable().optional(),
|
||||
projectId: UUID_SCHEMA.nullable().optional(),
|
||||
expectedDeliveryDate: DATE_ONLY_SCHEMA.nullable().optional(),
|
||||
items: z
|
||||
.array(
|
||||
@@ -106,6 +108,7 @@ const PURCHASE_SUMMARY_SELECT = {
|
||||
supplier_id: true,
|
||||
document_category_id: true,
|
||||
budget_pool_id: true,
|
||||
project_id: true,
|
||||
title: true,
|
||||
reason: true,
|
||||
currency_code: true,
|
||||
@@ -171,6 +174,14 @@ const PURCHASE_SUMMARY_SELECT = {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
project: {
|
||||
select: {
|
||||
id: true,
|
||||
project_no: true,
|
||||
name: true,
|
||||
status: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const PURCHASE_DETAIL_SELECT = {
|
||||
@@ -334,6 +345,7 @@ function parseListQuery(query) {
|
||||
supplierId: parsed.data.supplierId,
|
||||
legalEntityId: parsed.data.legalEntityId,
|
||||
costCenterId: parsed.data.costCenterId,
|
||||
projectId: parsed.data.projectId,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -472,6 +484,7 @@ function mapPurchaseRequestSummary(item) {
|
||||
supplierId: item.supplier_id ?? null,
|
||||
documentCategoryId: item.document_category_id ?? null,
|
||||
budgetPoolId: item.budget_pool_id ?? null,
|
||||
projectId: item.project_id ?? null,
|
||||
title: item.title,
|
||||
reason: item.reason ?? null,
|
||||
currencyCode: item.currency_code,
|
||||
@@ -525,6 +538,14 @@ function mapPurchaseRequestSummary(item) {
|
||||
name: item.budget_pool.name,
|
||||
}
|
||||
: null,
|
||||
project: item.project
|
||||
? {
|
||||
id: item.project.id,
|
||||
projectNo: item.project.project_no,
|
||||
name: item.project.name,
|
||||
status: item.project.status,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -769,10 +790,90 @@ async function ensureBudgetPoolAvailable(tx, budgetPoolId) {
|
||||
return item;
|
||||
}
|
||||
|
||||
async function ensureProjectLinkingEnabled(fastify, tx, request) {
|
||||
const gate = await evaluateFeatureFlag({
|
||||
prisma: tx,
|
||||
config: fastify.config,
|
||||
flagKey: FEATURE_FLAG_KEYS.projectLinking,
|
||||
departmentId: request.employee.department_id ?? null,
|
||||
strictDepartment: false,
|
||||
});
|
||||
|
||||
if (!gate.enabled) {
|
||||
throw buildValidationError({ featureFlag: `${FEATURE_FLAG_KEYS.projectLinking}_disabled`, reason: gate.reason }, 409);
|
||||
}
|
||||
}
|
||||
|
||||
function canReadProjectForLink(fastify, request, project) {
|
||||
if (!project) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
fastify.hasPermission(request.employee, "project.view_all") ||
|
||||
fastify.hasPermission(request.employee, "project.manage") ||
|
||||
fastify.hasPermission(request.employee, "system.settings")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
project.owner_employee_id === request.employee.id ||
|
||||
project.manager_employee_id === request.employee.id ||
|
||||
(project.members ?? []).some((item) => item.employee_id === request.employee.id && item.left_at == null)
|
||||
);
|
||||
}
|
||||
|
||||
async function ensureProjectLinkable(fastify, tx, request, projectId) {
|
||||
if (!projectId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
await ensureProjectLinkingEnabled(fastify, tx, request);
|
||||
|
||||
const project = await tx.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: {
|
||||
id: true,
|
||||
project_no: true,
|
||||
name: true,
|
||||
status: true,
|
||||
owner_employee_id: true,
|
||||
manager_employee_id: true,
|
||||
members: {
|
||||
where: { left_at: null },
|
||||
select: { employee_id: true, left_at: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
throw new AppError({
|
||||
code: "SYS_404",
|
||||
message: "Not Found",
|
||||
statusCode: 404,
|
||||
});
|
||||
}
|
||||
|
||||
if (!canReadProjectForLink(fastify, request, project)) {
|
||||
throw new AppError({
|
||||
code: "PERM_001",
|
||||
message: "无权限",
|
||||
statusCode: 403,
|
||||
details: { permission: "project.view_own" },
|
||||
});
|
||||
}
|
||||
|
||||
if (project.status === "archived") {
|
||||
throw buildValidationError({ projectId: "archived" }, 409);
|
||||
}
|
||||
|
||||
return project;
|
||||
}
|
||||
|
||||
async function loadPurchaseRequestForUpdate(tx, purchaseRequestId) {
|
||||
const rows = await tx.$queryRaw`
|
||||
SELECT id, applicant_id, submitter_id, department_id, legal_entity_id, cost_center_id, supplier_id,
|
||||
document_category_id, budget_pool_id, request_no, currency_code, status
|
||||
document_category_id, budget_pool_id, project_id, request_no, currency_code, status
|
||||
FROM "purchase_requests"
|
||||
WHERE id = ${purchaseRequestId}::uuid
|
||||
FOR UPDATE
|
||||
@@ -1249,6 +1350,7 @@ async function purchaseRequestRoutes(fastify) {
|
||||
...(query.supplierId ? { supplier_id: query.supplierId } : {}),
|
||||
...(query.legalEntityId ? { legal_entity_id: query.legalEntityId } : {}),
|
||||
...(query.costCenterId ? { cost_center_id: query.costCenterId } : {}),
|
||||
...(query.projectId ? { project_id: query.projectId } : {}),
|
||||
...(mineOnly
|
||||
? {
|
||||
OR: [
|
||||
@@ -1411,6 +1513,9 @@ async function purchaseRequestRoutes(fastify) {
|
||||
if (payload.budgetPoolId) {
|
||||
await ensureBudgetPoolAvailable(tx, payload.budgetPoolId);
|
||||
}
|
||||
if (payload.projectId && payload.projectId !== (locked.project_id ?? null)) {
|
||||
await ensureProjectLinkable(fastify, tx, request, payload.projectId);
|
||||
}
|
||||
|
||||
const updateData = {
|
||||
...(payload.title !== undefined ? { title: payload.title.trim() } : {}),
|
||||
@@ -1421,6 +1526,7 @@ async function purchaseRequestRoutes(fastify) {
|
||||
...(payload.supplierId !== undefined ? { supplier_id: payload.supplierId || null } : {}),
|
||||
...(payload.documentCategoryId !== undefined ? { document_category_id: payload.documentCategoryId || null } : {}),
|
||||
...(payload.budgetPoolId !== undefined ? { budget_pool_id: payload.budgetPoolId || null } : {}),
|
||||
...(payload.projectId !== undefined ? { project_id: payload.projectId || null } : {}),
|
||||
...(payload.expectedDeliveryDate !== undefined
|
||||
? {
|
||||
expected_delivery_date: payload.expectedDeliveryDate
|
||||
|
||||
@@ -66,11 +66,12 @@ function buildProjectState(overrides = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
function createPrismaState({ communicationLogs = [], closureChecklistItems = [] } = {}) {
|
||||
function createPrismaState({ communicationLogs = [], closureChecklistItems = [], purchaseRequests = [] } = {}) {
|
||||
const state = {
|
||||
project: buildProjectState(),
|
||||
communicationLogs: communicationLogs.map((item) => ({ ...item })),
|
||||
closureChecklistItems: closureChecklistItems.map((item) => ({ ...item })),
|
||||
purchaseRequests: purchaseRequests.map((item) => ({ ...item })),
|
||||
openRiskCount: 0,
|
||||
openReimbursementCount: 0,
|
||||
openTravelCount: 0,
|
||||
@@ -89,6 +90,7 @@ function createPrismaState({ communicationLogs = [], closureChecklistItems = []
|
||||
tasks: (project.tasks ?? []).length,
|
||||
risks: (project.risks ?? []).length,
|
||||
reimbursements: 0,
|
||||
purchase_requests: state.purchaseRequests.filter((item) => item.project_id === project.id).length,
|
||||
travel_requests: 0,
|
||||
todo_items: 0,
|
||||
weekly_reports: 0,
|
||||
@@ -277,6 +279,13 @@ function createPrismaState({ communicationLogs = [], closureChecklistItems = []
|
||||
projectRisk: { count: vi.fn().mockImplementation(async () => state.openRiskCount) },
|
||||
reimbursementForm: { count: vi.fn().mockImplementation(async () => state.openReimbursementCount) },
|
||||
travelRequest: { count: vi.fn().mockImplementation(async () => state.openTravelCount) },
|
||||
purchaseRequest: {
|
||||
findMany: vi.fn().mockImplementation(async ({ where }) => {
|
||||
return state.purchaseRequests
|
||||
.filter((item) => item.project_id === where.project_id)
|
||||
.sort((left, right) => new Date(right.updated_at).getTime() - new Date(left.updated_at).getTime());
|
||||
}),
|
||||
},
|
||||
projectDeliveryRecord: { count: vi.fn().mockImplementation(async () => state.deliveryRecordCount) },
|
||||
contractRegistry: { count: vi.fn().mockImplementation(async () => state.contractCount) },
|
||||
confidentialDocumentRef: { count: vi.fn().mockImplementation(async () => state.confidentialDocRefCount) },
|
||||
@@ -329,6 +338,79 @@ async function buildApp({ employee, prisma }) {
|
||||
}
|
||||
|
||||
describe("project R23 routes", () => {
|
||||
it("returns purchase request summary only to readable project users", async () => {
|
||||
const { prisma } = createPrismaState({
|
||||
purchaseRequests: [
|
||||
{
|
||||
id: "77777777-7777-4777-8777-777777777777",
|
||||
project_id: PROJECT_ID,
|
||||
request_no: "PR-20260513-001",
|
||||
title: "测试设备采购",
|
||||
status: "approved",
|
||||
total_amount: "1200.50",
|
||||
updated_at: new Date("2026-05-13T08:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: "88888888-8888-4888-8888-888888888888",
|
||||
project_id: PROJECT_ID,
|
||||
request_no: null,
|
||||
title: "未编号采购草稿",
|
||||
status: "draft",
|
||||
total_amount: "99.50",
|
||||
updated_at: new Date("2026-05-13T09:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
});
|
||||
const memberApp = await buildApp({
|
||||
employee: { id: MEMBER_ID, department_id: null, permissionCodes: ["project.view_own"] },
|
||||
prisma,
|
||||
});
|
||||
|
||||
const response = await memberApp.inject({
|
||||
method: "GET",
|
||||
url: `/api/projects/${PROJECT_ID}/purchase-requests/summary`,
|
||||
headers: { authorization: "Bearer test-token" },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().data).toEqual({
|
||||
totalAmount: "1300.00",
|
||||
items: [
|
||||
{
|
||||
id: "88888888-8888-4888-8888-888888888888",
|
||||
requestNo: "88888888-8888-4888-8888-888888888888",
|
||||
title: "未编号采购草稿",
|
||||
status: "draft",
|
||||
totalAmount: "99.50",
|
||||
updatedAt: "2026-05-13T09:00:00.000Z",
|
||||
},
|
||||
{
|
||||
id: "77777777-7777-4777-8777-777777777777",
|
||||
requestNo: "PR-20260513-001",
|
||||
title: "测试设备采购",
|
||||
status: "approved",
|
||||
totalAmount: "1200.50",
|
||||
updatedAt: "2026-05-13T08:00:00.000Z",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const outsiderApp = await buildApp({
|
||||
employee: { id: OUTSIDER_ID, department_id: null, permissionCodes: ["project.view_own"] },
|
||||
prisma,
|
||||
});
|
||||
const forbiddenResponse = await outsiderApp.inject({
|
||||
method: "GET",
|
||||
url: `/api/projects/${PROJECT_ID}/purchase-requests/summary`,
|
||||
headers: { authorization: "Bearer test-token" },
|
||||
});
|
||||
|
||||
expect(forbiddenResponse.statusCode).toBe(403);
|
||||
expect(forbiddenResponse.json().error.code).toBe("PERM_001");
|
||||
|
||||
await Promise.all([memberApp.close(), outsiderApp.close()]);
|
||||
});
|
||||
|
||||
it("allows project member to create communication logs and blocks outsiders", async () => {
|
||||
const { prisma } = createPrismaState();
|
||||
const memberApp = await buildApp({
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
const Fastify = require("fastify");
|
||||
|
||||
const { AppError } = require("../../../src/utils/AppError");
|
||||
const purchaseRequestRoutes = require("../../../src/routes/purchaseRequests");
|
||||
|
||||
const PURCHASE_REQUEST_ID = "11111111-1111-4111-8111-111111111111";
|
||||
const EMPLOYEE_ID = "22222222-2222-4222-8222-222222222222";
|
||||
const OTHER_EMPLOYEE_ID = "33333333-3333-4333-8333-333333333333";
|
||||
const DEPARTMENT_ID = "44444444-4444-4444-8444-444444444444";
|
||||
const PROJECT_ID = "55555555-5555-4555-8555-555555555555";
|
||||
const NOW = new Date("2026-05-13T10:00:00.000Z");
|
||||
|
||||
function buildFeatureFlagRecord(flagKey) {
|
||||
return {
|
||||
id: `flag-${flagKey}`,
|
||||
flag_key: flagKey,
|
||||
override_mode: "force_on",
|
||||
rollout_type: "global",
|
||||
department_ids: [],
|
||||
note: "unit-test",
|
||||
version: 1,
|
||||
created_at: NOW,
|
||||
created_by: null,
|
||||
updated_at: NOW,
|
||||
updated_by: null,
|
||||
};
|
||||
}
|
||||
|
||||
function buildProject(overrides = {}) {
|
||||
return {
|
||||
id: PROJECT_ID,
|
||||
project_no: "PRJ-BIZ8",
|
||||
name: "BIZ8 测试项目",
|
||||
status: "active",
|
||||
owner_employee_id: EMPLOYEE_ID,
|
||||
manager_employee_id: null,
|
||||
members: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function buildPurchaseRequest(overrides = {}) {
|
||||
return {
|
||||
id: PURCHASE_REQUEST_ID,
|
||||
request_no: null,
|
||||
applicant_id: EMPLOYEE_ID,
|
||||
submitter_id: null,
|
||||
department_id: DEPARTMENT_ID,
|
||||
legal_entity_id: null,
|
||||
cost_center_id: null,
|
||||
supplier_id: null,
|
||||
document_category_id: null,
|
||||
budget_pool_id: null,
|
||||
project_id: null,
|
||||
title: "项目关联采购草稿",
|
||||
reason: null,
|
||||
currency_code: "CNY",
|
||||
total_amount: "0.00",
|
||||
expected_delivery_date: null,
|
||||
status: "draft",
|
||||
created_at: NOW,
|
||||
updated_at: NOW,
|
||||
applicant: { id: EMPLOYEE_ID, employee_no: "E001", name: "申请人" },
|
||||
submitter: null,
|
||||
department: { id: DEPARTMENT_ID, name: "测试部门" },
|
||||
legal_entity: null,
|
||||
cost_center: null,
|
||||
supplier: null,
|
||||
document_category: null,
|
||||
budget_pool: null,
|
||||
project: null,
|
||||
items: [],
|
||||
attachments: [],
|
||||
order_archive: null,
|
||||
workflow_instances: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function buildApp({
|
||||
project = buildProject(),
|
||||
actorId = EMPLOYEE_ID,
|
||||
permissionCodes = ["procurement.create", "procurement.view_own", "project.view_own"],
|
||||
purchaseRequestOverrides = {},
|
||||
purchaseRequests = null,
|
||||
} = {}) {
|
||||
const app = Fastify();
|
||||
const actor = {
|
||||
id: actorId,
|
||||
department_id: DEPARTMENT_ID,
|
||||
roleCodes: [],
|
||||
permissionCodes,
|
||||
};
|
||||
const state = {
|
||||
purchaseRequest: buildPurchaseRequest(purchaseRequestOverrides),
|
||||
purchaseRequests: null,
|
||||
auditEntries: [],
|
||||
};
|
||||
state.purchaseRequests = purchaseRequests?.map((item) => buildPurchaseRequest(item)) ?? [state.purchaseRequest];
|
||||
|
||||
function attachProjectRelation(item) {
|
||||
return {
|
||||
...item,
|
||||
project: item.project_id === project.id
|
||||
? {
|
||||
id: project.id,
|
||||
project_no: project.project_no,
|
||||
name: project.name,
|
||||
status: project.status,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
const tx = {
|
||||
$queryRaw: vi.fn(async () => [state.purchaseRequest]),
|
||||
featureFlag: {
|
||||
findUnique: vi.fn(async ({ where }) => buildFeatureFlagRecord(where.flag_key)),
|
||||
},
|
||||
project: {
|
||||
findUnique: vi.fn(async ({ where }) => (where.id === project.id ? project : null)),
|
||||
},
|
||||
purchaseRequest: {
|
||||
update: vi.fn(async ({ data }) => {
|
||||
state.purchaseRequest = {
|
||||
...state.purchaseRequest,
|
||||
...(data.project_id !== undefined ? { project_id: data.project_id } : {}),
|
||||
...(data.title !== undefined ? { title: data.title } : {}),
|
||||
...(data.reason !== undefined ? { reason: data.reason } : {}),
|
||||
...(data.currency_code !== undefined ? { currency_code: data.currency_code } : {}),
|
||||
...(data.total_amount !== undefined ? { total_amount: data.total_amount } : {}),
|
||||
updated_by: data.updated_by,
|
||||
updated_at: NOW,
|
||||
};
|
||||
return attachProjectRelation(state.purchaseRequest);
|
||||
}),
|
||||
findUnique: vi.fn(async () => attachProjectRelation(state.purchaseRequest)),
|
||||
},
|
||||
auditLog: {
|
||||
create: vi.fn(async ({ data }) => {
|
||||
state.auditEntries.push(data);
|
||||
return { id: "audit-1" };
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
function listMatchesWhere(item, where = {}) {
|
||||
if (where.project_id && item.project_id !== where.project_id) {
|
||||
return false;
|
||||
}
|
||||
if (where.status && item.status !== where.status) {
|
||||
return false;
|
||||
}
|
||||
if (where.OR) {
|
||||
return where.OR.some((entry) => {
|
||||
if (entry.applicant_id) return item.applicant_id === entry.applicant_id;
|
||||
if (entry.submitter_id) return item.submitter_id === entry.submitter_id;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const prisma = {
|
||||
$transaction: vi.fn(async (callback) => callback(tx)),
|
||||
purchaseRequest: {
|
||||
findUnique: vi.fn(async () => attachProjectRelation(state.purchaseRequest)),
|
||||
findMany: vi.fn(async ({ where }) => state.purchaseRequests.filter((item) => listMatchesWhere(item, where)).map(attachProjectRelation)),
|
||||
count: vi.fn(async ({ where }) => state.purchaseRequests.filter((item) => listMatchesWhere(item, where)).length),
|
||||
},
|
||||
entityRiskFlag: {
|
||||
findMany: vi.fn(async () => []),
|
||||
},
|
||||
};
|
||||
|
||||
app.decorate("prisma", prisma);
|
||||
app.decorate("config", {
|
||||
appTimezone: "Asia/Shanghai",
|
||||
projectLinkingEnabled: true,
|
||||
cutoverConsoleEnabled: false,
|
||||
});
|
||||
app.decorate("hasPermission", (employee, permissionCode) => {
|
||||
const permissionCodes = employee?.permissionCodes ?? [];
|
||||
return permissionCodes.includes("*") || permissionCodes.includes(permissionCode);
|
||||
});
|
||||
app.decorate("requirePermission", (permissionCode) => async (request) => {
|
||||
request.employee = actor;
|
||||
if (!app.hasPermission(actor, permissionCode)) {
|
||||
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 });
|
||||
}
|
||||
});
|
||||
app.decorate("authenticate", async (request) => {
|
||||
request.employee = actor;
|
||||
});
|
||||
app.setErrorHandler((error, request, reply) => {
|
||||
reply.status(error.statusCode || 500).send({
|
||||
requestId: request.id,
|
||||
error: {
|
||||
code: error.code || "SYS_001",
|
||||
message: error.message,
|
||||
details: error.details ?? null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
await app.register(purchaseRequestRoutes, { prefix: "/api" });
|
||||
return { app, tx, state };
|
||||
}
|
||||
|
||||
describe("purchase request project link", () => {
|
||||
it("links draft purchase request to a readable active project", async () => {
|
||||
const { app, tx, state } = await buildApp();
|
||||
|
||||
const response = await app.inject({
|
||||
method: "PATCH",
|
||||
url: `/api/purchase-requests/${PURCHASE_REQUEST_ID}`,
|
||||
payload: { projectId: PROJECT_ID },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().data.purchaseRequest).toEqual(
|
||||
expect.objectContaining({
|
||||
id: PURCHASE_REQUEST_ID,
|
||||
projectId: PROJECT_ID,
|
||||
project: {
|
||||
id: PROJECT_ID,
|
||||
projectNo: "PRJ-BIZ8",
|
||||
name: "BIZ8 测试项目",
|
||||
status: "active",
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(state.purchaseRequest.project_id).toBe(PROJECT_ID);
|
||||
expect(tx.auditLog.create).toHaveBeenCalledTimes(1);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("blocks archived projects from new purchase links", async () => {
|
||||
const { app, tx } = await buildApp({
|
||||
project: buildProject({ status: "archived" }),
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "PATCH",
|
||||
url: `/api/purchase-requests/${PURCHASE_REQUEST_ID}`,
|
||||
payload: { projectId: PROJECT_ID },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(409);
|
||||
expect(response.json().error.details).toEqual({ projectId: "archived" });
|
||||
expect(tx.purchaseRequest.update).not.toHaveBeenCalled();
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("does not revalidate an unchanged existing project link during draft edits", async () => {
|
||||
const { app, tx } = await buildApp({
|
||||
project: buildProject({ status: "archived" }),
|
||||
purchaseRequestOverrides: {
|
||||
project_id: PROJECT_ID,
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "PATCH",
|
||||
url: `/api/purchase-requests/${PURCHASE_REQUEST_ID}`,
|
||||
payload: { projectId: PROJECT_ID, title: "只修改标题" },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().data.purchaseRequest).toEqual(
|
||||
expect.objectContaining({
|
||||
projectId: PROJECT_ID,
|
||||
title: "只修改标题",
|
||||
project: expect.objectContaining({ status: "archived" }),
|
||||
}),
|
||||
);
|
||||
expect(tx.project.findUnique).not.toHaveBeenCalled();
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("does not let unreadable projects be linked to purchase drafts", async () => {
|
||||
const { app, tx } = await buildApp({
|
||||
project: buildProject({ owner_employee_id: OTHER_EMPLOYEE_ID }),
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "PATCH",
|
||||
url: `/api/purchase-requests/${PURCHASE_REQUEST_ID}`,
|
||||
payload: { projectId: PROJECT_ID },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
expect(response.json().error.code).toBe("PERM_001");
|
||||
expect(tx.purchaseRequest.update).not.toHaveBeenCalled();
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("filters purchase request list by project id", async () => {
|
||||
const otherProjectId = "66666666-6666-4666-8666-666666666666";
|
||||
const { app } = await buildApp({
|
||||
permissionCodes: ["procurement.view_all"],
|
||||
purchaseRequests: [
|
||||
{
|
||||
id: PURCHASE_REQUEST_ID,
|
||||
project_id: PROJECT_ID,
|
||||
request_no: "PR-001",
|
||||
title: "关联项目采购",
|
||||
status: "draft",
|
||||
},
|
||||
{
|
||||
id: "77777777-7777-4777-8777-777777777777",
|
||||
project_id: otherProjectId,
|
||||
request_no: "PR-002",
|
||||
title: "其他项目采购",
|
||||
status: "draft",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/purchase-requests?projectId=${PROJECT_ID}&mine=0`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().data).toEqual(
|
||||
expect.objectContaining({
|
||||
total: 1,
|
||||
items: [
|
||||
expect.objectContaining({
|
||||
id: PURCHASE_REQUEST_ID,
|
||||
projectId: PROJECT_ID,
|
||||
project: expect.objectContaining({
|
||||
projectNo: "PRJ-BIZ8",
|
||||
name: "BIZ8 测试项目",
|
||||
}),
|
||||
}),
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("does not let project membership bypass purchase detail permission", async () => {
|
||||
const { app } = await buildApp({
|
||||
actorId: OTHER_EMPLOYEE_ID,
|
||||
project: buildProject({ owner_employee_id: OTHER_EMPLOYEE_ID }),
|
||||
permissionCodes: ["procurement.view_own", "project.view_own"],
|
||||
purchaseRequestOverrides: {
|
||||
applicant_id: EMPLOYEE_ID,
|
||||
project_id: PROJECT_ID,
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/purchase-requests/${PURCHASE_REQUEST_ID}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
expect(response.json().error.code).toBe("PERM_001");
|
||||
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
在新工单中引用
屏蔽一个用户