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
@@ -0,0 +1,79 @@
# 供应商系统 · 商城管理(客户商品库)一期
- 日期:2026-10-29
- 状态:一期(Web 管理后台)按开发者「先做商城管理后台」决定落地;客户登录/自助商城不在本期
- 参考:配送系统 `docs/design/20261029-customer-mall-management.md`、`customerMallAdminService.ts`、`MallManagement.tsx`
- 权限:复用 `customer_manage`,不新增权限码
## 1. 范围
Web 新增「商城管理」页,按客户维护 `customer_skus`:
- 查看客户商品库;
- 从基础商品库批量添加;
- 原位改客户商品名 / 单位 / 描述 / 收藏 / 上下架;
- 改客户销售价(复用既有 `PUT /customers/:customerCode/sku-sale-price`);
- 移出客户商品库;
- Excel 导入(只新增,已存在跳过)。
本期**不做**:客户登录、客户自助商城、小程序商城、订单提交新链路。
## 2. 与配送系统的差异
1. 供应商 `customer_skus` 已有 `sale_price/cost_price/price_updated_at/price_updated_by`,直接复用。
2. 供应商没有客户门户登录,B 期另定。
3. 供应商 `skus`/`product_catalog` 没有 `description`;本期只加 `customer_skus.description`,加入商品时描述为空,后续运营填写。图片继续用 `skus.image_url`。
4. 价格来源复用供应商 `enrichOrderItemsWithPrices`,与录单同源;不新写取价 SQL。
## 3. 数据
迁移(所有 tenant + template,幂等):
```sql
ALTER TABLE customer_skus ADD COLUMN IF NOT EXISTS is_listed boolean NOT NULL DEFAULT true;
ALTER TABLE customer_skus ADD COLUMN IF NOT EXISTS description text;
```
`is_listed=false` 只影响未来客户商城展示;本期没有客户商城,录单/订单不受影响。
## 4. 接口(workflow,`customer_manage`)
| 方法 | 路径 |
|---|---|
| GET | `/customers/:customerCode/mall-products` |
| GET | `/customers/:customerCode/mall-catalog?q=` |
| POST | `/customers/:customerCode/mall-products` |
| PATCH | `/customers/:customerCode/mall-products/:skuCode` |
| DELETE | `/customers/:customerCode/mall-products/:skuCode` |
| POST | `/customers/:customerCode/mall-products/import` |
| PUT | `/customers/:customerCode/sku-sale-price`(复用既有) |
服务端约束:
- customer_code 只从 URL 取;branch 由客户档案/租户上下文决定;
- 添加/导入只新增,不覆盖已有展示名/单位/描述/价格;
- 导入按 sku_code 去重,档案不存在/停用计失败;
- 所有写操作写 operation_logs;
- 不写订单/库存/结算。
## 5. 页面
`/customers/mall`,菜单「商城管理」(商品与客户组,客户列表之后)。
- 客户选择;搜索;
- 卡片/列表展示缩略图、客户商品名、单位、价格来源、描述、状态(可下单/待报价/档案停用/已下架)、收藏;
- 原位编辑,失焦/回车保存;
- 上架/下架;移出二次确认;
- 添加商品弹窗(本分公司启用 SKU,排除已在库);
- 导入预览/确认。
## 6. 验收
1. 迁移幂等,列存在;
2. 列表只显示当前客户商品库,价格与录单同源;
3. 添加/导入只新增,重复/停用/不存在正确处理;
4. 原位改名称/单位/描述/收藏/上下架,刷新保持;
5. 移出后 customer_skus 删除,录单不再可选;
6. 改销售价复用既有接口,写报价单或客户商品库;
7. 权限 customer_manage;跨分公司客户不可见;
8. typecheck + 后端/前端测试。
@@ -0,0 +1,26 @@
-- 2026-10-29:商城管理一期:客户商品库可见/上下架与描述。
-- 所有 tenant schema + tenant_template;幂等;不改录单/订单行为。
DO $$
DECLARE
sch text;
BEGIN
FOR sch IN
SELECT nspname FROM pg_namespace
WHERE nspname = 'tenant_template' OR nspname LIKE 'tenant\_%'
LOOP
-- 历史/空 tenant 可能没有 customer_skus;跳过而不是让整个迁移事务因 42P01 回滚
IF EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_schema = sch AND table_name = 'customer_skus'
) THEN
EXECUTE format(
'ALTER TABLE %I.customer_skus ADD COLUMN IF NOT EXISTS is_listed BOOLEAN NOT NULL DEFAULT true',
sch
);
EXECUTE format(
'ALTER TABLE %I.customer_skus ADD COLUMN IF NOT EXISTS description TEXT',
sch
);
END IF;
END LOOP;
END $$;
@@ -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);
+1 -1
View File
@@ -28,7 +28,7 @@ import { useT } from '../i18n';
export interface SmartImportConfig {
/** 导入类型(记忆隔离键) */
importType: 'sku' | 'category' | 'quote' | 'customer' | 'supplier';
importType: 'sku' | 'category' | 'quote' | 'customer' | 'supplier' | 'mall_product';
/** 字段词典 */
fields: ImportFieldDef[];
/** 解析 sheet 偏好 */
+1
View File
@@ -36,6 +36,7 @@ export const MENU_CATALOG: MenuCatalogEntry[] = [
},
{ menuKey: 'customers-list', path: '/customers', defaultLabel: '客户列表', icon: 'ChevronRight', permission: 'customer_manage', secondary: true },
{ menuKey: 'customers-quote-versions', path: '/customers/quote-versions', defaultLabel: '报价管理', icon: 'ChevronRight', permission: 'customer_manage', secondary: true },
{ menuKey: 'customers-mall', path: '/customers/mall', defaultLabel: '商城管理', icon: 'Store', permission: 'customer_manage', secondary: true },
{ menuKey: 'products-categories', path: '/products/categories', defaultLabel: '分类管理', icon: 'ChevronRight', permission: ['category_manage', 'product_manage'], secondary: true },
{ menuKey: 'products-skus', path: '/products/skus', defaultLabel: '商品管理', icon: 'ChevronRight', permission: ['sku_manage', 'product_manage'], secondary: true },
{ menuKey: 'products-units', path: '/products/units', defaultLabel: '单位管理', icon: 'ChevronRight', permission: ['sku_manage', 'product_manage'], secondary: true },
+46
View File
@@ -151,4 +151,50 @@ export const customers: MessageDict = {
'toast.importDone': 'Customer import finished',
'toast.unsupportedAction': 'This page does not support action {id}',
'mall.title': 'Mall management',
'mall.customerPlaceholder': 'Select customer',
'mall.searchPlaceholder': 'Search product name or code',
'mall.filter.all': 'All',
'mall.filter.aria': 'Filter products',
'mall.btn.add': 'Add products',
'mall.btn.import': 'Import products',
'mall.btn.remove': 'Remove',
'mall.btn.list': 'List',
'mall.btn.unlist': 'Unlist',
'mall.col.price': 'Mall price',
'mall.col.favorite': 'Favorite',
'mall.col.lastOrder': 'Last order',
'mall.col.product': 'products',
'mall.status.orderable': 'Orderable',
'mall.status.unlisted': 'Unlisted',
'mall.status.missingPrice': 'No price',
'mall.status.skuDisabled': 'Product disabled',
'mall.status.skuMissing': 'Product missing',
'mall.priceTarget.quoteSheet': 'Quote',
'mall.priceTarget.lastSale': 'Last sale',
'mall.priceTarget.library': 'Library',
'mall.empty.noCustomer': 'Select a customer first',
'mall.empty.noItems': 'No products yet. Use Add products or Import products.',
'mall.empty.noMatch': 'No matching products',
'mall.add.title': 'Add products',
'mall.add.searchPlaceholder': 'Search product catalog',
'mall.add.selected': '{n} selected',
'mall.add.empty': 'No products available to add',
'mall.add.unknown': '{n} product codes do not exist or are disabled',
'mall.edit.title': 'Edit product',
'mall.edit.name': 'Customer product name',
'mall.edit.description': 'Description',
'mall.edit.unit': 'Unit',
'mall.edit.price': 'Customer sale price',
'mall.edit.favorite': 'Pin to top in mall',
'mall.remove.title': 'Remove product',
'mall.remove.message': 'Remove {name} from this customer product library? It will no longer be selectable in the mall or order entry.',
'mall.remove.confirm': 'Remove',
'mall.toast.added': '{n} products added',
'mall.toast.saved': 'Saved',
'mall.toast.removed': 'Removed',
'mall.import.title': 'Import products',
'mall.import.description': 'Fill in product codes from the template to import into {name} customer library. Existing products are skipped.',
'mall.import.templateHint': 'Template: Product code* / Customer product name / Unit / Favorite',
'mall.summary': '{total} products · {orderable} orderable',
};
+1
View File
@@ -50,4 +50,5 @@ export const menu: MessageDict = {
'group.grp-business': 'Operations',
'group.grp-finance': 'Finance',
'group.grp-system': 'System',
'customers-mall': 'Mall management',
};
+46
View File
@@ -152,4 +152,50 @@ export const customers: MessageDict = {
'toast.importDone': 'Impor pelanggan selesai',
'toast.unsupportedAction': 'Halaman ini tidak mendukung aksi {id}',
'mall.title': 'Manajemen toko',
'mall.customerPlaceholder': 'Pilih pelanggan',
'mall.searchPlaceholder': 'Cari nama atau kode produk',
'mall.filter.all': 'Semua',
'mall.filter.aria': 'Saring produk',
'mall.btn.add': 'Tambah produk',
'mall.btn.import': 'Impor produk',
'mall.btn.remove': 'Keluarkan',
'mall.btn.list': 'Tampilkan',
'mall.btn.unlist': 'Sembunyikan',
'mall.col.price': 'Harga toko',
'mall.col.favorite': 'Favorit',
'mall.col.lastOrder': 'Pesanan terakhir',
'mall.col.product': 'produk',
'mall.status.orderable': 'Bisa dipesan',
'mall.status.unlisted': 'Tidak ditampilkan',
'mall.status.missingPrice': 'Belum ada harga',
'mall.status.skuDisabled': 'Produk nonaktif',
'mall.status.skuMissing': 'Produk tidak ada',
'mall.priceTarget.quoteSheet': 'Penawaran',
'mall.priceTarget.lastSale': 'Penjualan terakhir',
'mall.priceTarget.library': 'Pustaka',
'mall.empty.noCustomer': 'Pilih pelanggan terlebih dahulu',
'mall.empty.noItems': 'Belum ada produk. Gunakan Tambah produk atau Impor produk.',
'mall.empty.noMatch': 'Tidak ada produk yang cocok',
'mall.add.title': 'Tambah produk',
'mall.add.searchPlaceholder': 'Cari katalog produk',
'mall.add.selected': '{n} dipilih',
'mall.add.empty': 'Tidak ada produk yang bisa ditambahkan',
'mall.add.unknown': '{n} kode produk tidak ada atau nonaktif',
'mall.edit.title': 'Edit produk',
'mall.edit.name': 'Nama produk pelanggan',
'mall.edit.description': 'Deskripsi',
'mall.edit.unit': 'Satuan',
'mall.edit.price': 'Harga jual pelanggan',
'mall.edit.favorite': 'Sematkan di atas toko',
'mall.remove.title': 'Keluarkan produk',
'mall.remove.message': 'Keluarkan {name} dari pustaka produk pelanggan ini? Produk tidak bisa dipilih lagi di toko maupun entri pesanan.',
'mall.remove.confirm': 'Keluarkan',
'mall.toast.added': '{n} produk ditambahkan',
'mall.toast.saved': 'Tersimpan',
'mall.toast.removed': 'Dikeluarkan',
'mall.import.title': 'Impor produk',
'mall.import.description': 'Isi kode produk sesuai templat untuk mengimpor ke pustaka pelanggan {name}. Produk yang sudah ada akan dilewati.',
'mall.import.templateHint': 'Templat: Kode produk* / Nama produk pelanggan / Satuan / Favorit',
'mall.summary': '{total} produk · {orderable} bisa dipesan',
};
+1
View File
@@ -50,4 +50,5 @@ export const menu: MessageDict = {
'group.grp-business': 'Operasi',
'group.grp-finance': 'Keuangan',
'group.grp-system': 'Sistem',
'customers-mall': 'Manajemen toko',
};
+46
View File
@@ -151,4 +151,50 @@ export const customers: MessageDict = {
'toast.importDone': '客户批量导入完成',
'toast.unsupportedAction': '当前页不支持操作 {id}',
'mall.title': '商城管理',
'mall.customerPlaceholder': '选择客户',
'mall.searchPlaceholder': '搜索商品名或编码',
'mall.filter.all': '全部',
'mall.filter.aria': '筛选商品',
'mall.btn.add': '添加商品',
'mall.btn.import': '导入商品',
'mall.btn.remove': '移出',
'mall.btn.list': '上架',
'mall.btn.unlist': '下架',
'mall.col.price': '商城价',
'mall.col.favorite': '收藏',
'mall.col.lastOrder': '最近下单',
'mall.col.product': '商品',
'mall.status.orderable': '可下单',
'mall.status.unlisted': '已下架',
'mall.status.missingPrice': '待报价',
'mall.status.skuDisabled': '档案停用',
'mall.status.skuMissing': '档案缺失',
'mall.priceTarget.quoteSheet': '报价单',
'mall.priceTarget.lastSale': '上次成交',
'mall.priceTarget.library': '商品库',
'mall.empty.noCustomer': '请先选择客户',
'mall.empty.noItems': '暂无商品,点击「添加商品」或「导入商品」',
'mall.empty.noMatch': '没有匹配的商品',
'mall.add.title': '添加商品',
'mall.add.searchPlaceholder': '搜索商品档案',
'mall.add.selected': '已选 {n} 个',
'mall.add.empty': '没有可添加的商品',
'mall.add.unknown': '{n} 个商品编码不存在或已停用',
'mall.edit.title': '编辑商品',
'mall.edit.name': '客户商品名',
'mall.edit.description': '描述',
'mall.edit.unit': '单位',
'mall.edit.price': '客户销售价',
'mall.edit.favorite': '收藏到商城前排',
'mall.remove.title': '移出商品',
'mall.remove.message': '将「{name}」从该客户商品库移除?商城与录单都将不可再选。',
'mall.remove.confirm': '移出',
'mall.toast.added': '已添加 {n} 个商品',
'mall.toast.saved': '已保存',
'mall.toast.removed': '已移出',
'mall.import.title': '导入商品',
'mall.import.description': '按模板填写商品编码,导入到「{name}」的客户商品库。已在库中的商品会跳过。',
'mall.import.templateHint': '模板列:商品编码* / 客户商品名 / 单位 / 收藏',
'mall.summary': '共 {total} 个商品 · 可下单 {orderable}',
};
+1
View File
@@ -50,4 +50,5 @@ export const menu: MessageDict = {
'group.grp-business': '业务流程',
'group.grp-finance': '财务管理',
'group.grp-system': '系统管理',
'customers-mall': '商城管理',
};
+2 -1
View File
@@ -72,7 +72,7 @@ export const BUSINESS_MODULES: BusinessModuleDef[] = [
id: 'customer',
name: '客户管理',
permissions: ['customer_manage', 'alias_manage'],
menuKeys: ['customers-list', 'customers-quote-versions'],
menuKeys: ['customers-list', 'customers-quote-versions', 'customers-mall'],
routes: [
{
path: 'customers',
@@ -81,6 +81,7 @@ export const BUSINESS_MODULES: BusinessModuleDef[] = [
{ path: '', page: 'CustomerManagement', permission: 'customer_manage' },
{ path: 'alias-library', page: 'CustomerManagement', permission: ['customer_manage', 'alias_manage'], redirect: '/customers/quote-versions?view=library' },
{ path: 'quote-versions', page: 'QuoteVersionManagement', permission: 'customer_manage' },
{ path: 'mall', page: 'MallManagement', permission: 'customer_manage' },
],
},
],
+1
View File
@@ -21,6 +21,7 @@ const PAGE_LOADERS: Record<string, ReturnType<typeof lazyPage>> = {
UnitManagement: lazyPage(() => import('../pages/products/UnitManagement'), 'UnitManagement'),
CustomerManagement: lazyPage(() => import('../pages/customers/CustomerManagement'), 'CustomerManagement'),
QuoteVersionManagement: lazyPage(() => import('../pages/customers/QuoteVersionManagement'), 'QuoteVersionManagement'),
MallManagement: lazyPage(() => import('../pages/customers/MallManagement'), 'MallManagement'),
SupplierManagement: lazyPage(() => import('../pages/suppliers/SupplierManagement'), 'SupplierManagement'),
OrderManagement: lazyPage(() => import('../pages/orders/orderManagement'), 'OrderManagement'),
OrderTrash: lazyPage(() => import('../pages/orders/OrderTrash'), 'OrderTrash'),
+861
View File
@@ -0,0 +1,861 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import {
Loader2,
Package,
Plus,
RefreshCw,
Search,
Star,
Trash2,
Upload,
} from 'lucide-react';
import { supabase } from '../../supabase/client';
import { useOperatingBranch } from '../../hooks/useOperatingBranch';
import { useT } from '../../i18n';
import { SearchableSelect } from '../../components/ui/SearchableSelect';
import { DialogOverlay } from '../../components/ui/DialogOverlay';
import { BulkImportModal } from '../../components/BulkImportModal';
import { TablePaginationBar } from '../../components/ui/TablePaginationBar';
import { useClientTablePagination } from '../../hooks/useClientTablePagination';
import { notify } from '../../utils/notify';
import { confirmDialog } from '../../utils/confirmDialog';
import { resolveSkuImageUrl } from '../../utils/skuImage';
import {
MALL_IMPORT_FIELD_DICT,
downloadMallImportTemplate,
mapMallImportRows,
} from '../../utils/customerMallImport';
import {
addMallLibrarySkusApi,
fetchMallLibraryApi,
importMallRowsApi,
previewMallImportApi,
removeMallLibrarySkuApi,
searchMallCatalogApi,
setCustomerSkuSalePriceApi,
updateMallLibraryItemApi,
type MallCatalogSku,
type MallLibraryItem,
type MallLibraryStatus,
} from '../../utils/workflowApi';
type CustomerOption = {
customer_code: string;
company_name: string;
branch_code: string | null;
status: number | null;
};
type MallLibraryState = {
customer: { customer_code: string; company_name: string; branch_code: string | null };
items: MallLibraryItem[];
summary: Record<MallLibraryStatus, number> & { total: number };
};
const TRADABLE_STATUS = new Set([1, 10, 20, 30]);
// 卡片内原位输入框:普通灰边框(不用主题色 focus 外框,2026-10-30 开发者要求)。
const INLINE_INPUT_CLASS =
'h-7 rounded-md border border-slate-200 bg-white px-1.5 text-[13px] text-slate-800 transition-colors hover:border-slate-300 focus:border-slate-400 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100';
type MallCardProps = {
item: MallLibraryItem;
customerCode: string;
listing: boolean;
onToggleListed: (item: MallLibraryItem) => void;
onRemove: (item: MallLibraryItem) => void;
onRefresh: () => Promise<void>;
};
/** 卡片内直接编辑:输入框就在显示位置,失焦/回车即保存(无编辑按钮、无 ✓/×)。 */
const MallCard: React.FC<MallCardProps> = ({
item,
customerCode,
listing,
onToggleListed,
onRemove,
onRefresh,
}) => {
const t = useT();
const statusMeta: Record<MallLibraryStatus, { label: string; cls: string }> = {
orderable: { label: t('customers.mall.status.orderable'), cls: 'app-status-success' },
missing_price: { label: t('customers.mall.status.missingPrice'), cls: 'app-status-warning' },
sku_disabled: { label: t('customers.mall.status.skuDisabled'), cls: 'app-status-danger' },
sku_missing: { label: t('customers.mall.status.skuMissing'), cls: 'app-status-danger' },
};
const meta = statusMeta[item.status];
const imageSrc = resolveSkuImageUrl(item.image_url, item.sku_code);
// 展示名与档案名一致时输入框留空(placeholder 显示档案名),保存空值 = 沿用档案名。
const editableName = (value: string) =>
item.catalog_name && value === item.catalog_name ? '' : value;
const initialPrice =
item.mall_price > 0
? item.mall_price
: item.sale_price != null && item.sale_price > 0
? item.sale_price
: null;
const saved = useRef({
name: editableName(String(item.display_name || '')),
description: String(item.description || ''),
unit: String(item.unit || ''),
price: initialPrice as number | null,
});
const [name, setName] = useState(saved.current.name);
const [description, setDescription] = useState(saved.current.description);
const [unit, setUnit] = useState(saved.current.unit);
const [price, setPrice] = useState(initialPrice != null ? initialPrice.toFixed(2) : '');
const [favorite, setFavorite] = useState(item.is_favorite);
const [pending, setPending] = useState(0);
const priceDirty = useRef(false);
const busy = pending > 0;
// 价格可能由报价单决定:服务端刷新后用生效价回填,但不打断正在输入的值。
useEffect(() => {
if (priceDirty.current) return;
const next =
item.mall_price > 0
? item.mall_price
: item.sale_price != null && item.sale_price > 0
? item.sale_price
: null;
saved.current.price = next;
setPrice(next != null ? next.toFixed(2) : '');
}, [item.mall_price, item.sale_price]);
const fail = (error: any) => notify.error(error?.message || t('customers.toast.saveFail'));
const patchFields = async (patch: {
customer_sku_name?: string | null;
description?: string | null;
customer_unit?: string | null;
}): Promise<boolean> => {
if (!Object.keys(patch).length) return true;
setPending((n) => n + 1);
try {
await updateMallLibraryItemApi(customerCode, item.sku_code, patch);
return true;
} catch (error: any) {
fail(error);
return false;
} finally {
setPending((n) => n - 1);
}
};
const commitName = async () => {
const next = name.trim();
if (next === saved.current.name.trim()) return;
if (await patchFields({ customer_sku_name: next || null })) {
saved.current.name = next;
setName(next);
await onRefresh();
} else {
setName(saved.current.name);
}
};
const commitDescription = async () => {
const next = description.trim();
if (next === saved.current.description.trim()) return;
if (await patchFields({ description: next || null })) {
saved.current.description = next;
setDescription(next);
await onRefresh();
} else {
setDescription(saved.current.description);
}
};
const commitUnit = async () => {
const next = unit.trim();
if (next === saved.current.unit.trim()) return;
if (await patchFields({ customer_unit: next || null })) {
saved.current.unit = next;
setUnit(next);
await onRefresh();
} else {
setUnit(saved.current.unit);
}
};
const commitPrice = async () => {
const raw = price.trim();
const next = raw === '' ? null : Number(raw);
if (next != null && (!Number.isFinite(next) || next < 0)) {
fail(new Error(t('customers.toast.saveFail')));
setPrice(saved.current.price != null ? saved.current.price.toFixed(2) : '');
return;
}
const normalized = next != null && next > 0 ? next : null;
if (normalized === saved.current.price) {
priceDirty.current = false;
setPrice(saved.current.price != null ? saved.current.price.toFixed(2) : '');
return;
}
setPending((n) => n + 1);
try {
// 改价复用既有入口:执行中报价单里有该商品 → 写报价单条目;
// 没有报价单 → 写客户商品库。
await setCustomerSkuSalePriceApi({
customerCode,
sku_code: item.sku_code,
sale_price: normalized,
});
saved.current.price = normalized;
priceDirty.current = false;
await onRefresh();
} catch (error: any) {
fail(error);
setPrice(saved.current.price != null ? saved.current.price.toFixed(2) : '');
} finally {
setPending((n) => n - 1);
}
};
const toggleFavorite = async () => {
const next = !favorite;
setFavorite(next);
setPending((n) => n + 1);
try {
await updateMallLibraryItemApi(customerCode, item.sku_code, { is_favorite: next });
} catch (error: any) {
setFavorite(!next);
fail(error);
} finally {
setPending((n) => n - 1);
}
};
const commitOnEnter = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Enter') event.currentTarget.blur();
};
return (
<div className="flex gap-1.5 overflow-hidden rounded-lg border border-slate-200 bg-white p-2 dark:border-slate-700 dark:bg-slate-900">
<div className="relative w-20 shrink-0 self-stretch overflow-hidden rounded-md bg-slate-100 dark:bg-slate-800">
{imageSrc ? (
<img
src={imageSrc}
alt={item.display_name}
loading="lazy"
className="h-full w-full object-cover"
/>
) : (
<div className="flex h-full w-full items-center justify-center">
<Package className="h-4 w-4 text-slate-300 dark:text-slate-600" />
</div>
)}
<button
type="button"
className={`absolute bottom-0.5 right-0.5 rounded p-0.5 hover:bg-white/70 disabled:opacity-50 dark:hover:bg-slate-800 ${
favorite ? 'text-amber-500' : 'text-slate-400'
}`}
title={t('customers.mall.col.favorite')}
aria-label={t('customers.mall.col.favorite')}
disabled={busy}
onClick={() => void toggleFavorite()}
>
<Star className="h-3 w-3" fill={favorite ? 'currentColor' : 'none'} />
</button>
</div>
<div className="flex min-w-0 flex-1 flex-col justify-center gap-1">
<div className="flex items-center gap-1">
<span
className={`shrink-0 whitespace-nowrap rounded-full px-1.5 py-0.5 text-xs ${
item.is_listed
? meta.cls
: 'bg-slate-200 text-slate-600 dark:bg-slate-700 dark:text-slate-300'
}`}
>
{item.is_listed ? meta.label : t('customers.mall.status.unlisted')}
</span>
<input
className={`${INLINE_INPUT_CLASS} min-w-0 flex-1`}
style={{ outline: 'none' }}
value={name}
onChange={(event) => setName(event.target.value)}
onBlur={() => void commitName()}
onKeyDown={commitOnEnter}
placeholder={item.catalog_name || item.display_name}
aria-label={t('customers.mall.edit.name')}
/>
<button
type="button"
className="shrink-0 whitespace-nowrap rounded-md border border-slate-200 px-1.5 py-0.5 text-[13px] text-slate-800 transition-colors hover:bg-slate-50 disabled:opacity-50 dark:border-slate-700 dark:text-slate-100 dark:hover:bg-slate-800"
disabled={listing}
onClick={() => onToggleListed(item)}
>
{listing
? '…'
: item.is_listed
? t('customers.mall.btn.unlist')
: t('customers.mall.btn.list')}
</button>
<button
type="button"
className="shrink-0 rounded p-0.5 text-slate-500 hover:bg-slate-100 hover:text-rose-600 dark:hover:bg-slate-800 dark:hover:text-rose-400"
title={t('customers.mall.btn.remove')}
aria-label={t('customers.mall.btn.remove')}
onClick={() => onRemove(item)}
>
<Trash2 className="h-3.5 w-3.5" />
</button>
{busy ? <Loader2 className="h-3 w-3 shrink-0 animate-spin text-slate-400" /> : null}
</div>
<div className="flex items-center gap-1">
<span className="text-[13px] text-slate-800 dark:text-slate-100">¥</span>
<input
type="number"
min="0"
step="0.01"
className={`${INLINE_INPUT_CLASS} min-w-0 flex-1 appearance-none text-right tabular-nums [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none`}
style={{ outline: 'none' }}
value={price}
onChange={(event) => {
priceDirty.current = true;
setPrice(event.target.value);
}}
onBlur={() => void commitPrice()}
onKeyDown={commitOnEnter}
placeholder="—"
aria-label={t('customers.mall.edit.price')}
/>
<input
className={`${INLINE_INPUT_CLASS} w-[4.5rem] shrink-0 px-1 text-center`}
style={{ outline: 'none' }}
value={unit}
onChange={(event) => setUnit(event.target.value)}
onBlur={() => void commitUnit()}
onKeyDown={commitOnEnter}
placeholder={item.catalog_unit || '斤'}
aria-label={t('customers.mall.edit.unit')}
/>
<span className="shrink-0 whitespace-nowrap rounded-md border border-slate-200 px-1.5 text-[13px] leading-7 text-slate-800 dark:border-slate-700 dark:text-slate-100">
{item.price_source === 'quote_sheet' || item.on_quote_sheet
? t('customers.mall.priceTarget.quoteSheet')
: item.price_source === 'last_sale_name_spec'
? t('customers.mall.priceTarget.lastSale')
: t('customers.mall.priceTarget.library')}
</span>
</div>
<input
className={`${INLINE_INPUT_CLASS} w-full`}
style={{ outline: 'none' }}
value={description}
onChange={(event) => setDescription(event.target.value)}
onBlur={() => void commitDescription()}
onKeyDown={commitOnEnter}
placeholder={t('customers.mall.edit.description')}
aria-label={t('customers.mall.edit.description')}
/>
</div>
</div>
);
}
export const MallManagement: React.FC = () => {
const t = useT();
const { operatingBranchCode } = useOperatingBranch();
const [searchParams, setSearchParams] = useSearchParams();
const [customers, setCustomers] = useState<CustomerOption[]>([]);
const [customerCode, setCustomerCode] = useState('');
const [library, setLibrary] = useState<MallLibraryState | null>(null);
const [loading, setLoading] = useState(false);
const [query, setQuery] = useState('');
const [sourceFilter, setSourceFilter] = useState<'all' | 'missing_price' | 'library' | 'quote_sheet'>('all');
const [addOpen, setAddOpen] = useState(false);
const [catalogQuery, setCatalogQuery] = useState('');
const [catalog, setCatalog] = useState<MallCatalogSku[]>([]);
const [catalogLoading, setCatalogLoading] = useState(false);
const [selectedCodes, setSelectedCodes] = useState<string[]>([]);
const [adding, setAdding] = useState(false);
const [listingSku, setListingSku] = useState<string | null>(null);
const [importOpen, setImportOpen] = useState(false);
const catalogTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const initialCustomerRef = useRef(String(searchParams.get('customer') || '').trim());
useEffect(() => {
let cancelled = false;
void (async () => {
const { data } = await supabase
.from('customers')
.select('customer_code, company_name, branch_code, status')
.order('company_name', { ascending: true });
if (cancelled) return;
const rows = ((data || []) as CustomerOption[]).filter((row) =>
TRADABLE_STATUS.has(Number(row.status ?? 10))
);
setCustomers(rows);
const fromUrl = initialCustomerRef.current;
setCustomerCode((prev) => {
if (prev && rows.some((row) => row.customer_code === prev)) return prev;
if (fromUrl && rows.some((row) => row.customer_code === fromUrl)) return fromUrl;
return rows[0]?.customer_code || '';
});
})();
return () => {
cancelled = true;
};
// 只在切分公司时重拉客户列表;URL 上的 customer 只用于首次定位
}, [operatingBranchCode]);
useEffect(() => {
if (!customerCode) {
setLibrary(null);
return;
}
setSearchParams(
(prev) => {
const next = new URLSearchParams(prev);
next.set('customer', customerCode);
return next;
},
{ replace: true }
);
}, [customerCode, setSearchParams]);
const loadLibrary = useCallback(async (options?: { silent?: boolean }) => {
if (!customerCode) return;
if (!options?.silent) setLoading(true);
try {
const res = await fetchMallLibraryApi(customerCode);
setLibrary(res.data);
} catch (error: any) {
notify.error(error?.message || t('customers.mall.empty.noCustomer'));
setLibrary(null);
} finally {
if (!options?.silent) setLoading(false);
}
}, [customerCode, t]);
useEffect(() => {
void loadLibrary();
}, [loadLibrary]);
const customerOptions = useMemo(
() =>
customers.map((row) => ({
value: row.customer_code,
label: row.company_name || row.customer_code,
})),
[customers]
);
const filteredItems = useMemo(() => {
const q = query.trim().toLowerCase();
let items = library?.items || [];
if (sourceFilter === 'missing_price') {
items = items.filter((item) => item.status === 'missing_price');
} else if (sourceFilter === 'library') {
items = items.filter((item) => !item.on_quote_sheet);
} else if (sourceFilter === 'quote_sheet') {
items = items.filter((item) => Boolean(item.on_quote_sheet));
}
if (!q) return items;
return items.filter(
(item) =>
item.display_name.toLowerCase().includes(q) ||
item.sku_code.toLowerCase().includes(q) ||
String(item.catalog_name || '').toLowerCase().includes(q)
);
}, [library, query, sourceFilter]);
const page = useClientTablePagination(filteredItems, {
resetKey: `${customerCode}|${query}|${sourceFilter}`,
});
const loadCatalog = useCallback(
async (q: string) => {
if (!customerCode) return;
setCatalogLoading(true);
try {
const res = await searchMallCatalogApi(customerCode, q);
setCatalog(res.data || []);
} catch (error: any) {
notify.error(error?.message || t('customers.mall.add.empty'));
setCatalog([]);
} finally {
setCatalogLoading(false);
}
},
[customerCode, t]
);
const openAdd = () => {
if (!customerCode) return;
setAddOpen(true);
setCatalogQuery('');
setSelectedCodes([]);
void loadCatalog('');
};
const onCatalogQueryChange = (value: string) => {
setCatalogQuery(value);
if (catalogTimer.current) clearTimeout(catalogTimer.current);
catalogTimer.current = setTimeout(() => {
catalogTimer.current = null;
void loadCatalog(value);
}, 300);
};
const toggleCatalogSku = (skuCode: string) => {
setSelectedCodes((prev) =>
prev.includes(skuCode) ? prev.filter((code) => code !== skuCode) : [...prev, skuCode]
);
};
const submitAdd = async () => {
if (!customerCode || !selectedCodes.length || adding) return;
setAdding(true);
try {
const res = await addMallLibrarySkusApi(customerCode, selectedCodes);
const data = res.data;
notify.success(
t('customers.mall.toast.added', { n: String(data.added) })
);
if (data.unknown?.length) {
notify.warning(t('customers.mall.add.unknown', { n: String(data.unknown.length) }));
}
setAddOpen(false);
setSelectedCodes([]);
await loadLibrary();
} catch (error: any) {
notify.error(error?.message || t('customers.mall.add.title'));
} finally {
setAdding(false);
}
};
const toggleListed = async (item: MallLibraryItem) => {
if (!customerCode || listingSku) return;
setListingSku(item.sku_code);
try {
await updateMallLibraryItemApi(customerCode, item.sku_code, {
is_listed: !item.is_listed,
});
await loadLibrary();
} catch (error: any) {
notify.error(error?.message || t('customers.toast.saveFail'));
} finally {
setListingSku(null);
}
};
const removeItem = async (item: MallLibraryItem) => {
if (!customerCode) return;
const ok = await confirmDialog({
title: t('customers.mall.remove.title'),
message: t('customers.mall.remove.message', { name: item.display_name }),
confirmText: t('customers.mall.remove.confirm'),
danger: true,
});
if (!ok) return;
try {
await removeMallLibrarySkuApi(customerCode, item.sku_code);
notify.success(t('customers.mall.toast.removed'));
await loadLibrary();
} catch (error: any) {
notify.error(error?.message || t('customers.mall.remove.title'));
}
};
return (
<div className="space-y-4">
<div className="app-surface rounded-xl p-4">
<div className="flex items-center gap-2 overflow-x-auto">
{library ? (
<p className="app-foreground-muted shrink-0 whitespace-nowrap text-[12px]">
{t('customers.mall.summary', {
total: String(library.summary.total),
orderable: String(library.summary.orderable),
})}
</p>
) : null}
<div className="w-56 shrink-0">
<SearchableSelect
value={customerCode}
onChange={(value) => {
setCustomerCode(value);
setQuery('');
setSourceFilter('all');
}}
options={customerOptions}
placeholder={t('customers.mall.customerPlaceholder')}
hideSearchIcon
portal
/>
</div>
<div className="relative min-w-[180px] flex-1">
<Search className="app-foreground-muted pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2" />
<input
className="app-input w-full pl-9"
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder={t('customers.mall.searchPlaceholder')}
/>
</div>
<div className="flex shrink-0 items-center gap-2" role="group" aria-label={t('customers.mall.filter.aria')}>
{(
[
['all', t('customers.mall.filter.all')],
['missing_price', t('customers.mall.status.missingPrice')],
['library', t('customers.mall.priceTarget.library')],
['quote_sheet', t('customers.mall.priceTarget.quoteSheet')],
] as const
).map(([value, label]) => {
const active = sourceFilter === value;
return (
<button
key={value}
type="button"
aria-pressed={active}
className={`rounded-lg border px-3 py-1.5 text-sm transition-colors ${
active ? 'app-button-primary border-transparent' : 'app-button-secondary app-border'
}`}
onClick={() => setSourceFilter(value)}
>
{label}
</button>
);
})}
</div>
<div className="ml-auto flex shrink-0 items-center gap-2">
<button
type="button"
className="app-button-secondary inline-flex items-center gap-1.5 rounded-lg border px-3 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50"
onClick={() => void loadLibrary()}
disabled={!customerCode || loading}
>
<RefreshCw className={`h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
{t('common.refresh')}
</button>
<button
type="button"
className="app-button-secondary inline-flex items-center gap-1.5 rounded-lg border px-3 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50"
onClick={() => setImportOpen(true)}
disabled={!customerCode}
>
<Upload className="h-4 w-4" />
{t('customers.mall.btn.import')}
</button>
<button
type="button"
className="app-button-primary inline-flex items-center gap-1.5 rounded-lg px-3 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50"
onClick={openAdd}
disabled={!customerCode}
>
<Plus className="h-4 w-4" />
{t('customers.mall.btn.add')}
</button>
</div>
</div>
</div>
<div className="app-surface overflow-hidden rounded-xl">
{!customerCode ? (
<div className="app-foreground-muted px-4 py-16 text-center text-sm">
{t('customers.mall.empty.noCustomer')}
</div>
) : loading && !library ? (
<div className="app-foreground-muted flex items-center justify-center gap-2 px-4 py-16 text-sm">
<Loader2 className="h-4 w-4 animate-spin" />
{t('common.loading')}
</div>
) : filteredItems.length === 0 ? (
<div className="app-foreground-muted px-4 py-16 text-center text-sm">
{library?.items.length
? t('customers.mall.empty.noMatch')
: t('customers.mall.empty.noItems')}
</div>
) : (
<div>
<div
className="grid gap-2 p-2"
style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))' }}
>
{page.pageRows.map((item) => (
<MallCard
key={`${customerCode}:${item.sku_code}`}
item={item}
customerCode={customerCode}
listing={listingSku === item.sku_code}
onToggleListed={(row) => void toggleListed(row)}
onRemove={(row) => void removeItem(row)}
onRefresh={() => loadLibrary({ silent: true })}
/>
))}
</div>
<TablePaginationBar
total={page.total}
page={page.page}
pageSize={page.pageSize}
onPageChange={page.setPage}
onPageSizeChange={page.setPageSize}
itemLabel={t('customers.mall.col.product')}
/>
</div>
)}
</div>
{addOpen ? (
<DialogOverlay>
<div className="flex max-h-[80vh] w-full max-w-2xl flex-col rounded-xl bg-white shadow-xl dark:bg-slate-900">
<div className="flex items-center justify-between border-b border-slate-200 px-4 py-3 dark:border-slate-700">
<h2 className="text-lg font-semibold">{t('customers.mall.add.title')}</h2>
<button
type="button"
className="rounded-md px-2 text-xl leading-none text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-800"
onClick={() => setAddOpen(false)}
aria-label={t('common.close')}
>
×
</button>
</div>
<div className="border-b border-slate-200 px-4 py-3 dark:border-slate-700">
<div className="relative">
<Search className="app-foreground-muted pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2" />
<input
className="app-input w-full pl-9"
value={catalogQuery}
onChange={(event) => onCatalogQueryChange(event.target.value)}
placeholder={t('customers.mall.add.searchPlaceholder')}
autoFocus
/>
</div>
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-2 py-2">
{catalogLoading ? (
<div className="app-foreground-muted flex items-center justify-center gap-2 py-12 text-sm">
<Loader2 className="h-4 w-4 animate-spin" />
{t('common.loading')}
</div>
) : catalog.length === 0 ? (
<div className="app-foreground-muted py-12 text-center text-sm">
{t('customers.mall.add.empty')}
</div>
) : (
catalog.map((sku) => {
const checked = selectedCodes.includes(sku.sku_code);
return (
<label
key={sku.sku_code}
className="flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2 hover:bg-slate-50 dark:hover:bg-slate-800"
>
<input
type="checkbox"
checked={checked}
onChange={() => toggleCatalogSku(sku.sku_code)}
/>
{resolveSkuImageUrl(sku.image_url, sku.sku_code) ? (
<img
src={resolveSkuImageUrl(sku.image_url, sku.sku_code)}
alt={sku.sku_name}
loading="lazy"
className="h-10 w-10 shrink-0 rounded-lg object-cover"
/>
) : (
<span className="h-10 w-10 shrink-0 rounded-lg bg-slate-100 dark:bg-slate-800" />
)}
<span className="min-w-0 flex-1">
<span className="block truncate font-medium">{sku.sku_name}</span>
<span className="app-foreground-muted block truncate text-xs">
{sku.sku_code}
{sku.spec ? ` · ${sku.spec}` : ''}
{sku.unit ? ` · ${sku.unit}` : ''}
</span>
</span>
</label>
);
})
)}
</div>
<div className="flex items-center justify-between gap-3 border-t border-slate-200 px-4 py-3 dark:border-slate-700">
<span className="app-foreground-muted text-sm">
{t('customers.mall.add.selected', { n: String(selectedCodes.length) })}
</span>
<div className="flex items-center gap-2">
<button
type="button"
className="app-button-secondary inline-flex items-center justify-center rounded-lg border px-3 py-2 text-sm font-medium transition-colors"
onClick={() => setAddOpen(false)}
>
{t('common.cancel')}
</button>
<button
type="button"
className="app-button-primary inline-flex items-center justify-center gap-1.5 rounded-lg px-3 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50"
onClick={() => void submitAdd()}
disabled={!selectedCodes.length || adding}
>
{adding ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
{t('customers.mall.btn.add')}
</button>
</div>
</div>
</div>
</DialogOverlay>
) : null}
{customerCode ? (
<BulkImportModal
open={importOpen}
title={t('customers.mall.import.title')}
description={t('customers.mall.import.description', {
name: library?.customer.company_name || customerCode,
})}
templateHint={t('customers.mall.import.templateHint')}
onClose={() => setImportOpen(false)}
onDownloadTemplate={downloadMallImportTemplate}
stepFeatures={[
t('bulkImport.features.autoMap'),
t('bulkImport.features.examples'),
t('bulkImport.features.formats'),
]}
maxRowsHint={2000}
onPreview={async (_file, preMapped) => {
const res = await previewMallImportApi(customerCode, mapMallImportRows(preMapped));
const data = res.data;
return {
rowCount: data.total,
willCreate: data.will_create,
willSkip: data.will_skip,
willFail: data.will_fail,
sampleCreates: data.sample_creates,
errors: data.errors,
};
}}
onImport={async (_file, preMapped) => {
const res = await importMallRowsApi(customerCode, mapMallImportRows(preMapped));
const data = res.data;
return {
success: data.created,
skipped: data.skipped,
failed: data.failed,
errors: data.errors,
};
}}
smartImport={{
importType: 'mall_product',
fields: MALL_IMPORT_FIELD_DICT,
preferredSheetNames: ['商城商品'],
requiredHeaderHints: ['商品编码'],
}}
onComplete={() => {
setImportOpen(false);
void loadLibrary();
}}
/>
) : null}
</div>
);
};
export default MallManagement;
+79
View File
@@ -0,0 +1,79 @@
import { downloadExcelTemplate, getCell } from './excelImportExport';
import type { ImportFieldDef } from './smartColumnMapping';
import type { MallImportRow } from './workflowApi';
/**
* 商城管理 · 客户商品库导入(2026-10-29)
*
* 只导入「商品编码 + 可选展示字段」:商品档案本身必须在「商品管理」里已存在,
* 本导入不新建商品档案、不写价格。
*/
export const MALL_IMPORT_HEADERS = ['商品编码*', '客户商品名', '单位', '收藏'];
export const MALL_IMPORT_EXAMPLES: (string | number)[][] = [['SKU00000001', '客户叫法', '斤', '是']];
export const MALL_IMPORT_FIELD_DICT: ImportFieldDef[] = [
{
key: 'skuCode',
label: '商品编码',
required: true,
templateHeader: '商品编码*',
aliases: ['商品编码', '商品代码', '商品编号', 'sku编码', 'sku'],
patterns: [/商品.*(编码|代码|编号)|sku/i],
},
{
key: 'customerSkuName',
label: '客户商品名',
templateHeader: '客户商品名',
aliases: ['客户商品名', '商品名称', '品名', '客户叫法', '名称'],
patterns: [/客户.*名|商品名|品名/],
},
{
key: 'customerUnit',
label: '单位',
templateHeader: '单位',
aliases: ['单位', 'unit'],
patterns: [/单位|unit/i],
},
{
key: 'isFavorite',
label: '收藏',
templateHeader: '收藏',
aliases: ['收藏', '常用', 'is_favorite'],
patterns: [/收藏|常用/],
},
];
export async function downloadMallImportTemplate() {
await downloadExcelTemplate(
'商城商品导入模板.xlsx',
'商城商品',
MALL_IMPORT_HEADERS,
MALL_IMPORT_EXAMPLES,
[
{
name: '填写说明',
headers: ['字段', '说明'],
rows: [
['商品编码*', '必填,必须是本分公司已启用的商品档案编码(sku_code)'],
['客户商品名', '选填,不填则用商品档案名'],
['单位', '选填,不填则用商品档案单位'],
['收藏', '选填,填「是」则该商品排到商城前面'],
],
},
]
);
}
/** 把智能映射后的行转成接口载荷(键为模板表头) */
export function mapMallImportRows(rows?: Record<string, string>[]): MallImportRow[] {
return (rows || [])
.map((row) => ({
sku_code: getCell(row, '商品编码*', '商品编码', '商品代码', '商品编号').trim(),
customer_sku_name: getCell(row, '客户商品名', '商品名称', '品名').trim(),
customer_unit: getCell(row, '单位').trim(),
is_favorite: getCell(row, '收藏', '常用').trim(),
}))
.filter((row) => Boolean(row.sku_code));
}
+86 -2
View File
@@ -6086,6 +6086,90 @@ export async function listCustomerRecipientsApi(customerCode: string) {
}> }>(`/customers/${encodeURIComponent(customerCode)}/recipients`);
}
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;
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;
};
export type MallImportRow = {
sku_code: string;
customer_sku_name: string;
customer_unit: string;
is_favorite: string;
};
export type MallCatalogSku = {
sku_code: string;
sku_name: string;
spec: string | null;
unit: string | null;
category_code: string | null;
category_name: string | null;
image_url: string | null;
};
export async function fetchMallLibraryApi(customerCode: string) {
return workflowFetch<{ data: {
customer: { customer_code: string; company_name: string; branch_code: string | null };
items: MallLibraryItem[];
summary: Record<MallLibraryStatus, number> & { total: number };
} }>(`/customers/${encodeURIComponent(customerCode)}/mall-products`);
}
export async function searchMallCatalogApi(customerCode: string, q = '') {
return workflowFetch<{ data: MallCatalogSku[] }>(
`/customers/${encodeURIComponent(customerCode)}/mall-catalog?q=${encodeURIComponent(q)}`
);
}
export async function addMallLibrarySkusApi(customerCode: string, skuCodes: string[]) {
return workflowFetch<{ data: { added: number; skipped: number; unknown: string[] } }>(
`/customers/${encodeURIComponent(customerCode)}/mall-products`,
{ method: 'POST', body: JSON.stringify({ sku_codes: skuCodes }) }
);
}
export async function updateMallLibraryItemApi(customerCode: string, skuCode: string, body: Record<string, unknown>) {
return workflowFetch<{ data: unknown }>(
`/customers/${encodeURIComponent(customerCode)}/mall-products/${encodeURIComponent(skuCode)}`,
{ method: 'PATCH', body: JSON.stringify(body) }
);
}
export async function removeMallLibrarySkuApi(customerCode: string, skuCode: string) {
return workflowFetch<{ data: { removed: boolean } }>(
`/customers/${encodeURIComponent(customerCode)}/mall-products/${encodeURIComponent(skuCode)}`,
{ method: 'DELETE' }
);
}
export async function previewMallImportApi(customerCode: string, rows: unknown[]) {
return workflowFetch<{ data: {
total: number; will_create: number; will_skip: number; will_fail: number;
duplicates: number; sample_creates: string[]; errors: string[];
} }>(`/customers/${encodeURIComponent(customerCode)}/mall-products/import`, {
method: 'POST', body: JSON.stringify({ dry_run: true, rows }),
});
}
export async function importMallRowsApi(customerCode: string, rows: unknown[]) {
return workflowFetch<{ data: {
created: number; skipped: number; failed: number; duplicates: number; errors: string[];
} }>(`/customers/${encodeURIComponent(customerCode)}/mall-products/import`, {
method: 'POST', body: JSON.stringify({ rows }),
});
}
export async function createCustomerRecipientApi(body: Record<string, unknown>) {
return workflowFetch<{ data: unknown }>('/customers/recipients', { method: 'POST', body: JSON.stringify(body) });
}
@@ -7011,7 +7095,7 @@ export async function setAllocationRulesApi(rules: Partial<AllocationRules>) {
/** 免模板智能导入:读取表头映射记忆 */
export async function getImportMappingMemoryApi(
importType: 'sku' | 'category' | 'quote' | 'customer' | 'supplier',
importType: 'sku' | 'category' | 'quote' | 'customer' | 'supplier' | 'mall_product',
signature: string
) {
const query = new URLSearchParams({ signature, _ts: String(Date.now()) });
@@ -7022,7 +7106,7 @@ export async function getImportMappingMemoryApi(
/** 免模板智能导入:保存表头映射记忆 */
export async function saveImportMappingMemoryApi(
importType: 'sku' | 'category' | 'quote' | 'customer' | 'supplier',
importType: 'sku' | 'category' | 'quote' | 'customer' | 'supplier' | 'mall_product',
body: { signature: string; mapping: Record<string, string>; source_headers: string[] }
) {
return workflowFetch<{ ok: boolean }>(`/import-mappings/${importType}`, {