来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
288 lines
9.4 KiB
TypeScript
288 lines
9.4 KiB
TypeScript
import type { PoolClient } from 'pg';
|
|
import { pool } from '../db';
|
|
import { assertBranchAllowsProductCatalog } from './platformBranch';
|
|
|
|
function savepointName(prefix: string): string {
|
|
return `${prefix}_${Math.random().toString(36).slice(2, 10)}`;
|
|
}
|
|
|
|
async function countBySku(client: PoolClient, sql: string, codes: string[]): Promise<number> {
|
|
const sp = savepointName('sp_cnt');
|
|
await client.query(`SAVEPOINT ${sp}`);
|
|
try {
|
|
const r = await client.query(sql, [codes]);
|
|
await client.query(`RELEASE SAVEPOINT ${sp}`);
|
|
return Number(r.rows[0]?.c) || 0;
|
|
} catch (error: any) {
|
|
await client.query(`ROLLBACK TO SAVEPOINT ${sp}`).catch(() => undefined);
|
|
if (error?.code === '42P01' || error?.code === '42703') return 0;
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async function safeDeleteBySku(client: PoolClient, table: string, codes: string[]): Promise<void> {
|
|
const sp = savepointName('sp_del');
|
|
await client.query(`SAVEPOINT ${sp}`);
|
|
try {
|
|
await client.query(`DELETE FROM ${table} WHERE sku_code = ANY($1::text[])`, [codes]);
|
|
await client.query(`RELEASE SAVEPOINT ${sp}`);
|
|
} catch (error: any) {
|
|
await client.query(`ROLLBACK TO SAVEPOINT ${sp}`).catch(() => undefined);
|
|
if (error?.code === '42P01' || error?.code === '42703') return;
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async function assertNoBusinessRefs(client: PoolClient, codes: string[]): Promise<void> {
|
|
const blockers: string[] = [];
|
|
const orderCnt = await countBySku(
|
|
client,
|
|
`SELECT COUNT(*)::int AS c FROM order_items WHERE sku_code = ANY($1::text[])`,
|
|
codes
|
|
);
|
|
if (orderCnt > 0) blockers.push(`订单明细 ${orderCnt} 条`);
|
|
|
|
const prepCnt = await countBySku(
|
|
client,
|
|
`SELECT COUNT(*)::int AS c FROM supplier_preparations WHERE sku_code = ANY($1::text[])`,
|
|
codes
|
|
);
|
|
if (prepCnt > 0) blockers.push(`备货 ${prepCnt} 条`);
|
|
|
|
const purchaseCnt = await countBySku(
|
|
client,
|
|
`SELECT COUNT(*)::int AS c FROM purchase_orders WHERE sku_code = ANY($1::text[])`,
|
|
codes
|
|
);
|
|
if (purchaseCnt > 0) blockers.push(`采购单 ${purchaseCnt} 条`);
|
|
|
|
const inspCnt = await countBySku(
|
|
client,
|
|
`SELECT COUNT(*)::int AS c FROM inspections WHERE sku_code = ANY($1::text[])`,
|
|
codes
|
|
);
|
|
if (inspCnt > 0) blockers.push(`验收 ${inspCnt} 条`);
|
|
|
|
const invCnt = await countBySku(
|
|
client,
|
|
`SELECT COUNT(*)::int AS c FROM inventory
|
|
WHERE sku_code = ANY($1::text[])
|
|
AND (COALESCE(available_qty, 0) > 0 OR COALESCE(quantity, 0) > 0)`,
|
|
codes
|
|
);
|
|
if (invCnt > 0) blockers.push(`库存批次 ${invCnt} 条`);
|
|
|
|
const quoteCnt = await countBySku(
|
|
client,
|
|
`SELECT COUNT(*)::int AS c FROM customer_quote_sheet_items WHERE sku_code = ANY($1::text[])`,
|
|
codes
|
|
);
|
|
if (quoteCnt > 0) blockers.push(`报价明细 ${quoteCnt} 条`);
|
|
|
|
if (blockers.length) {
|
|
throw Object.assign(
|
|
new Error(
|
|
`无法删除:仍被引用(${blockers.join('、')})。请先处理相关单据,或仅删除无业务引用的测试商品。`
|
|
),
|
|
{ status: 409, code: 'product_in_use' }
|
|
);
|
|
}
|
|
}
|
|
|
|
async function cleanupSkuDependents(client: PoolClient, codes: string[]): Promise<void> {
|
|
await safeDeleteBySku(client, 'customer_sku_aliases', codes);
|
|
await safeDeleteBySku(client, 'customer_processing_aliases', codes);
|
|
await safeDeleteBySku(client, 'customer_sku_remarks', codes);
|
|
await safeDeleteBySku(client, 'customer_skus', codes);
|
|
await safeDeleteBySku(client, 'sku_suppliers', codes);
|
|
|
|
const spInv = savepointName('sp_inv0');
|
|
await client.query(`SAVEPOINT ${spInv}`);
|
|
try {
|
|
await client.query(
|
|
`DELETE FROM inventory WHERE sku_code = ANY($1::text[])
|
|
AND COALESCE(available_qty, 0) = 0 AND COALESCE(quantity, 0) = 0`,
|
|
[codes]
|
|
);
|
|
await client.query(`RELEASE SAVEPOINT ${spInv}`);
|
|
} catch (error: any) {
|
|
await client.query(`ROLLBACK TO SAVEPOINT ${spInv}`).catch(() => undefined);
|
|
if (error?.code !== '42P01' && error?.code !== '42703') throw error;
|
|
}
|
|
await safeDeleteBySku(client, 'inventory_logs', codes);
|
|
}
|
|
|
|
export type OrphanSkuRow = {
|
|
sku_code: string;
|
|
sku_name: string;
|
|
category_code: string | null;
|
|
unit: string | null;
|
|
spec: string | null;
|
|
barcode: string | null;
|
|
image_url: string | null;
|
|
default_loss_threshold: number | null;
|
|
is_prepackaged: boolean | null;
|
|
brand: string | null;
|
|
tax_code: string | null;
|
|
tax_rate: number | null;
|
|
origin: string | null;
|
|
unit_weight: number | null;
|
|
status: number | null;
|
|
created_at: string | null;
|
|
branch_code: string | null;
|
|
};
|
|
|
|
/** 无 product_catalog 行、且 skus.branch_code 为空或等于当前分公司的孤儿商品 */
|
|
export async function listOrphanSkus(branchCode: string): Promise<OrphanSkuRow[]> {
|
|
const branch = String(branchCode || '').trim();
|
|
if (!branch) {
|
|
throw Object.assign(new Error('请选择当前操作分公司'), { status: 400 });
|
|
}
|
|
assertBranchAllowsProductCatalog(branch);
|
|
|
|
const r = await pool.query(
|
|
`SELECT
|
|
s.sku_code, s.sku_name, s.category_code, s.unit, s.spec, s.barcode, s.image_url,
|
|
s.default_loss_threshold, s.is_prepackaged, s.brand, s.tax_code, s.tax_rate,
|
|
s.status, s.created_at, s.branch_code
|
|
FROM skus s
|
|
WHERE NOT EXISTS (
|
|
SELECT 1 FROM product_catalog pc
|
|
WHERE pc.item_type = 'product' AND pc.code = s.sku_code
|
|
)
|
|
AND (
|
|
s.branch_code IS NULL
|
|
OR TRIM(s.branch_code) = ''
|
|
OR s.branch_code = $1
|
|
)
|
|
ORDER BY s.created_at DESC NULLS LAST
|
|
LIMIT 500`,
|
|
[branch]
|
|
);
|
|
return r.rows.map((row) => ({
|
|
...row,
|
|
origin: null,
|
|
unit_weight: null,
|
|
})) as OrphanSkuRow[];
|
|
}
|
|
|
|
/**
|
|
* 商品真删除:删 product_catalog(触发器同步删 skus);
|
|
* 仅 skus 残留时走孤儿路径直接删 skus。
|
|
* 有履约/库存/报价等引用时拒绝。
|
|
*/
|
|
export async function deleteCatalogProducts(
|
|
productCodes: string[],
|
|
branchCode: string
|
|
): Promise<{ deleted: number; orphan_deleted?: number }> {
|
|
const codes = [...new Set(productCodes.map((c) => String(c || '').trim()).filter(Boolean))];
|
|
if (!codes.length) return { deleted: 0 };
|
|
|
|
const branch = String(branchCode || '').trim();
|
|
if (!branch) {
|
|
throw Object.assign(new Error('请选择当前操作分公司'), { status: 400 });
|
|
}
|
|
assertBranchAllowsProductCatalog(branch);
|
|
|
|
const client = await pool.connect();
|
|
try {
|
|
await client.query('BEGIN');
|
|
|
|
const catalogFound = await client.query(
|
|
`SELECT code, name, branch_code, status
|
|
FROM product_catalog
|
|
WHERE item_type = 'product'
|
|
AND code = ANY($1::text[])`,
|
|
[codes]
|
|
);
|
|
const catalogByCode = new Map(
|
|
catalogFound.rows.map((row) => [String(row.code), row as { code: string; branch_code: string | null }])
|
|
);
|
|
|
|
const skuFound = await client.query(
|
|
`SELECT sku_code, branch_code FROM skus WHERE sku_code = ANY($1::text[])`,
|
|
[codes]
|
|
);
|
|
const skuByCode = new Map(
|
|
skuFound.rows.map((row) => [String(row.sku_code), row as { sku_code: string; branch_code: string | null }])
|
|
);
|
|
|
|
const catalogCodes: string[] = [];
|
|
const orphanCodes: string[] = [];
|
|
|
|
for (const code of codes) {
|
|
const cat = catalogByCode.get(code);
|
|
if (cat) {
|
|
const catBranch = String(cat.branch_code || '').trim();
|
|
if (catBranch && catBranch !== branch) {
|
|
throw Object.assign(
|
|
new Error(`商品 ${code} 属于分公司 ${catBranch},当前分公司 ${branch} 不可删除`),
|
|
{ status: 409, code: 'product_other_branch' }
|
|
);
|
|
}
|
|
catalogCodes.push(code);
|
|
continue;
|
|
}
|
|
if (skuByCode.has(code)) {
|
|
orphanCodes.push(code);
|
|
continue;
|
|
}
|
|
throw Object.assign(new Error(`商品 ${code} 在当前分公司不存在或已删除`), {
|
|
status: 404,
|
|
});
|
|
}
|
|
|
|
const allCodes = [...catalogCodes, ...orphanCodes];
|
|
await assertNoBusinessRefs(client, allCodes);
|
|
await cleanupSkuDependents(client, allCodes);
|
|
|
|
let deleted = 0;
|
|
if (catalogCodes.length) {
|
|
const del = await client.query(
|
|
`DELETE FROM product_catalog
|
|
WHERE item_type = 'product'
|
|
AND code = ANY($2::text[])
|
|
AND (
|
|
branch_code = $1
|
|
OR branch_code IS NULL
|
|
OR TRIM(branch_code) = ''
|
|
)
|
|
RETURNING code`,
|
|
[branch, catalogCodes]
|
|
);
|
|
deleted += del.rowCount || 0;
|
|
}
|
|
|
|
let orphanDeleted = 0;
|
|
if (orphanCodes.length) {
|
|
const delSku = await client.query(
|
|
`DELETE FROM skus WHERE sku_code = ANY($1::text[]) RETURNING sku_code`,
|
|
[orphanCodes]
|
|
);
|
|
orphanDeleted = delSku.rowCount || 0;
|
|
deleted += orphanDeleted;
|
|
}
|
|
|
|
await client.query('COMMIT');
|
|
return { deleted, orphan_deleted: orphanDeleted };
|
|
} catch (error) {
|
|
await client.query('ROLLBACK').catch(() => undefined);
|
|
const msg = String((error as Error)?.message || error);
|
|
if (/23503|foreign key/i.test(msg)) {
|
|
throw Object.assign(
|
|
new Error('无法删除:仍被其他业务表引用。请清空相关单据后再删,或联系管理员检查外键。'),
|
|
{ status: 409, code: 'product_fk_block' }
|
|
);
|
|
}
|
|
if (/current transaction is aborted/i.test(msg)) {
|
|
throw Object.assign(
|
|
new Error('删除失败:请刷新后重试。若仍失败,可能仍有业务单据引用该商品。'),
|
|
{ status: 409, code: 'product_delete_aborted' }
|
|
);
|
|
}
|
|
throw error;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|