Revert "feat(库存): 「删除批次」改为物理删除 inventory 行(留操作日志、保留流水;仍被未完结订单占用时 409 拒绝)"
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s

This reverts commit 5fe80d572d.
This commit is contained in:
Ubuntu
2026-10-20 22:04:36 +08:00
parent 5fe80d572d
commit ee6d691f1f
5 changed files with 8 additions and 111 deletions
@@ -479,28 +479,6 @@ export function mountInventoryWorkflowRoutes(router: Router): void {
}
});
/**
* **物理删除库存批次**(2026-10-20 裁定):真删 inventory 行,留操作日志;流水保留;
* 仍被未完结订单引用时拒绝(409 batch_in_use)。
*/
router.post('/inventory/batches/:id/delete', authMiddleware, async (req: AuthRequest, res) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['inventory_manage']);
const { deleteInventoryBatch } = await import('../../../services/inventoryBatchEditService');
const data = await deleteInventoryBatch({
branchCode: String(req.body?.branch_code || ctx?.branchCode || ''),
inventoryId: String(req.params.id || ''),
operatorId: ctx?.userId || null,
operatorRole: (ctx as any)?.roleCode || null,
});
return res.json({ data });
} catch (error: any) {
const status = Number(error?.status) || 400;
return res.status(status).json({ error: error?.code || 'server_error', error_description: error?.message });
}
});
router.delete('/inventory/batch-reports/:id', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
@@ -16,7 +16,6 @@
*/
import { pool } from '../db';
import { writeAuditLog } from './auditService';
import { runWithTenantDbContext } from './tenantDbContext';
import { deriveExpiryDate } from '../utils/shelfLife';
function trimText(v: unknown): string {
@@ -414,78 +413,3 @@ export async function updateInventoryBatchAttributes(
client.release();
}
}
/**
* **物理删除库存批次**(2026-10-20 开发者裁定):
* 之前前端「删除」只是把 available_qty 改 0(软删),现在改为**真删行**,但必须留下操作日志。
*
* 安全前置(不破坏在用数据):
* · 该批次若仍被【未删除且未完结(<90)】订单引用(cover_batches / 出库批次),拒绝删除;
* · `inventory_logs`(出入库流水)**保留**,不级联删除,用于追溯。
*/
export async function deleteInventoryBatch(input: {
branchCode?: string | null;
inventoryId: string;
operatorId?: string | null;
operatorRole?: string | null;
}): Promise<{ deleted: boolean; batch_no: string | null; active_refs: number }> {
const inventoryId = String(input.inventoryId || '').trim();
if (!inventoryId) throw Object.assign(new Error('缺少库存批次 id'), { status: 400, code: 'invalid_request' });
const branch = String(input.branchCode || '').trim();
return runWithTenantDbContext(branch, async () => {
const before = await pool.query<{
id: string;
sku_code: string | null;
batch_no: string | null;
quantity: string | number | null;
available_qty: string | number | null;
}>(
`SELECT id, sku_code, batch_no, quantity, available_qty FROM inventory WHERE id = $1 LIMIT 1`,
[inventoryId]
);
if (!before.rowCount) throw Object.assign(new Error('库存批次不存在'), { status: 404, code: 'not_found' });
const row = before.rows[0];
// 仍被活订单引用 ⇒ 拒绝(避免删掉要发货的货)
const refs = await pool.query<{ n: string }>(
`SELECT count(*)::int AS n
FROM order_item_fulfillments f
JOIN order_items oi ON oi.id = f.order_item_id
JOIN orders o ON o.order_code = oi.order_code
WHERE COALESCE(f.inventory_cover_qty, 0) > 0
AND o.deleted_at IS NULL
AND COALESCE(o.order_status, 0) < 90
AND oi.cover_batches::text LIKE '%' || $1 || '%'`,
[String(row.batch_no || '')]
);
const activeRefs = Number(refs.rows[0]?.n || 0);
if (activeRefs > 0) {
throw Object.assign(
new Error(`该批次仍被 ${activeRefs} 张未完结订单占用,请先完成配送或取消抵扣后再删除`),
{ status: 409, code: 'batch_in_use' }
);
}
await pool.query(`DELETE FROM inventory WHERE id = $1`, [inventoryId]);
try {
await writeAuditLog({
operatorId: input.operatorId || null,
operatorRole: input.operatorRole || null,
operationType: 'inventory_batch_delete',
targetTable: 'inventory',
targetId: inventoryId,
oldValue: {
sku_code: row.sku_code,
batch_no: row.batch_no,
quantity: row.quantity,
available_qty: row.available_qty,
},
newValue: { deleted: true, branch_code: branch || null },
actionCategory: 'inventory',
});
} catch (error) {
console.error('[inventoryBatchDelete] writeAuditLog failed:', (error as Error)?.message || error);
}
return { deleted: true, batch_no: row.batch_no, active_refs: activeRefs };
});
}
+2 -2
View File
@@ -130,9 +130,9 @@ export const inventory: MessageDict = {
'void.title': '删除库存批次',
'void.bodyOne':
'将物理删除该库存批次(真删,不是清空库存)。出入库流水保留,删除会写入操作日志;仍被未完结订单占用的批次会被拒绝。',
'将本批次可用改为 0,默认列表不再显示。不物理删库,流水保留。请勿把真实在库批次一并删掉。',
'void.bodyMany':
'将物理删除当前页 {n} 条批次(不含其它页)。流水保留、写入操作日志;被未完结订单占用的批次会被拒绝。',
'将删除当前页 {n} 条批次(不含其它页)。可用改为 0 后默认列表不再显示,流水保留。',
'void.product': '商品',
'void.batch': '批次',
'void.currentAvailable': '当前可用 {qty}',
+6 -3
View File
@@ -50,7 +50,6 @@ import {
listInboundHoldingCostsApi,
} from '../../utils/workflowApi';
import {
deleteInventoryBatchApi,
fetchInventoryBatchReportsByInventoryApi,
deleteInventoryBatchReportApi,
} from '../../utils/workflowApi';
@@ -471,8 +470,12 @@ export const InventoryManagement: React.FC = () => {
const item = targets[i];
setVoidProgress(`${i + 1}/${targets.length}`);
try {
// 2026-10-20:改为**物理删除批次**(留审计日志;被活订单占用时后端拒绝并给出原因)
await deleteInventoryBatchApi(item.id, branch);
await adjustInventoryAvailableApi({
inventoryId: item.id,
availableQty: 0,
remark: INVENTORY_VOID_REMARK,
operatingBranchCode: branch,
});
ok += 1;
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : t('inventory.toast.deleteFail');
-8
View File
@@ -7354,11 +7354,3 @@ export async function confirmReturnQualityApi(returnCode: string, qualified: boo
{ method: 'POST', body: JSON.stringify({ qualified }) }
).then((r) => r.data);
}
/** 物理删除库存批次(真删行,留审计日志;被活订单占用时后端返回 409) */
export async function deleteInventoryBatchApi(inventoryId: string, operatingBranchCode?: string | null) {
return workflowFetch<{ data: { deleted: boolean; batch_no: string | null } }>(
`/inventory/batches/${encodeURIComponent(inventoryId)}/delete`,
{ method: 'POST', body: JSON.stringify({ branch_code: operatingBranchCode || undefined }) }
).then((r) => r.data);
}