Files
SupplierSystem/server/src/services/customerDeleteService.ts
T
Ubuntu 5fa2bbfd55
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
fix(audit-20261019): T1-T9 审计修复、存储归属与审计日志列宽
- 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 超长修复
2026-10-19 16:16:51 +08:00

112 lines
4.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { pool } from '../db';
import type { TenantContext } from './tenantScope';
import { invalidateQueryCacheForTable } from './queryCacheService';
async function deletePortalAuthUsers(client: import('pg').PoolClient, userIds: string[]) {
for (const userId of userIds) {
const otherBindings = await client.query(
`SELECT 1 FROM supplier_users WHERE user_id = $1
UNION ALL SELECT 1 FROM purchaser_users WHERE user_id = $1
UNION ALL SELECT 1 FROM delivery_person_users WHERE user_id = $1
UNION ALL SELECT 1 FROM customer_portal_users WHERE user_id = $1
LIMIT 1`,
[userId]
);
if (otherBindings.rowCount) continue;
await client.query(`DELETE FROM user_roles WHERE user_id = $1`, [userId]);
await client.query(`DELETE FROM profiles WHERE id = $1`, [userId]);
await client.query(`DELETE FROM auth.users WHERE id = $1`, [userId]);
}
}
export async function deleteCustomer(customerCode: string, ctx?: TenantContext | null) {
const code = String(customerCode || '').trim();
if (!code) {
throw Object.assign(new Error('客户编码无效'), { status: 400 });
}
const customer = await pool.query(
`SELECT customer_code, company_name, branch_code FROM customers WHERE customer_code = $1 LIMIT 1`,
[code]
);
if (!customer.rowCount) {
throw Object.assign(new Error('客户不存在'), { status: 404 });
}
const row = customer.rows[0];
if (ctx?.branchCode && !ctx.isSuperAdmin && row.branch_code !== ctx.branchCode) {
throw Object.assign(new Error('无权删除该分公司客户'), { status: 403 });
}
const orderCount = await pool.query(`SELECT COUNT(*)::int AS cnt FROM orders WHERE customer_code = $1`, [code]);
if ((orderCount.rows[0]?.cnt || 0) > 0) {
throw Object.assign(new Error('该客户存在历史订单,无法删除'), { status: 400 });
}
/**
* 报价单引用也不能硬删(2026-10-18 反向核对):
* 旧实现只拦订单,解绑/改绑时 `deleteCustomer` 会把 `customer_quote_sheet_customers`、
* `customer_quote_versions` 一起级联删掉(报价单本体还在,却失去客户归属、版本历史不可恢复)。
* 有引用 ⇒ 返回 400,让调用方(绑定解绑)退化为「停用 status=40」。
*/
const quoteRefCount = await pool.query<{ cnt: number }>(
`SELECT (
(SELECT COUNT(*)::int FROM customer_quote_sheet_customers WHERE customer_code = $1) +
(SELECT COUNT(*)::int FROM customer_quote_versions WHERE customer_code = $1)
)::int AS cnt`,
[code]
);
if ((quoteRefCount.rows[0]?.cnt || 0) > 0) {
throw Object.assign(new Error('该客户存在报价单引用,无法删除(可停用)'), { status: 400 });
}
const client = await pool.connect();
try {
await client.query('BEGIN');
const portalUsers = await client.query(`SELECT user_id FROM customer_portal_users WHERE customer_code = $1`, [code]);
const portalUserIds = portalUsers.rows.map((r) => String(r.user_id));
const tables = [
'alias_recognition_logs',
'customer_alias_stats',
'customer_quote_sheet_customers',
'customer_quote_versions',
'customer_processing_aliases',
'customer_sku_aliases',
'customer_skus',
'customer_recipients',
'customer_portal_users',
'customer_delivery_assignments',
// 客户×商品的常用备注库:删商品侧已由 productDeleteService.cleanupSkuDependents
// 清理,客户侧原先遗漏 → 补齐,避免删客户后遗留孤儿备注(同 customer_code 重建会"复活")
'customer_sku_remarks',
// 商品直送名单:删商品侧由 skuDirectDelivery 按 sku_code 清理,客户侧原先遗漏
'sku_direct_delivery_customers',
];
for (const table of tables) {
await client.query(`DELETE FROM ${table} WHERE customer_code = $1`, [code]);
}
const statements = await client.query(`SELECT statement_no FROM customer_statements WHERE customer_code = $1`, [code]);
for (const stmt of statements.rows) {
const statementNo = String(stmt.statement_no);
await client.query(`DELETE FROM statement_disputes WHERE statement_no = $1`, [statementNo]);
await client.query(`DELETE FROM statement_lines WHERE statement_no = $1`, [statementNo]);
}
await client.query(`DELETE FROM customer_statements WHERE customer_code = $1`, [code]);
await client.query(`DELETE FROM customers WHERE customer_code = $1`, [code]);
await deletePortalAuthUsers(client, portalUserIds);
await client.query('COMMIT');
await invalidateQueryCacheForTable('customers');
return { customer_code: code, company_name: row.company_name };
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
}