@@ -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 ,
} ;
}