feat(商城管理): 客户商品库后台一期

新增 /customers/mall 卡片管理、Excel 导入、上下架/描述/收藏/移出;复用客户销售价接口;修复共享报价单并发改价、i18n、迁移空 schema、并发计数。
This commit is contained in:
Ubuntu
2026-10-28 20:23:43 +08:00
parent 415e5a58c0
commit 94de4e60de
21 changed files with 2230 additions and 19 deletions
@@ -11,6 +11,15 @@ import { getWorkflowCtx, requireWorkflowPermission } from '../context';
import { getEffectiveBranchCode, readOperatingBranchCode } from '../../../services/tenantScope';
import { requireAdminRole } from '../context';
import { getGeoProvider, isValidLatLng } from '../../../services/geoProvider';
import {
listMallLibrary,
searchMallCatalog,
addMallLibrarySkus,
updateMallLibraryItem,
removeMallLibrarySku,
previewMallLibraryImport,
importMallLibraryRows,
} from '../../../services/customerMallAdminService';
/** 客户模块 workflow API */
export function mountCustomerWorkflowRoutes(router: Router): void {
@@ -193,4 +202,135 @@ router.delete('/customers/:customerCode', authMiddleware, async (req: AuthReques
return res.status(error?.status || 400).json({ error: 'server_error', error_description: error?.message });
}
});
router.get('/customers/:customerCode/mall-products', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['customer_manage']);
const data = await listMallLibrary(String(req.params.customerCode || ''));
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('/customers/:customerCode/mall-catalog', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['customer_manage']);
const data = await searchMallCatalog({
customerCode: String(req.params.customerCode || ''),
q: req.query?.q ? String(req.query.q) : null,
limit: req.query?.limit ? Number(req.query.limit) : undefined,
});
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('/customers/:customerCode/mall-products', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['customer_manage']);
const data = await addMallLibrarySkus({
customerCode: String(req.params.customerCode || ''),
skuCodes: req.body?.sku_codes,
operatorId: req.userId || null,
ipAddress: req.ip || null,
});
return res.json({ data });
} catch (error: any) {
return res.status(error?.status || 400).json({
error: error?.code || 'server_error',
error_description: error?.message || '添加商品失败',
});
}
});
router.patch(
'/customers/:customerCode/mall-products/:skuCode',
authMiddleware,
async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['customer_manage']);
const data = await updateMallLibraryItem({
customerCode: String(req.params.customerCode || ''),
skuCode: String(req.params.skuCode || ''),
customerSkuName: req.body?.customer_sku_name,
customerUnit: req.body?.customer_unit,
customerDescription: req.body?.description,
isFavorite: req.body?.is_favorite,
isListed: req.body?.is_listed,
operatorId: req.userId || null,
ipAddress: req.ip || null,
});
return res.json({ data });
} catch (error: any) {
return res.status(error?.status || 400).json({
error: error?.code || 'server_error',
error_description: error?.message || '保存商品失败',
});
}
}
);
router.delete(
'/customers/:customerCode/mall-products/:skuCode',
authMiddleware,
async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['customer_manage']);
const data = await removeMallLibrarySku({
customerCode: String(req.params.customerCode || ''),
skuCode: String(req.params.skuCode || ''),
operatorId: req.userId || null,
ipAddress: req.ip || null,
});
return res.json({ data });
} catch (error: any) {
return res.status(error?.status || 400).json({
error: error?.code || 'server_error',
error_description: error?.message || '移出商品失败',
});
}
}
);
router.post(
'/customers/:customerCode/mall-products/import',
authMiddleware,
async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['customer_manage']);
const dryRun = req.body?.dry_run === true;
const data = dryRun
? await previewMallLibraryImport({
customerCode: String(req.params.customerCode || ''),
rows: req.body?.rows,
})
: await importMallLibraryRows({
customerCode: String(req.params.customerCode || ''),
rows: req.body?.rows,
operatorId: req.userId || null,
ipAddress: req.ip || null,
});
return res.json({ data });
} catch (error: any) {
return res.status(error?.status || 400).json({
error: error?.code || 'server_error',
error_description: error?.message || '导入商品失败',
});
}
}
);
}
@@ -0,0 +1,728 @@
import { pool } from '../db';
import type { TenantContext } from './tenantScope';
import { enrichOrderItemsWithPrices } from './orderPricingService';
import { writeAuditLog } from './auditService';
/**
* 商城管理(客户商品库)—— 见 docs/design/20261029-customer-mall-management.md
*
* 只读写既有 `customer_skus` + `skus` + `categories`:
* **不新建表、不加列、不写价格来源**。商城与录单共用同一份客户商品库,
* 本服务只是给它一个 Web 管理面。
*/
const MAX_ADD_SKUS = 200;
const MAX_IMPORT_ROWS = 2000;
const MAX_ERRORS = 20;
export type MallLibraryStatus = 'orderable' | 'missing_price' | 'sku_disabled' | 'sku_missing';
export type MallLibraryItem = {
sku_code: string;
display_name: string;
catalog_name: string | null;
spec: string | null;
unit: string;
catalog_unit: string | null;
description: string | null;
sale_price: number | null;
mall_price: number;
price_source: string | null;
/** 该客户执行中报价单含此 SKU。改价会写报价单(与 price_source 不是同一件事)。 */
on_quote_sheet: boolean;
category_code: string | null;
category_name: string | null;
is_favorite: boolean;
is_listed: boolean;
usage_count: number;
last_order_at: string | null;
sku_status: number | null;
image_url: string | null;
status: MallLibraryStatus;
};
type CustomerRow = {
customer_code: string;
company_name: string;
branch_code: string | null;
status: number;
};
function badRequest(message: string, code = 'invalid_request'): Error {
const error: any = new Error(message);
error.status = 400;
error.code = code;
return error;
}
function notFound(message: string, code = 'not_found'): Error {
const error: any = new Error(message);
error.status = 404;
error.code = code;
return error;
}
async function loadCustomer(customerCode: string): Promise<CustomerRow> {
const code = String(customerCode || '').trim();
if (!code) throw badRequest('缺少客户编码');
const result = await pool.query(
`SELECT customer_code, company_name, branch_code, status
FROM customers WHERE customer_code = $1 LIMIT 1`,
[code]
);
const row = result.rows[0];
if (!row) throw notFound('客户不存在');
return {
customer_code: String(row.customer_code),
company_name: String(row.company_name || ''),
branch_code: row.branch_code == null ? null : String(row.branch_code),
status: Number(row.status) || 0,
};
}
function normalizeSkuCodes(raw: unknown): string[] {
const list = Array.isArray(raw) ? raw : [];
const codes = [...new Set(list.map((v) => String(v ?? '').trim()).filter(Boolean))];
if (!codes.length) throw badRequest('请选择要添加的商品');
if (codes.length > MAX_ADD_SKUS) {
throw badRequest(`单次最多添加 ${MAX_ADD_SKUS} 个商品`);
}
return codes;
}
/**
* 客户商品库 + 商城展示价。
*
* 显示名 / 单位 / 分类 的优先级与商城 `listMallProducts` 逐字一致;
* 价格走同一个 `enrichOrderItemsWithPrices`,保证后台与客户看到的是同一套价格。
*/
export async function listMallLibrary(customerCode: string): Promise<{
customer: { customer_code: string; company_name: string; branch_code: string | null };
items: MallLibraryItem[];
summary: Record<MallLibraryStatus, number> & { total: number };
}> {
const customer = await loadCustomer(customerCode);
const result = await pool.query(
`SELECT cs.sku_code,
COALESCE(NULLIF(TRIM(cs.customer_sku_name), ''), NULLIF(TRIM(s.sku_name), ''), cs.sku_code) AS display_name,
NULLIF(TRIM(s.sku_name), '') AS catalog_name,
s.spec,
COALESCE(NULLIF(TRIM(cs.customer_unit), ''), NULLIF(TRIM(s.unit), ''), '斤') AS unit,
NULLIF(TRIM(s.unit), '') AS catalog_unit,
NULLIF(TRIM(cs.description), '') AS description,
CASE WHEN COALESCE(cs.sale_price, 0) > 0 THEN cs.sale_price::float8 END AS sale_price,
COALESCE(NULLIF(TRIM(cs.category_code), ''), s.category_code) AS category_code,
cat.category_name,
COALESCE(cs.is_favorite, false) AS is_favorite,
COALESCE(cs.is_listed, true) AS is_listed,
COALESCE(cs.usage_count, 0) AS usage_count,
cs.last_order_at,
s.status AS sku_status,
NULLIF(TRIM(s.image_url), '') AS image_url
FROM customer_skus cs
LEFT JOIN skus s ON s.sku_code = cs.sku_code
LEFT JOIN categories cat
ON cat.category_code = COALESCE(NULLIF(TRIM(cs.category_code), ''), s.category_code)
WHERE cs.customer_code = $1
ORDER BY COALESCE(cs.is_favorite, false) DESC,
COALESCE(cs.usage_count, 0) DESC,
display_name ASC`,
[customer.customer_code]
);
const rows = result.rows;
const skuCodes = rows.map((row) => String(row.sku_code));
const priced = rows.length
? await enrichOrderItemsWithPrices(
customer.customer_code,
rows.map((row) => ({
sku_code: String(row.sku_code),
item_name: String(row.display_name || ''),
quantity: 1,
unit: String(row.unit || '斤'),
price: 0,
})),
customer.branch_code
)
: [];
// 与改价分支同一谓词:执行中、已审批、未过期的报价单里有这一行,哪怕报价是 0。
const quoteParams: unknown[] = [customer.customer_code, skuCodes];
let quoteBranchFilter = '';
if (customer.branch_code) {
quoteParams.push(customer.branch_code);
quoteBranchFilter = `AND (qs.branch_code IS NULL OR qs.branch_code = $${quoteParams.length})`;
}
const quoteHit = rows.length
? await pool.query(
`SELECT DISTINCT i.sku_code
FROM customer_quote_sheet_items i
INNER JOIN customer_quote_sheets qs ON qs.quote_sheet_code = i.quote_sheet_code
INNER JOIN customer_quote_sheet_customers qsc
ON qsc.quote_sheet_code = qs.quote_sheet_code
WHERE qsc.customer_code = $1
AND i.sku_code = ANY($2::text[])
AND qs.status = 1
AND qs.approval_status = 30
AND (qs.expires_at IS NULL OR qs.expires_at > NOW())
${quoteBranchFilter}`,
quoteParams
)
: { rows: [] as { sku_code?: string }[] };
const onQuoteSheet = new Set(
quoteHit.rows.map((row) => String(row.sku_code || '').trim()).filter(Boolean)
);
const summary: Record<MallLibraryStatus, number> & { total: number } = {
total: rows.length,
orderable: 0,
missing_price: 0,
sku_disabled: 0,
sku_missing: 0,
};
const items: MallLibraryItem[] = rows.map((row, index) => {
const pricedRow = priced[index] as
| ({ price?: number; price_source?: string | null } & Record<string, unknown>)
| undefined;
const mallPrice = Math.max(0, Number(pricedRow?.price) || 0);
const skuStatus = row.sku_status == null ? null : Number(row.sku_status);
let status: MallLibraryStatus = 'orderable';
if (skuStatus == null) status = 'sku_missing';
else if (skuStatus !== 1) status = 'sku_disabled';
else if (!(mallPrice > 0)) status = 'missing_price';
summary[status] += 1;
return {
sku_code: String(row.sku_code),
display_name: String(row.display_name || ''),
catalog_name: row.catalog_name == null ? null : String(row.catalog_name),
spec: row.spec == null ? null : String(row.spec),
unit: String(row.unit || '斤'),
catalog_unit: row.catalog_unit == null ? null : String(row.catalog_unit),
description: row.description == null ? null : String(row.description),
sale_price: row.sale_price == null ? null : Number(row.sale_price),
mall_price: mallPrice,
price_source: pricedRow?.price_source ? String(pricedRow.price_source) : null,
on_quote_sheet: onQuoteSheet.has(String(row.sku_code || '').trim()),
category_code: row.category_code == null ? null : String(row.category_code),
category_name: row.category_name == null ? null : String(row.category_name),
is_favorite: row.is_favorite === true,
is_listed: row.is_listed !== false,
usage_count: Number(row.usage_count) || 0,
last_order_at: row.last_order_at ? String(row.last_order_at) : null,
sku_status: skuStatus,
image_url: row.image_url == null ? null : String(row.image_url),
status,
};
});
return {
customer: {
customer_code: customer.customer_code,
company_name: customer.company_name,
branch_code: customer.branch_code,
},
items,
summary,
};
}
/** 可添加的商品档案:本分公司启用、且尚未在该客户商品库中 */
export async function searchMallCatalog(input: {
customerCode: string;
q?: string | null;
limit?: number;
}): Promise<Array<Record<string, unknown>>> {
const customer = await loadCustomer(input.customerCode);
const q = String(input.q || '').trim().slice(0, 50);
const limit = Math.min(Math.max(Number(input.limit) || 30, 1), 50);
const result = await pool.query(
`SELECT s.sku_code, s.sku_name, s.spec, s.unit, s.category_code,
cat.category_name, NULLIF(TRIM(s.image_url), '') AS image_url
FROM skus s
LEFT JOIN categories cat ON cat.category_code = s.category_code
WHERE COALESCE(s.status, 1) = 1
AND ($4::text IS NULL OR s.branch_code IS NULL OR s.branch_code = $4)
AND NOT EXISTS (
SELECT 1 FROM customer_skus cs
WHERE cs.customer_code = $1 AND cs.sku_code = s.sku_code
)
AND ($2 = '' OR s.sku_name ILIKE '%' || $2 || '%' OR s.sku_code ILIKE '%' || $2 || '%')
ORDER BY s.sku_name ASC
LIMIT $3`,
[customer.customer_code, q, limit, customer.branch_code]
);
return result.rows.map((row) => ({
sku_code: String(row.sku_code),
sku_name: String(row.sku_name || ''),
spec: row.spec == null ? null : String(row.spec),
unit: row.unit == null ? null : String(row.unit),
category_code: row.category_code == null ? null : String(row.category_code),
category_name: row.category_name == null ? null : String(row.category_name),
image_url: row.image_url == null ? null : String(row.image_url),
}));
}
/** 批量加入客户商品库(已在库的跳过,不覆盖人工维护的展示名/单位) */
export async function addMallLibrarySkus(input: {
customerCode: string;
skuCodes: unknown;
operatorId?: string | null;
ipAddress?: string | null;
}): Promise<{ added: number; skipped: number; unknown: string[] }> {
const customer = await loadCustomer(input.customerCode);
if (!customer.branch_code) throw badRequest('客户未绑定分公司,无法维护商品库');
const codes = normalizeSkuCodes(input.skuCodes);
const skus = await pool.query(
`SELECT sku_code, sku_name, unit FROM skus
WHERE sku_code = ANY($1::text[]) AND COALESCE(status, 1) = 1
AND ($2::text IS NULL OR branch_code IS NULL OR branch_code = $2)`,
[codes, customer.branch_code]
);
const valid = new Map(
skus.rows.map((row) => [
String(row.sku_code),
{
name: row.sku_name,
unit: row.unit,
description: null,
},
])
);
const existing = await pool.query(
`SELECT sku_code FROM customer_skus
WHERE customer_code = $1 AND sku_code = ANY($2::text[])`,
[customer.customer_code, codes]
);
const already = new Set(existing.rows.map((row) => String(row.sku_code)));
const unknown = codes.filter((code) => !valid.has(code));
const toAdd = codes.filter((code) => valid.has(code) && !already.has(code));
const client = await pool.connect();
let actuallyAdded = 0;
try {
await client.query('BEGIN');
for (const code of toAdd) {
const sku = valid.get(code)!;
const inserted = await client.query(
`INSERT INTO customer_skus
(customer_code, sku_code, customer_sku_name, customer_unit, description, usage_count, is_favorite, branch_code)
VALUES ($1, $2, $3, $4, $5, 0, false, $6)
ON CONFLICT (customer_code, sku_code) DO NOTHING
RETURNING sku_code`,
[
customer.customer_code,
code,
sku.name == null ? null : String(sku.name),
sku.unit == null ? null : String(sku.unit),
null,
customer.branch_code,
]
);
actuallyAdded += inserted.rowCount || 0;
}
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
await writeAuditLog({
operatorId: input.operatorId || null,
operationType: 'customer_mall_sku_add',
targetTable: 'customer_skus',
targetId: customer.customer_code,
newValue: { customer_code: customer.customer_code, added: toAdd.length, skipped: already.size, unknown },
ipAddress: input.ipAddress || null,
branchCode: customer.branch_code,
actionCategory: 'customer',
}).catch(() => undefined);
return { added: actuallyAdded, skipped: codes.length - actuallyAdded - unknown.length, unknown };
}
/** 改客户商品库展示字段(只改展示名/单位/描述/收藏/上架;价格不在此写) */
export async function updateMallLibraryItem(input: {
customerCode: string;
skuCode: string;
customerSkuName?: unknown;
customerUnit?: unknown;
customerDescription?: unknown;
isFavorite?: unknown;
isListed?: unknown;
operatorId?: string | null;
ipAddress?: string | null;
}): Promise<{
sku_code: string;
display_name: string;
unit: string;
description: string | null;
is_favorite: boolean;
is_listed: boolean;
}> {
const customer = await loadCustomer(input.customerCode);
const skuCode = String(input.skuCode || '').trim();
if (!skuCode) throw badRequest('缺少商品编码');
const before = await pool.query(
`SELECT cs.sku_code,
COALESCE(NULLIF(TRIM(cs.customer_sku_name), ''), NULLIF(TRIM(s.sku_name), ''), cs.sku_code) AS display_name,
COALESCE(NULLIF(TRIM(cs.customer_unit), ''), NULLIF(TRIM(s.unit), ''), '斤') AS unit,
COALESCE(cs.is_favorite, false) AS is_favorite,
COALESCE(cs.is_listed, true) AS is_listed,
cs.customer_sku_name, cs.customer_unit,
NULLIF(TRIM(cs.description), '') AS description
FROM customer_skus cs
LEFT JOIN skus s ON s.sku_code = cs.sku_code
WHERE cs.customer_code = $1 AND cs.sku_code = $2
LIMIT 1`,
[customer.customer_code, skuCode]
);
if (!before.rowCount) throw notFound('该商品不在客户商品库中');
const sets: string[] = [];
const params: unknown[] = [customer.customer_code, skuCode];
const patch: Record<string, unknown> = {};
if (input.customerSkuName !== undefined) {
const raw = String(input.customerSkuName ?? '').trim();
if (raw.length > 200) throw badRequest('客户商品名不能超过 200 个字符');
params.push(raw || null);
sets.push(`customer_sku_name = $${params.length}`);
patch.customer_sku_name = raw || null;
}
if (input.customerUnit !== undefined) {
const raw = String(input.customerUnit ?? '').trim();
if (raw.length > 50) throw badRequest('单位不能超过 50 个字符');
params.push(raw || null);
sets.push(`customer_unit = $${params.length}`);
patch.customer_unit = raw || null;
}
if (input.customerDescription !== undefined) {
const raw = String(input.customerDescription ?? '').trim();
if (raw.length > 500) throw badRequest('描述不能超过 500 个字符');
params.push(raw || null);
sets.push(`description = $${params.length}`);
patch.description = raw || null;
}
if (input.isFavorite !== undefined) {
params.push(input.isFavorite === true || input.isFavorite === 1 || input.isFavorite === '1');
sets.push(`is_favorite = $${params.length}`);
patch.is_favorite = params[params.length - 1];
}
if (input.isListed !== undefined) {
params.push(input.isListed === true || input.isListed === 1 || input.isListed === '1');
sets.push(`is_listed = $${params.length}`);
patch.is_listed = params[params.length - 1];
}
if (!sets.length) throw badRequest('没有需要更新的字段');
sets.push('updated_at = NOW()');
await pool.query(
`UPDATE customer_skus SET ${sets.join(', ')}
WHERE customer_code = $1 AND sku_code = $2`,
params
);
const after = await pool.query(
`SELECT COALESCE(NULLIF(TRIM(cs.customer_sku_name), ''), NULLIF(TRIM(s.sku_name), ''), cs.sku_code) AS display_name,
COALESCE(NULLIF(TRIM(cs.customer_unit), ''), NULLIF(TRIM(s.unit), ''), '斤') AS unit,
NULLIF(TRIM(cs.description), '') AS description,
COALESCE(cs.is_favorite, false) AS is_favorite,
COALESCE(cs.is_listed, true) AS is_listed
FROM customer_skus cs
LEFT JOIN skus s ON s.sku_code = cs.sku_code
WHERE cs.customer_code = $1 AND cs.sku_code = $2
LIMIT 1`,
[customer.customer_code, skuCode]
);
await writeAuditLog({
operatorId: input.operatorId || null,
operationType: 'customer_mall_sku_update',
targetTable: 'customer_skus',
targetId: `${customer.customer_code}:${skuCode}`,
oldValue: {
customer_code: customer.customer_code,
sku_code: skuCode,
customer_sku_name: before.rows[0]?.customer_sku_name ?? null,
customer_unit: before.rows[0]?.customer_unit ?? null,
description: before.rows[0]?.description ?? null,
is_favorite: before.rows[0]?.is_favorite === true,
is_listed: before.rows[0]?.is_listed !== false,
},
newValue: patch,
ipAddress: input.ipAddress || null,
branchCode: customer.branch_code,
actionCategory: 'customer',
}).catch(() => undefined);
const row = after.rows[0] || {};
return {
sku_code: skuCode,
display_name: String(row.display_name || ''),
unit: String(row.unit || '斤'),
description: row.description == null ? null : String(row.description),
is_favorite: row.is_favorite === true,
is_listed: row.is_listed !== false,
};
}
/** 从客户商品库移除(商城与录单同时不可再选) */
export async function removeMallLibrarySku(input: {
customerCode: string;
skuCode: string;
operatorId?: string | null;
ipAddress?: string | null;
}): Promise<{ removed: boolean }> {
const customer = await loadCustomer(input.customerCode);
const skuCode = String(input.skuCode || '').trim();
if (!skuCode) throw badRequest('缺少商品编码');
const result = await pool.query(
`DELETE FROM customer_skus WHERE customer_code = $1 AND sku_code = $2 RETURNING sku_code`,
[customer.customer_code, skuCode]
);
if (!result.rowCount) throw notFound('该商品不在客户商品库中');
await writeAuditLog({
operatorId: input.operatorId || null,
operationType: 'customer_mall_sku_remove',
targetTable: 'customer_skus',
targetId: `${customer.customer_code}:${skuCode}`,
oldValue: { customer_code: customer.customer_code, sku_code: skuCode },
ipAddress: input.ipAddress || null,
branchCode: customer.branch_code,
actionCategory: 'customer',
}).catch(() => undefined);
return { removed: true };
}
type ImportRowInput = {
sku_code?: unknown;
customer_sku_name?: unknown;
customer_unit?: unknown;
is_favorite?: unknown;
};
type NormalizedImportRow = {
row: number;
sku_code: string;
customer_sku_name: string | null;
customer_unit: string | null;
is_favorite: boolean;
};
function parseFavorite(raw: unknown): boolean {
const text = String(raw ?? '').trim().toLowerCase();
return text === '1' || text === 'true' || text === 'yes' || text === '是' || text === 'y';
}
function normalizeImportRows(rawRows: unknown): {
rows: NormalizedImportRow[];
errors: string[];
duplicates: number;
} {
const list = Array.isArray(rawRows) ? rawRows : [];
if (!list.length) throw badRequest('导入内容为空');
if (list.length > MAX_IMPORT_ROWS) {
throw badRequest(`单次最多导入 ${MAX_IMPORT_ROWS} 行`);
}
const errors: string[] = [];
const seen = new Set<string>();
const rows: NormalizedImportRow[] = [];
let duplicates = 0;
list.forEach((raw, index) => {
const input = (raw || {}) as ImportRowInput;
const rowNo = index + 2; // Excel 第 1 行是表头
const skuCode = String(input.sku_code ?? '').trim();
if (!skuCode) {
if (errors.length < MAX_ERRORS) errors.push(`第 ${rowNo} 行:缺少商品编码`);
return;
}
if (seen.has(skuCode)) {
duplicates += 1;
return;
}
seen.add(skuCode);
const name = String(input.customer_sku_name ?? '').trim().slice(0, 200);
const unit = String(input.customer_unit ?? '').trim().slice(0, 50);
rows.push({
row: rowNo,
sku_code: skuCode,
customer_sku_name: name || null,
customer_unit: unit || null,
is_favorite: parseFavorite(input.is_favorite),
});
});
return { rows, errors, duplicates };
}
async function loadImportContext(customer: CustomerRow, rows: NormalizedImportRow[]) {
const codes = rows.map((row) => row.sku_code);
const [skus, existing] = await Promise.all([
pool.query(
`SELECT sku_code, sku_name, unit FROM skus
WHERE sku_code = ANY($1::text[]) AND COALESCE(status, 1) = 1
AND ($2::text IS NULL OR branch_code IS NULL OR branch_code = $2)`,
[codes, customer.branch_code]
),
pool.query(
`SELECT sku_code FROM customer_skus
WHERE customer_code = $1 AND sku_code = ANY($2::text[])`,
[customer.customer_code, codes]
),
]);
return {
skuByCode: new Map(skus.rows.map((row) => [String(row.sku_code), row])),
existing: new Set(existing.rows.map((row) => String(row.sku_code))),
};
}
/** 导入预览(只读):统计将新建 / 跳过 / 失败 */
export async function previewMallLibraryImport(input: {
customerCode: string;
rows: unknown;
}): Promise<{
total: number;
will_create: number;
will_skip: number;
will_fail: number;
duplicates: number;
sample_creates: string[];
errors: string[];
}> {
const customer = await loadCustomer(input.customerCode);
const normalized = normalizeImportRows(input.rows);
const { skuByCode, existing } = await loadImportContext(customer, normalized.rows);
const errors = [...normalized.errors];
const creates: NormalizedImportRow[] = [];
let skip = 0;
let fail = 0;
for (const row of normalized.rows) {
const sku = skuByCode.get(row.sku_code);
if (!sku) {
fail += 1;
if (errors.length < MAX_ERRORS) errors.push(`第 ${row.row} 行:商品编码不存在或已停用(${row.sku_code})`);
continue;
}
if (existing.has(row.sku_code)) {
skip += 1;
continue;
}
creates.push(row);
}
const nameByCode = new Map(
creates.map((row) => {
const sku = skuByCode.get(row.sku_code);
return [row.sku_code, String(row.customer_sku_name || sku?.sku_name || row.sku_code)];
})
);
return {
total: normalized.rows.length,
will_create: creates.length,
will_skip: skip,
will_fail: fail,
duplicates: normalized.duplicates,
sample_creates: creates.slice(0, 5).map((row) => nameByCode.get(row.sku_code) || row.sku_code),
errors,
};
}
/** 导入落库:只新增,已在库的跳过 */
export async function importMallLibraryRows(input: {
customerCode: string;
rows: unknown;
operatorId?: string | null;
ipAddress?: string | null;
}): Promise<{ created: number; skipped: number; failed: number; duplicates: number; errors: string[] }> {
const customer = await loadCustomer(input.customerCode);
if (!customer.branch_code) throw badRequest('客户未绑定分公司,无法维护商品库');
const normalized = normalizeImportRows(input.rows);
const { skuByCode, existing } = await loadImportContext(customer, normalized.rows);
const errors = [...normalized.errors];
const toCreate: NormalizedImportRow[] = [];
let skipped = 0;
let failed = 0;
for (const row of normalized.rows) {
const sku = skuByCode.get(row.sku_code);
if (!sku) {
failed += 1;
if (errors.length < MAX_ERRORS) errors.push(`第 ${row.row} 行:商品编码不存在或已停用(${row.sku_code})`);
continue;
}
if (existing.has(row.sku_code)) {
skipped += 1;
continue;
}
toCreate.push(row);
}
const client = await pool.connect();
let actuallyCreated = 0;
try {
await client.query('BEGIN');
for (const row of toCreate) {
const sku = skuByCode.get(row.sku_code)!;
const inserted = await client.query(
`INSERT INTO customer_skus
(customer_code, sku_code, customer_sku_name, customer_unit, description, usage_count, is_favorite, branch_code)
VALUES ($1, $2, $3, $4, $5, 0, $6, $7)
ON CONFLICT (customer_code, sku_code) DO NOTHING
RETURNING sku_code`,
[
customer.customer_code,
row.sku_code,
row.customer_sku_name || (sku.sku_name == null ? null : String(sku.sku_name)),
row.customer_unit || (sku.unit == null ? null : String(sku.unit)),
null,
row.is_favorite,
customer.branch_code,
]
);
actuallyCreated += inserted.rowCount || 0;
}
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
await writeAuditLog({
operatorId: input.operatorId || null,
operationType: 'customer_mall_sku_import',
targetTable: 'customer_skus',
targetId: customer.customer_code,
newValue: {
customer_code: customer.customer_code,
created: toCreate.length,
skipped,
failed,
duplicates: normalized.duplicates,
},
ipAddress: input.ipAddress || null,
branchCode: customer.branch_code,
actionCategory: 'customer',
}).catch(() => undefined);
return {
created: actuallyCreated,
skipped: skipped + (toCreate.length - actuallyCreated),
failed,
duplicates: normalized.duplicates,
errors,
};
}
+21 -13
View File
@@ -96,19 +96,6 @@ export async function setCustomerSkuSalePrice(input: {
[requestedSheet, customerCode, branchCode]
);
if (!active.rowCount) throw bad('报价单已失效或不属于该客户', 'quote_sheet_changed', 409);
const shared = await client.query(
`SELECT COUNT(*)::int AS n
FROM customer_quote_sheet_customers
WHERE quote_sheet_code = $1`,
[requestedSheet]
);
if (Number(shared.rows[0]?.n) > 1) {
throw bad(
'该报价单绑定多个客户,不能就地改价,避免改动其他客户价格',
'quote_sheet_shared_customer',
409
);
}
sheetCode = requestedSheet;
} else if (requestedTarget !== 'customer_sku') {
sheetCode = await resolveActiveQuoteSheetForCustomer(
@@ -131,7 +118,28 @@ export async function setCustomerSkuSalePrice(input: {
if (requestedTarget === 'quote_sheet') {
throw bad('该商品不在指定报价单中', 'quote_sheet_item_missing', 409);
}
// 自动选中的共享单不含该 SKU:不写别人的报价单,回落到客户商品库
sheetCode = null;
} else {
/**
* 先锁报价单条目,再锁绑定表:与“绑定新客户”的 INSERT 不会形成 item→binding 与
* binding→item 的环;锁内 count 封住 TOCTOU(校验后另一客户才绑定的窗口)。
* 自动选中的共享单不含该 SKU 时已在上面回落 customer_skus,不进入此分支。
*/
await client.query('LOCK TABLE customer_quote_sheet_customers IN SHARE ROW EXCLUSIVE MODE');
const shared = await client.query(
`SELECT COUNT(*)::int AS n
FROM customer_quote_sheet_customers
WHERE quote_sheet_code = $1`,
[sheetCode]
);
if (Number(shared.rows[0]?.n) > 1) {
throw bad(
'该报价单绑定多个客户,不能就地改价,避免改动其他客户价格',
'quote_sheet_shared_customer',
409
);
}
oldSalePrice = Number(current.rows[0]?.current_price) || null;
if (oldSalePrice != null && Math.abs(oldSalePrice - price) < 0.005) {
await client.query('COMMIT');
@@ -1,6 +1,6 @@
import { runWithTenantDataAccess } from './tenantSchemaService';
export type ImportType = 'sku' | 'category' | 'quote' | 'customer' | 'supplier';
export type ImportType = 'sku' | 'category' | 'quote' | 'customer' | 'supplier' | 'mall_product';
export interface ImportMappingMemory {
import_type: string;
@@ -12,7 +12,7 @@ export interface ImportMappingMemory {
function normalizeType(t: string): ImportType {
const v = String(t || '').toLowerCase();
if (v === 'sku' || v === 'category' || v === 'quote' || v === 'customer' || v === 'supplier') {
if (v === 'sku' || v === 'category' || v === 'quote' || v === 'customer' || v === 'supplier' || v === 'mall_product') {
return v;
}
throw new Error(`未知导入类型: ${t}`);
+59
View File
@@ -0,0 +1,59 @@
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
const read = (rel: string) => readFileSync(new URL(`../${rel}`, import.meta.url), 'utf8');
const migration = read('../migrations/20261088_customer_skus_mall_fields.sql');
const svc = read('src/services/customerMallAdminService.ts');
const route = read('src/modules/workflow/routes/customerRoutes.ts');
const page = readFileSync(new URL('../../src/pages/customers/MallManagement.tsx', import.meta.url), 'utf8');
describe('商城管理一期', () => {
it('迁移幂等:is_listed/default true、description', () => {
expect(migration).toContain('ADD COLUMN IF NOT EXISTS is_listed BOOLEAN NOT NULL DEFAULT true');
expect(migration).toContain('ADD COLUMN IF NOT EXISTS description TEXT');
const mapping = read('src/services/importMappingMemoryService.ts');
expect(mapping).toContain("'mall_product'");
});
it('列表价格复用录单取价;只读 customer_skus/skus/categories', () => {
expect(svc).toContain('enrichOrderItemsWithPrices');
expect(svc).toContain('branch_code = $4');
expect(svc).toContain('FROM customer_skus cs');
expect(svc).toContain('sale_price');
expect(svc).not.toMatch(/INSERT INTO orders|UPDATE orders|inventory|settlement/i);
});
it('添加/导入只新增不覆盖;已存在/停用/不存在计数', () => {
expect(svc).toContain('ON CONFLICT (customer_code, sku_code) DO NOTHING');
expect(svc).toContain('already');
expect(svc).toContain('unknown');
expect(svc).toContain('sku_disabled');
expect(svc).toContain('will_skip');
});
it('更新展示字段/上下架/收藏;删除二次确认页面', () => {
expect(svc).toContain('customer_sku_name');
expect(svc).toContain('is_listed');
expect(svc).toContain("operationType: 'customer_mall_sku_update'");
expect(svc).toContain("operationType: 'customer_mall_sku_remove'");
expect(page).toContain('confirmDialog');
});
it('6 个 workflow 路由 + customer_manage', () => {
for (const path of ['mall-products', 'mall-catalog']) {
expect(route).toContain(path);
}
expect(route).toContain("requireWorkflowPermission(ctx, ['customer_manage'])");
expect(route).toContain("dry_run");
});
it('前端价格复用 setCustomerSkuSalePriceApi、原位编辑、导入预览', () => {
expect(page).toContain('setCustomerSkuSalePriceApi');
expect(page).toContain('onBlur');
expect(page).toContain('BulkImportModal');
expect(page).toContain('mapMallImportRows');
expect(page).toContain('resolveSkuImageUrl');
expect(page).toContain('TablePaginationBar');
expect(page).toContain('removeMallLibrarySkuApi');
});
});
@@ -26,6 +26,9 @@ describe('客户 SKU 销售价二期', () => {
it('接口:报价单优先,否则 customer_skus;审计;不写订单/库存/结算', () => {
expect(svc).toContain("target = 'quote_sheet'");
expect(svc).toContain('sale_price_manual = true');
// 自动选择报价单也必须校验共享单,避免商城/排行改价串改其他客户价格
expect(svc).toContain('先锁报价单条目');
expect(svc).toContain('customer_quote_sheet_customers');
expect(svc).toContain('INSERT INTO customer_skus');
expect(svc).toContain('customer_sku_sale_price_update');
expect(svc).not.toMatch(/UPDATE orders|INSERT INTO order_items|inventory|settlement/i);