- T1 资金/库存/报价/自采 P1(BIZ-1/2/3/4/10/13/14) - T2 主系统反向事件墓碑/改派/孤儿处理(BIZ-6/8/9) - T3 选分公司 ticket、trust proxy、角色权限收口(SEC-2/3/4) - T4 缺列/RLS/tenant 名单/FK/迁移执行器(DATA-1..8) - T5 401 登出/分页/映射口径/blob/ZIP 中文名(FE-1..4/BIZ-15) - T6 测试脚本目标守卫/config fail-fast/容器配置(OPS-2..8) - T7 前后端测试与 lint 门禁清零 - T8 应付卡片按关联订单日(口径 A) - T9 存储对象全链路归属校验、敏感列禁写、审计 target_id 超长修复
1205 lines
49 KiB
TypeScript
1205 lines
49 KiB
TypeScript
import { Router, Response } from 'express';
|
||
import { authMiddleware, type AuthRequest } from '../../../middleware/auth';
|
||
import { pool } from '../../../db';
|
||
import { readOperatingBranchCode, getEffectiveBranchCode } from '../../../services/tenantScope';
|
||
import { buildDirectDeliveryPhotoUrls } from '../../../services/purchaseDirectDeliveryPhotoService';
|
||
import {
|
||
completeSelfPurchase,
|
||
appendPurchaseDirectDeliveryPhoto,
|
||
amendPurchaseActual,
|
||
setPurchaseSelfProcessed,
|
||
skipWarehouseProcessingPurchase,
|
||
createSelfPurchaseStockInbound,
|
||
updateSelfPurchaseStockInbound,
|
||
voidSelfPurchaseStockInbound,
|
||
resubmitSelfPurchaseStockInbound,
|
||
updatePurchaseLinkedSalePrice,
|
||
updateOrderItemSalePrice,
|
||
assignPurchaseOrderToSupplier,
|
||
listAssignableSuppliersForPurchase,
|
||
resetPurchaseAfterQualityReject,
|
||
} from '../../../services/selfPurchaseOps';
|
||
import {
|
||
applyPurchaserAssignment,
|
||
listBranchPurchasers,
|
||
normalizeAssignMode,
|
||
reassignSinglePurchasePurchaser,
|
||
} from '../../../services/purchasePurchaserAssignService';
|
||
import {
|
||
getPurchaseAssignDefaultConfig,
|
||
setPurchaseAssignDefaultConfig,
|
||
} from '../../../services/purchaseAssignDefaultConfigService';
|
||
import {
|
||
getCategoryPurchaserMap,
|
||
setCategoryPurchaserMap,
|
||
} from '../../../services/purchaseCategoryPurchaserMapService';
|
||
import { fetchCategoryRows, getCategoryDisplayLabel, createQuickCatalogCategory } from '../../../services/categoryCatalogService';
|
||
import {
|
||
uploadQualityReport,
|
||
updateQualityReportValidity,
|
||
getActiveQualityReportForPurchase,
|
||
validityStatusLabel,
|
||
listQualityReportsLedger,
|
||
uploadLibraryQualityReport,
|
||
listLibraryQualityReports,
|
||
} from '../../../services/qualityReportService';
|
||
import {
|
||
listQualityReportDayItems,
|
||
listReportsForSupplierDay,
|
||
matchUploadQualityReports,
|
||
rematchLibraryQualityReport,
|
||
updateQualityReportType,
|
||
voidQualityReport,
|
||
} from '../../../services/qualityReportOps';
|
||
import { getWorkflowCtx, requireAdminRole, requireWorkflowPermission } from '../context';
|
||
import {
|
||
getAllowZeroSupplyCostConfig,
|
||
setAllowZeroSupplyCostConfig,
|
||
} from '../../../services/zeroSupplyCostConfigService';
|
||
import { listPurchaseOrdersForManagement, sumSelfPurchaseTotalAmount } from '../../../services/purchaseOrderQueryService';
|
||
import { listPriceInvertRisks } from '../../../services/priceInvertRiskQueryService';
|
||
import { resolveSelfPurchaseWriteAccess } from '../../../services/selfPurchaseHttpAccess';
|
||
import { assertOwnedStoragePaths } from '../../../services/storageObjectOwnership';
|
||
|
||
const PREP_AMEND_PERMS = [
|
||
'preparation_manage',
|
||
'purchase_manage',
|
||
'order_manage',
|
||
'order_entry',
|
||
];
|
||
|
||
/**
|
||
* T9:质检报告上传入口只对「桶内对象路径」做归属断言;
|
||
* data:/裸 base64/外链不是桶内 key(服务端会另存或忽略),不参与归属校验。
|
||
*/
|
||
function uploadPathRefs(files: string[]): string[] {
|
||
return files.filter((value) => {
|
||
const text = String(value || '').trim();
|
||
if (!text) return false;
|
||
if (/^data:/i.test(text) || /^(?:https?:)?\/\//i.test(text)) return false;
|
||
if (text.length > 200 && /^[A-Za-z0-9+/=\s]+$/.test(text)) return false;
|
||
return true;
|
||
});
|
||
}
|
||
|
||
/** 采购模块 workflow API(质检库与 /purchase*) */
|
||
export function mountPurchaseWorkflowRoutes(router: Router): void {
|
||
/**
|
||
* 「允许成本价为 0」开关(分公司级,默认关闭)——**只有分公司管理员能改**(超管不参与)。
|
||
* 设计:docs/design/20260923-allow-zero-supply-cost.md §4
|
||
*/
|
||
router.get('/purchase/allow-zero-cost-config', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
// 读权限要覆盖所有"有成本录入"的页面:采购(自采/备货/独立自采入库)、库存入库、系统配置。
|
||
// 少数只有 inventory_manage 的仓管用户也要能读到开关,否则前端本地校验会误拦 0。
|
||
requireWorkflowPermission(ctx, [
|
||
'purchase_manage',
|
||
'inventory_manage',
|
||
'order_manage',
|
||
'order_entry',
|
||
'system_manage',
|
||
]);
|
||
const branchCode = getEffectiveBranchCode(ctx, readOperatingBranchCode(req));
|
||
const cfg = await getAllowZeroSupplyCostConfig(branchCode);
|
||
return res.json({
|
||
data: { enabled: cfg.enabled, branch_code: cfg.branch_code, source: cfg.source },
|
||
});
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '读取成本价开关失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.put('/purchase/allow-zero-cost-config', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
// 只给分公司管理员:requireAdminRole 只认 admin 角色(超管不含 admin)→ 超管改不了
|
||
requireAdminRole(ctx, '仅分公司管理员可修改该开关');
|
||
const branchCode = getEffectiveBranchCode(ctx, readOperatingBranchCode(req));
|
||
if (!branchCode) {
|
||
return res.status(400).json({
|
||
error: 'operating_branch_required',
|
||
error_description: '请先选择操作分公司',
|
||
});
|
||
}
|
||
if (typeof req.body?.enabled !== 'boolean') {
|
||
return res.status(400).json({
|
||
error: 'invalid_request',
|
||
error_description: '请提供 enabled 布尔值',
|
||
});
|
||
}
|
||
const saved = await setAllowZeroSupplyCostConfig(branchCode, req.body.enabled, req.userId || null);
|
||
return res.json({ data: { enabled: saved.enabled, branch_code: branchCode } });
|
||
} catch (error: any) {
|
||
const status = Number(error?.status) || 500;
|
||
return res.status(status).json({
|
||
// 403 用 forbidden(超管调用会走到这里:requireAdminRole 只认 admin 角色)
|
||
error: error?.code || (status === 403 ? 'forbidden' : 'server_error'),
|
||
error_description: error?.message || '保存成本价开关失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
|
||
function resolvePurchaseBranch(ctx: Awaited<ReturnType<typeof getWorkflowCtx>>, req: AuthRequest): string {
|
||
if (!ctx) {
|
||
throw Object.assign(new Error('未登录'), { status: 401 });
|
||
}
|
||
const branchCode = getEffectiveBranchCode(ctx, readOperatingBranchCode(req));
|
||
if (!branchCode) {
|
||
throw Object.assign(new Error('请选择当前操作分公司'), { status: 400, code: 'branch_required' });
|
||
}
|
||
return branchCode;
|
||
}
|
||
|
||
router.get('/quality-reports', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, [...PREP_AMEND_PERMS]);
|
||
const proto = String(req.headers['x-forwarded-proto'] || req.protocol || 'https');
|
||
const host = String(req.headers['x-forwarded-host'] || req.get('host') || '');
|
||
const libraryOnly =
|
||
req.query?.library_only === '1' ||
|
||
req.query?.library_only === 'true' ||
|
||
String(req.query?.library_only || '').toLowerCase() === 'yes';
|
||
const includeVoided =
|
||
req.query?.include_voided === '1' ||
|
||
req.query?.include_voided === 'true' ||
|
||
String(req.query?.include_voided || '').toLowerCase() === 'yes';
|
||
const data = await listQualityReportsLedger({
|
||
dateFrom: typeof req.query?.from === 'string' ? req.query.from : null,
|
||
dateTo: typeof req.query?.to === 'string' ? req.query.to : null,
|
||
supplierCode: typeof req.query?.supplier_code === 'string' ? req.query.supplier_code : null,
|
||
batchNo: typeof req.query?.batch_no === 'string' ? req.query.batch_no : null,
|
||
validityStatus: typeof req.query?.validity_status === 'string' ? req.query.validity_status : null,
|
||
q: typeof req.query?.q === 'string' ? req.query.q : null,
|
||
libraryOnly,
|
||
includeVoided,
|
||
requestHost: host ? `${proto}://${host}` : null,
|
||
limit: req.query?.limit != null ? Number(req.query.limit) : 100,
|
||
});
|
||
return res.json({ data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '加载检验报告台账失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.get('/quality-reports/library', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, [...PREP_AMEND_PERMS, 'order_create', 'order_entry', 'order_manage']);
|
||
const proto = String(req.headers['x-forwarded-proto'] || req.protocol || 'https');
|
||
const host = String(req.headers['x-forwarded-host'] || req.get('host') || '');
|
||
const includeVoided =
|
||
req.query?.include_voided === '1' ||
|
||
req.query?.include_voided === 'true' ||
|
||
String(req.query?.include_voided || '').toLowerCase() === 'yes';
|
||
const data = await listLibraryQualityReports({
|
||
supplierCode: typeof req.query?.supplier_code === 'string' ? req.query.supplier_code : null,
|
||
reportDate: typeof req.query?.report_date === 'string' ? req.query.report_date : null,
|
||
dateFrom: typeof req.query?.from === 'string' ? req.query.from : null,
|
||
dateTo: typeof req.query?.to === 'string' ? req.query.to : null,
|
||
q: typeof req.query?.q === 'string' ? req.query.q : null,
|
||
includeVoided,
|
||
requestHost: host ? `${proto}://${host}` : null,
|
||
limit: req.query?.limit != null ? Number(req.query.limit) : 100,
|
||
});
|
||
return res.json({ data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '加载质检报告库失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.post('/quality-reports/library', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, [...PREP_AMEND_PERMS, 'order_create', 'order_entry', 'order_manage']);
|
||
const files = Array.isArray(req.body?.files)
|
||
? req.body.files.map(String)
|
||
: req.body?.file
|
||
? [String(req.body.file)]
|
||
: [];
|
||
const supplierCode = String(req.body?.supplier_code || '').trim();
|
||
// T9:写库前校验报告文件 key 归属(跨分支 key ⇒ 403,不落库)
|
||
await assertOwnedStoragePaths(ctx, 'quality-reports', uploadPathRefs(files));
|
||
if (ctx!.isSupplierAccount) {
|
||
if (!ctx!.supplierCode) {
|
||
return res.status(403).json({
|
||
error: 'supplier_unbound',
|
||
error_description: '账号未绑定供应商,请联系管理员',
|
||
});
|
||
}
|
||
if (supplierCode && supplierCode !== ctx!.supplierCode) {
|
||
return res.status(403).json({
|
||
error: 'forbidden',
|
||
error_description: '只能上传本供应商报告库',
|
||
});
|
||
}
|
||
}
|
||
const data = await uploadLibraryQualityReport({
|
||
supplierCode: ctx!.isSupplierAccount ? String(ctx!.supplierCode) : supplierCode,
|
||
reportDate: req.body?.report_date,
|
||
reportType: req.body?.report_type,
|
||
reportLabel: req.body?.report_label,
|
||
files,
|
||
uploadedBy: req.userId || null,
|
||
sourceParty: ctx!.isSupplierAccount ? 'supplier' : 'library',
|
||
branchCode: ctx?.branchCode || readOperatingBranchCode(req),
|
||
skuCode: req.body?.sku_code,
|
||
productName: req.body?.product_name,
|
||
});
|
||
return res.json({ data: { ...data, validity_label: validityStatusLabel(data.validity_status) } });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '上传质检报告库失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.get('/quality-reports/day-view', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, [...PREP_AMEND_PERMS, 'order_create', 'order_entry']);
|
||
const proto = String(req.headers['x-forwarded-proto'] || req.protocol || 'https');
|
||
const host = String(req.headers['x-forwarded-host'] || req.get('host') || '');
|
||
const supplierCode = String(req.query?.supplier_code || '').trim();
|
||
const deliveryDate = String(req.query?.delivery_date || req.query?.report_date || '').trim();
|
||
if (ctx!.isSupplierAccount) {
|
||
if (!ctx!.supplierCode) {
|
||
return res.status(403).json({
|
||
error: 'supplier_unbound',
|
||
error_description: '账号未绑定供应商,请联系管理员',
|
||
});
|
||
}
|
||
if (supplierCode && supplierCode !== ctx!.supplierCode) {
|
||
return res.status(403).json({ error: 'forbidden', error_description: '只能查看本供应商' });
|
||
}
|
||
}
|
||
const includeVoided =
|
||
req.query?.include_voided === '1' ||
|
||
req.query?.include_voided === 'true' ||
|
||
String(req.query?.include_voided || '').toLowerCase() === 'yes';
|
||
const data = await listReportsForSupplierDay({
|
||
supplierCode: ctx!.isSupplierAccount ? String(ctx!.supplierCode) : supplierCode,
|
||
deliveryDate,
|
||
branchCode: ctx?.branchCode || readOperatingBranchCode(req),
|
||
includeVoided,
|
||
requestHost: host ? `${proto}://${host}` : null,
|
||
limit: req.query?.limit != null ? Number(req.query.limit) : 200,
|
||
});
|
||
return res.json({ data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '加载当日报告失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.get('/quality-reports/day-items', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, [...PREP_AMEND_PERMS, 'order_create', 'order_entry']);
|
||
const supplierCode = String(req.query?.supplier_code || '').trim();
|
||
const deliveryDate = String(req.query?.delivery_date || req.query?.report_date || '').trim();
|
||
if (ctx!.isSupplierAccount) {
|
||
if (!ctx!.supplierCode) {
|
||
return res.status(403).json({
|
||
error: 'supplier_unbound',
|
||
error_description: '账号未绑定供应商,请联系管理员',
|
||
});
|
||
}
|
||
if (supplierCode && supplierCode !== ctx!.supplierCode) {
|
||
return res.status(403).json({ error: 'forbidden', error_description: '只能查看本供应商' });
|
||
}
|
||
}
|
||
const data = await listQualityReportDayItems({
|
||
supplierCode: ctx!.isSupplierAccount ? String(ctx!.supplierCode) : supplierCode,
|
||
deliveryDate,
|
||
branchCode: ctx?.branchCode || readOperatingBranchCode(req),
|
||
});
|
||
return res.json({ data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '加载当日供货商品失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.post('/quality-reports/match-upload', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, [...PREP_AMEND_PERMS]);
|
||
const files = Array.isArray(req.body?.files)
|
||
? req.body.files.map(String)
|
||
: req.body?.file
|
||
? [String(req.body.file)]
|
||
: [];
|
||
const supplierCode = String(req.body?.supplier_code || '').trim();
|
||
if (ctx!.isSupplierAccount) {
|
||
if (!ctx!.supplierCode) {
|
||
return res.status(403).json({
|
||
error: 'supplier_unbound',
|
||
error_description: '账号未绑定供应商,请联系管理员',
|
||
});
|
||
}
|
||
if (supplierCode && supplierCode !== ctx!.supplierCode) {
|
||
return res.status(403).json({
|
||
error: 'forbidden',
|
||
error_description: '只能上传本供应商报告',
|
||
});
|
||
}
|
||
}
|
||
const proto = String(req.headers['x-forwarded-proto'] || req.protocol || 'https');
|
||
const host = String(req.headers['x-forwarded-host'] || req.get('host') || '');
|
||
const data = await matchUploadQualityReports({
|
||
supplierCode: ctx!.isSupplierAccount ? String(ctx!.supplierCode) : supplierCode,
|
||
reportDate: String(req.body?.report_date || req.body?.delivery_date || ''),
|
||
files,
|
||
uploadedBy: req.userId || null,
|
||
branchCode: ctx?.branchCode || readOperatingBranchCode(req),
|
||
requestHost: host ? `${proto}://${host}` : null,
|
||
reportType: req.body?.report_type,
|
||
});
|
||
return res.json({ data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '批量匹配上传失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.patch('/quality-reports/:id/match', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, [...PREP_AMEND_PERMS]);
|
||
const proto = String(req.headers['x-forwarded-proto'] || req.protocol || 'https');
|
||
const host = String(req.headers['x-forwarded-host'] || req.get('host') || '');
|
||
const skuRaw = req.body?.sku_code;
|
||
const skuCodesRaw = req.body?.sku_codes;
|
||
const skuCodes = Array.isArray(skuCodesRaw)
|
||
? skuCodesRaw.map((v: unknown) => String(v || '').trim()).filter(Boolean)
|
||
: undefined;
|
||
const skuCode =
|
||
skuCodes !== undefined
|
||
? undefined
|
||
: skuRaw === null || skuRaw === undefined || String(skuRaw).trim() === ''
|
||
? null
|
||
: String(skuRaw).trim();
|
||
const data = await rematchLibraryQualityReport({
|
||
id: String(req.params.id || ''),
|
||
skuCode,
|
||
skuCodes,
|
||
reportDate: req.body?.report_date != null ? String(req.body.report_date).trim() || null : null,
|
||
branchCode: ctx?.branchCode || readOperatingBranchCode(req),
|
||
requestHost: host ? `${proto}://${host}` : null,
|
||
});
|
||
return res.json({ data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '改挂报告失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.patch('/quality-reports/:id/type', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, [...PREP_AMEND_PERMS]);
|
||
const proto = String(req.headers['x-forwarded-proto'] || req.protocol || 'https');
|
||
const host = String(req.headers['x-forwarded-host'] || req.get('host') || '');
|
||
const reportType = String(req.body?.report_type || '').trim();
|
||
if (!reportType) {
|
||
return res.status(400).json({ error: 'invalid_request', error_description: '缺少 report_type' });
|
||
}
|
||
const data = await updateQualityReportType({
|
||
id: String(req.params.id || ''),
|
||
reportType,
|
||
branchCode: ctx?.branchCode || readOperatingBranchCode(req),
|
||
requestHost: host ? `${proto}://${host}` : null,
|
||
});
|
||
return res.json({ data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '修改报告类型失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.get('/purchase/quality-reports', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, [...PREP_AMEND_PERMS]);
|
||
const purchaseCode = String(req.query?.purchase_code || '').trim();
|
||
const skuCode = String(req.query?.sku_code || '').trim() || null;
|
||
if (!purchaseCode) {
|
||
return res.status(400).json({ error: 'invalid_request', error_description: '缺少 purchase_code' });
|
||
}
|
||
const data = await getActiveQualityReportForPurchase(purchaseCode, skuCode);
|
||
return res.json({
|
||
data: data
|
||
? { ...data, validity_label: validityStatusLabel(data.validity_status) }
|
||
: null,
|
||
});
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '加载自采检验报告失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.post('/purchase/quality-reports', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, [...PREP_AMEND_PERMS]);
|
||
const purchaseCode = String(req.body?.purchase_code || '').trim();
|
||
const files = Array.isArray(req.body?.files)
|
||
? req.body.files.map(String)
|
||
: req.body?.file
|
||
? [String(req.body.file)]
|
||
: [];
|
||
// T9:写库前校验报告文件 key 归属(跨分支 key ⇒ 403,不落库)
|
||
await assertOwnedStoragePaths(ctx, 'quality-reports', uploadPathRefs(files));
|
||
const data = await uploadQualityReport({
|
||
purchaseCode,
|
||
files,
|
||
uploadedBy: req.userId || null,
|
||
sourceParty: 'self_purchase',
|
||
branchCode: ctx?.branchCode || readOperatingBranchCode(req),
|
||
});
|
||
return res.json({ data: { ...data, validity_label: validityStatusLabel(data.validity_status) } });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '上传自采检验报告失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.patch('/quality-reports/:id/validity', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, [...PREP_AMEND_PERMS]);
|
||
const data = await updateQualityReportValidity({
|
||
id: String(req.params.id || ''),
|
||
testedAt: req.body?.tested_at,
|
||
validFrom: req.body?.valid_from,
|
||
validTo: req.body?.valid_to,
|
||
compareAt: req.body?.compare_at,
|
||
});
|
||
return res.json({ data: { ...data, validity_label: validityStatusLabel(data.validity_status) } });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '更新报告有效期失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.patch('/quality-reports/:id/void', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, [...PREP_AMEND_PERMS]);
|
||
const data = await voidQualityReport(String(req.params.id || ''));
|
||
return res.json({ data: { ...data, validity_label: validityStatusLabel(data.validity_status) } });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '作废检验报告失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.post('/purchase/retry-inbound', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage', 'order_manage', 'order_entry']);
|
||
const data = await resetPurchaseAfterQualityReject(String(req.body?.purchase_code || ''), ctx);
|
||
return res.json({ success: true, data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({ error: 'server_error', error_description: error?.message || '重新采购失败' });
|
||
}
|
||
});
|
||
|
||
router.post('/purchase/complete', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage', 'order_manage']);
|
||
const branchCode = resolvePurchaseBranch(ctx, req);
|
||
const data = await completeSelfPurchase({
|
||
purchaseCode: String(req.body?.purchase_code || ''),
|
||
branchCode,
|
||
// 方案 C:完成自采不透传实收数量(实收只由验收写入;直送行由服务端按计划量豁免)
|
||
actualPrice: req.body?.actual_price,
|
||
remark: req.body?.remark,
|
||
itemName: req.body?.item_name,
|
||
categoryCode: req.body?.category_code,
|
||
categoryName: req.body?.category_name,
|
||
unit: req.body?.unit,
|
||
});
|
||
return res.json(data);
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '完成采购失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.post('/purchase/direct-delivery-photo', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage', 'order_manage']);
|
||
const branchCode = resolvePurchaseBranch(ctx, req);
|
||
const extra = Array.isArray(req.body?.extra_purchase_codes)
|
||
? req.body.extra_purchase_codes.map((c: unknown) => String(c || ''))
|
||
: [];
|
||
const data = await appendPurchaseDirectDeliveryPhoto({
|
||
purchaseCode: String(req.body?.purchase_code || ''),
|
||
extraPurchaseCodes: extra,
|
||
branchCode,
|
||
content: String(req.body?.content || ''),
|
||
ext: String(req.body?.ext || 'jpg'),
|
||
});
|
||
return res.json({
|
||
success: true,
|
||
path: data.path,
|
||
photo_url: (await buildDirectDeliveryPhotoUrls(req, [data.path]))[0] || '',
|
||
purchase_codes: data.purchase_codes,
|
||
});
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '上传直送照片失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.post('/purchase/self-process', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const { branchCode } = await resolveSelfPurchaseWriteAccess(req);
|
||
const data = await setPurchaseSelfProcessed({
|
||
purchaseCode: String(req.body?.purchase_code || ''),
|
||
branchCode,
|
||
selfProcessed: Boolean(req.body?.self_processed),
|
||
});
|
||
return res.json({ success: true, data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '设置仓内加工失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.post('/purchase/skip-warehouse-demand', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const { branchCode } = await resolveSelfPurchaseWriteAccess(req);
|
||
const data = await skipWarehouseProcessingPurchase({
|
||
purchaseCode: String(req.body?.purchase_code || ''),
|
||
branchCode,
|
||
});
|
||
return res.json({ success: true, data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '跳过成品自采失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.post('/purchase/self-purchase-stock-inbound', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage', 'order_manage', 'inventory_manage']);
|
||
const branchCode = resolvePurchaseBranch(ctx, req);
|
||
const data = await createSelfPurchaseStockInbound({
|
||
skuCode: req.body?.sku_code,
|
||
skuName: req.body?.sku_name,
|
||
categoryCode: req.body?.category_code,
|
||
unit: req.body?.unit,
|
||
qty: Number(req.body?.qty),
|
||
unitCost: Number(req.body?.unit_cost),
|
||
branchCode,
|
||
remark: req.body?.remark,
|
||
operatorId: req.userId,
|
||
requestId: req.body?.request_id ? String(req.body.request_id) : null,
|
||
});
|
||
return res.json({ success: true, data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '新增自采商品入库失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
// 独立自采入库:修改(允许已消耗批次,但数量不得低于已领用量)
|
||
router.patch('/purchase/self-purchase-stock-inbound/:id', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage', 'order_manage', 'inventory_manage']);
|
||
const branchCode = resolvePurchaseBranch(ctx, req);
|
||
const data = await updateSelfPurchaseStockInbound({
|
||
id: String(req.params.id || ''),
|
||
branchCode,
|
||
qty: Number(req.body?.qty),
|
||
unitCost: Number(req.body?.unit_cost),
|
||
remark: req.body?.remark,
|
||
operatorId: req.userId,
|
||
});
|
||
return res.json({ success: true, data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '修改失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.post(
|
||
'/purchase/self-purchase-stock-inbound/:id/complete',
|
||
authMiddleware,
|
||
async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage', 'order_manage', 'inventory_manage']);
|
||
const branchCode = resolvePurchaseBranch(ctx, req);
|
||
const data = await resubmitSelfPurchaseStockInbound({
|
||
id: String(req.params.id || ''),
|
||
branchCode,
|
||
operatorId: req.userId,
|
||
});
|
||
return res.json({ success: true, data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '完成失败',
|
||
});
|
||
}
|
||
}
|
||
);
|
||
|
||
// 独立自采入库:删除(仅未消耗批次;记录保留 voided_at 审计,列表不再展示)
|
||
router.delete('/purchase/self-purchase-stock-inbound/:id', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage', 'order_manage', 'inventory_manage']);
|
||
const branchCode = resolvePurchaseBranch(ctx, req);
|
||
const data = await voidSelfPurchaseStockInbound({
|
||
id: String(req.params.id || ''),
|
||
branchCode,
|
||
operatorId: req.userId,
|
||
reason: req.body?.reason ? String(req.body.reason) : null,
|
||
});
|
||
return res.json({ success: true, data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '删除失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
// 兼容旧前端:作废即删除
|
||
router.post('/purchase/self-purchase-stock-inbound/:id/void', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage', 'order_manage', 'inventory_manage']);
|
||
const branchCode = resolvePurchaseBranch(ctx, req);
|
||
const data = await voidSelfPurchaseStockInbound({
|
||
id: String(req.params.id || ''),
|
||
branchCode,
|
||
operatorId: req.userId,
|
||
reason: req.body?.reason ? String(req.body.reason) : null,
|
||
});
|
||
return res.json({ success: true, data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '删除失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.patch('/purchase/:purchaseCode/amend-actual', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage', 'order_manage']);
|
||
const branchCode = resolvePurchaseBranch(ctx, req);
|
||
const purchaseCode = String(req.params.purchaseCode || req.body?.purchase_code || '').trim();
|
||
const data = await amendPurchaseActual({
|
||
purchaseCode,
|
||
branchCode,
|
||
// 方案 C(docs/design/20260920-self-purchase-actual-qty-single-writer.md):
|
||
// 自采入口不透传实收数量,实收只由验收写入;本接口只改价格/单位/备注。
|
||
preserveActualQty: true,
|
||
actualPrice: req.body?.actual_price,
|
||
unit: req.body?.unit,
|
||
remark: req.body?.remark,
|
||
operatorId: req.userId,
|
||
});
|
||
return res.json({ success: true, data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '改实采信息失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.patch('/purchase/:purchaseCode/linked-sale-price', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage', 'order_manage', 'order_entry']);
|
||
const branchCode = resolvePurchaseBranch(ctx, req);
|
||
const purchaseCode = String(req.params.purchaseCode || req.body?.purchase_code || '').trim();
|
||
const salePriceRaw = req.body?.sale_price ?? req.body?.price;
|
||
const data = await updatePurchaseLinkedSalePrice({
|
||
purchaseCode,
|
||
branchCode,
|
||
salePrice: salePriceRaw,
|
||
operatorId: req.userId,
|
||
});
|
||
return res.json({ success: true, data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '改销售价失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
/** 备货等无采购单号场景:按订单明细 id 改销售价(写入语义同采购改价) */
|
||
router.patch('/purchase/order-items/:itemId/sale-price', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage', 'order_manage', 'order_entry']);
|
||
const branchCode = resolvePurchaseBranch(ctx, req);
|
||
const data = await updateOrderItemSalePrice({
|
||
orderItemId: String(req.params.itemId || ''),
|
||
branchCode,
|
||
salePrice: req.body?.sale_price ?? req.body?.price,
|
||
operatorId: req.userId,
|
||
});
|
||
return res.json({ success: true, data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '改销售价失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.get('/purchase/assign-suppliers', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
const client = await pool.connect();
|
||
try {
|
||
const { branchCode } = await resolveSelfPurchaseWriteAccess(req);
|
||
const purchaseCode = String(req.query?.purchase_code || '').trim();
|
||
if (!purchaseCode) {
|
||
return res.status(400).json({ error: 'invalid_request', error_description: '缺少 purchase_code' });
|
||
}
|
||
const data = await listAssignableSuppliersForPurchase(client, purchaseCode, branchCode);
|
||
return res.json(data);
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '加载可转供应商失败',
|
||
});
|
||
} finally {
|
||
client.release();
|
||
}
|
||
});
|
||
|
||
router.post('/purchase/assign-supplier', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
const client = await pool.connect();
|
||
try {
|
||
const { branchCode, purchaserLabel } = await resolveSelfPurchaseWriteAccess(req);
|
||
const purchaseCode = String(req.body?.purchase_code || '').trim();
|
||
const supplierCode = String(req.body?.supplier_code || '').trim();
|
||
if (!purchaseCode) {
|
||
return res.status(400).json({ error: 'invalid_request', error_description: '缺少 purchase_code' });
|
||
}
|
||
await client.query('BEGIN');
|
||
const data = await assignPurchaseOrderToSupplier(client, {
|
||
purchaseCode,
|
||
branchCode,
|
||
supplierCode: supplierCode || null,
|
||
purchaserLabel,
|
||
});
|
||
await client.query('COMMIT');
|
||
return res.json({ success: true, data });
|
||
} catch (error: any) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '转供应商失败',
|
||
});
|
||
} finally {
|
||
client.release();
|
||
}
|
||
});
|
||
|
||
router.get('/purchase/purchasers', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, [...PREP_AMEND_PERMS, 'order_create', 'allocation_manage']);
|
||
const branchCode = resolvePurchaseBranch(ctx, req);
|
||
const data = await listBranchPurchasers(pool, branchCode);
|
||
return res.json({ data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '加载采购员失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.get('/purchase-orders/assign-default', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage']);
|
||
const branchCode = resolvePurchaseBranch(ctx, req);
|
||
if (!branchCode) {
|
||
return res.status(400).json({
|
||
error: 'branch_required',
|
||
error_description: '请选择当前操作分公司',
|
||
});
|
||
}
|
||
const data = await getPurchaseAssignDefaultConfig(branchCode);
|
||
return res.json({ data, branch_code: branchCode });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '读取默认分配失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.put('/purchase-orders/assign-default', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage']);
|
||
const branchCode = resolvePurchaseBranch(ctx, req);
|
||
if (!branchCode) {
|
||
return res.status(400).json({
|
||
error: 'branch_required',
|
||
error_description: '请选择当前操作分公司',
|
||
});
|
||
}
|
||
const data = await setPurchaseAssignDefaultConfig(branchCode, {
|
||
mode: req.body?.mode,
|
||
purchaser_code: req.body?.purchaser_code,
|
||
});
|
||
return res.json({ data, branch_code: branchCode });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '保存默认分配失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.get('/purchase-orders/category-purchaser-map', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage']);
|
||
const branchCode = resolvePurchaseBranch(ctx, req);
|
||
if (!branchCode) {
|
||
return res.status(400).json({
|
||
error: 'branch_required',
|
||
error_description: '请选择当前操作分公司',
|
||
});
|
||
}
|
||
const data = await getCategoryPurchaserMap(branchCode);
|
||
return res.json({ data, branch_code: branchCode });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '读取分类采购员绑定失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.put('/purchase-orders/category-purchaser-map', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage']);
|
||
const branchCode = resolvePurchaseBranch(ctx, req);
|
||
if (!branchCode) {
|
||
return res.status(400).json({
|
||
error: 'branch_required',
|
||
error_description: '请选择当前操作分公司',
|
||
});
|
||
}
|
||
const data = await setCategoryPurchaserMap(branchCode, { bindings: req.body?.bindings });
|
||
return res.json({ data, branch_code: branchCode });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '保存分类采购员绑定失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.post('/purchase/assign-purchasers', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
const client = await pool.connect();
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage']);
|
||
const branchCode = resolvePurchaseBranch(ctx, req);
|
||
const mode = normalizeAssignMode(req.body?.mode);
|
||
const purchaseCodes = Array.isArray(req.body?.purchase_codes)
|
||
? req.body.purchase_codes.map((c: unknown) => String(c || '').trim()).filter(Boolean)
|
||
: null;
|
||
await client.query('BEGIN');
|
||
const data = await applyPurchaserAssignment(client, {
|
||
branchCode,
|
||
mode,
|
||
dateField: req.body?.date_field ? String(req.body.date_field) : 'delivery_date',
|
||
dateFrom: req.body?.date_from ? String(req.body.date_from) : null,
|
||
dateTo: req.body?.date_to ? String(req.body.date_to) : null,
|
||
purchaseCodes,
|
||
purchaserCode: req.body?.purchaser_code ? String(req.body.purchaser_code) : null,
|
||
categoryCode: req.body?.category_code ? String(req.body.category_code) : null,
|
||
operatorId: req.userId,
|
||
});
|
||
await client.query('COMMIT');
|
||
return res.json({ success: true, data });
|
||
} catch (error: any) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '分配采购员失败',
|
||
});
|
||
} finally {
|
||
client.release();
|
||
}
|
||
});
|
||
|
||
router.patch('/purchase/:purchaseCode/purchaser', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
const client = await pool.connect();
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage']);
|
||
const branchCode = resolvePurchaseBranch(ctx, req);
|
||
const purchaseCode = String(req.params.purchaseCode || '').trim();
|
||
const purchaserCode = String(req.body?.purchaser_code || '').trim();
|
||
await client.query('BEGIN');
|
||
const data = await reassignSinglePurchasePurchaser(client, {
|
||
branchCode,
|
||
purchaseCode,
|
||
purchaserCode,
|
||
operatorId: req.userId,
|
||
});
|
||
await client.query('COMMIT');
|
||
return res.json({ success: true, data });
|
||
} catch (error: any) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '改挂采购员失败',
|
||
});
|
||
} finally {
|
||
client.release();
|
||
}
|
||
});
|
||
|
||
router.get('/purchase/categories', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage', 'order_manage']);
|
||
const branchCode = resolvePurchaseBranch(ctx, req);
|
||
const rows = await fetchCategoryRows(branchCode);
|
||
const data = rows
|
||
.filter((row) => row.status !== 0)
|
||
.map((row) => ({
|
||
category_code: row.category_code,
|
||
category_name: row.category_name,
|
||
label: getCategoryDisplayLabel(rows, row.category_code) || row.category_name,
|
||
}))
|
||
.sort((a, b) => a.label.localeCompare(b.label, 'zh-CN'));
|
||
return res.json({ data });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '加载分类失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.post('/purchase/categories', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage', 'order_manage']);
|
||
const branchCode = resolvePurchaseBranch(ctx, req);
|
||
const name = String(req.body?.name || '').trim();
|
||
if (!name) {
|
||
return res.status(400).json({ error: 'invalid_request', error_description: '请输入分类名称' });
|
||
}
|
||
const existing = await fetchCategoryRows(branchCode);
|
||
const created = await createQuickCatalogCategory(branchCode, name, existing.length + 1);
|
||
return res.json({
|
||
data: {
|
||
...created,
|
||
parent_code: null,
|
||
level: 1,
|
||
label:
|
||
getCategoryDisplayLabel(
|
||
[
|
||
...existing,
|
||
{
|
||
category_code: created.category_code,
|
||
category_name: created.category_name,
|
||
parent_code: null,
|
||
level: 1,
|
||
sort_order: existing.length + 1,
|
||
loss_threshold: 0,
|
||
is_fresh: true,
|
||
status: 1,
|
||
},
|
||
],
|
||
created.category_code
|
||
) || created.label,
|
||
},
|
||
});
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '创建分类失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.get('/purchase-orders/management-list', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage']);
|
||
const operatingBranchCode = readOperatingBranchCode(req);
|
||
// 列表自愈:仓内加工成品自采单可能因时序漏网(重分配等),web 端也挂 heal
|
||
// (此前只有小程序今日列表触发,web 跳过按钮禁用后无其它入口)
|
||
const healBranch = getEffectiveBranchCode(ctx, operatingBranchCode);
|
||
if (healBranch) {
|
||
const { healOpenWarehouseDemandPurchases, healWarehousePurchaseZeroCosts } = await import(
|
||
'../../../services/processingDemandSheetService'
|
||
);
|
||
await healOpenWarehouseDemandPurchases({ branchCode: healBranch }).catch((err) =>
|
||
console.error('[warehouse-demand] web 列表自愈失败', err)
|
||
);
|
||
await healWarehousePurchaseZeroCosts({ branchCode: healBranch }).catch((err) =>
|
||
console.error('[warehouse-demand] 仓内加工成本清零自愈失败', err)
|
||
);
|
||
}
|
||
const data = await listPurchaseOrdersForManagement(ctx, operatingBranchCode, {
|
||
page: Number(req.query.page) || 1,
|
||
pageSize: Number(req.query.page_size) || 20,
|
||
sortOrder: req.query.sort_order === 'asc' ? 'asc' : 'desc',
|
||
statusGroup: req.query.status_group ? String(req.query.status_group) : 'all',
|
||
dateRangePreset: (req.query.date_range as any) || 'custom',
|
||
dateFrom: req.query.date_from ? String(req.query.date_from) : null,
|
||
dateTo: req.query.date_to ? String(req.query.date_to) : null,
|
||
dateField: req.query.date_field ? String(req.query.date_field) : 'delivery_date',
|
||
sortDay: req.query.sort_day ? String(req.query.sort_day) : 'created_at',
|
||
supplierCode: req.query.supplier_code ? String(req.query.supplier_code) : null,
|
||
sourceType: req.query.source_type ? String(req.query.source_type) : null,
|
||
search: req.query.search ? String(req.query.search) : null,
|
||
category: req.query.category ? String(req.query.category) : null,
|
||
includeCategoryStats:
|
||
String(req.query.include_category_stats || '').trim() === '1',
|
||
});
|
||
return res.json({
|
||
data: data.rows,
|
||
total: data.total,
|
||
stats: data.stats,
|
||
category_stats: data.category_stats,
|
||
});
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '加载采购列表失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
router.get('/purchase-orders/price-invert-risks', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage']);
|
||
const operatingBranchCode = readOperatingBranchCode(req);
|
||
const data = await listPriceInvertRisks(ctx, operatingBranchCode, {
|
||
dateFrom: req.query.date_from ? String(req.query.date_from) : null,
|
||
dateTo: req.query.date_to ? String(req.query.date_to) : null,
|
||
dateField: req.query.date_field ? String(req.query.date_field) : 'delivery_date',
|
||
});
|
||
return res.json({ data: data.rows });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '加载倒挂风险失败',
|
||
});
|
||
}
|
||
});
|
||
|
||
/** 自采页统计专用:不返回详情,避免状态 Tab 的列表请求覆盖卡片计数。 */
|
||
router.get('/purchase-orders/management-counts', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage']);
|
||
const operatingBranchCode = readOperatingBranchCode(req);
|
||
const data = await listPurchaseOrdersForManagement(ctx, operatingBranchCode, {
|
||
page: 1,
|
||
pageSize: 1,
|
||
statusGroup: 'all',
|
||
dateRangePreset: (req.query.date_range as any) || 'custom',
|
||
dateFrom: req.query.date_from ? String(req.query.date_from) : null,
|
||
dateTo: req.query.date_to ? String(req.query.date_to) : null,
|
||
dateField: req.query.date_field ? String(req.query.date_field) : 'delivery_date',
|
||
sourceType: req.query.source_type ? String(req.query.source_type) : null,
|
||
search: req.query.search ? String(req.query.search) : null,
|
||
category: req.query.category ? String(req.query.category) : null,
|
||
statsOnly: true,
|
||
});
|
||
return res.json({ total: data.total, stats: data.stats });
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({ error: error?.code || 'server_error', error_description: error?.message || '加载采购统计失败' });
|
||
}
|
||
});
|
||
|
||
/** 自采总成本:按日期范围全状态合计,不受列表 Tab / 搜索影响 */
|
||
router.get('/purchase-orders/self-purchase-total', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||
try {
|
||
const ctx = await getWorkflowCtx(req);
|
||
requireWorkflowPermission(ctx, ['purchase_manage']);
|
||
const operatingBranchCode = readOperatingBranchCode(req);
|
||
const data = await sumSelfPurchaseTotalAmount(ctx, operatingBranchCode, {
|
||
dateFrom: req.query.date_from ? String(req.query.date_from) : null,
|
||
dateTo: req.query.date_to ? String(req.query.date_to) : null,
|
||
dateField: req.query.date_field ? String(req.query.date_field) : 'created_at',
|
||
dateRangePreset: (req.query.date_range as any) || 'custom',
|
||
search: req.query.search ? String(req.query.search) : null,
|
||
});
|
||
return res.json(data);
|
||
} catch (error: any) {
|
||
return res.status(error?.status || 500).json({
|
||
error: error?.code || 'server_error',
|
||
error_description: error?.message || '加载自采总成本失败',
|
||
});
|
||
}
|
||
});
|
||
}
|