1012 lines
33 KiB
JavaScript
1012 lines
33 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
|
||
/**
|
||
* 将输入值转换为有限数字。
|
||
*
|
||
* @param {unknown} value 待转换的值。
|
||
* @param {number} [defaultValue=0] 默认值。
|
||
* @return {number} 转换后的数字。
|
||
*/
|
||
function toNumber(value, defaultValue = 0) {
|
||
const normalized = Number(value);
|
||
return Number.isFinite(normalized) ? normalized : defaultValue;
|
||
}
|
||
|
||
/**
|
||
* 组合商品业务逻辑服务层。
|
||
* 负责组合商品的 CRUD、搜索、校验等核心业务逻辑。
|
||
*/
|
||
class ComboGoodsService extends Service {
|
||
// ---------- 公共辅助方法 ----------
|
||
|
||
/**
|
||
* 通过 stock_id 批量查询 wms_stock_warehouse,返回 Map 结构。
|
||
*
|
||
* @param {number[]} stockIds stock_id 数组。
|
||
* @return {Promise<Map<number, Object>>} stockId → { id, item_name, store_id, item_code } 的映射。
|
||
*/
|
||
async fetchStockInfoMap(stockIds) {
|
||
const { ctx, app } = this;
|
||
const { Op } = app.Sequelize;
|
||
const uniqueIds = [ ...new Set(stockIds.filter(id => toNumber(id) > 0)) ];
|
||
|
||
if (uniqueIds.length === 0) {
|
||
return new Map();
|
||
}
|
||
|
||
const rows = await ctx.model.StockWarehouse.findAll({
|
||
where: {
|
||
id: { [Op.in]: uniqueIds },
|
||
},
|
||
attributes: [ 'id', 'item_name', 'store_id', 'item_code' ],
|
||
raw: true,
|
||
});
|
||
|
||
const map = new Map();
|
||
for (const row of Array.isArray(rows) ? rows : []) {
|
||
const stockId = toNumber(row.id);
|
||
if (stockId > 0) {
|
||
map.set(stockId, {
|
||
id: stockId,
|
||
item_name: String(row.item_name || ''),
|
||
store_id: toNumber(row.store_id),
|
||
item_code: String(row.item_code || ''),
|
||
});
|
||
}
|
||
}
|
||
return map;
|
||
}
|
||
|
||
/**
|
||
* 构建字符串简记(格式:stock_id|数量,stock_id2|数量)。
|
||
*
|
||
* @param {Object[]} items 明细数组,每项包含 item_goods_sku_id 与 item_quantity。
|
||
* @return {string} 字符串简记。
|
||
*/
|
||
buildSimpleNotation(items) {
|
||
if (!Array.isArray(items) || items.length === 0) {
|
||
return '';
|
||
}
|
||
return items
|
||
.map(item => `${toNumber(item.item_goods_sku_id)}|${toNumber(item.item_quantity)}`)
|
||
.join(',');
|
||
}
|
||
|
||
/**
|
||
* 构建商品名称简记(格式:【数量】商品名称+【数量】商品名称)。
|
||
*
|
||
* @param {Object[]} items 明细数组,每项包含 item_goods_sku_id 与 item_quantity。
|
||
* @param {Map<number, Object>} stockInfoMap stockId → { item_name } 的映射。
|
||
* @return {string} 商品名称简记。
|
||
*/
|
||
buildNameNotation(items, stockInfoMap) {
|
||
if (!Array.isArray(items) || items.length === 0) {
|
||
return '';
|
||
}
|
||
return items
|
||
.map(item => {
|
||
const stockId = toNumber(item.item_goods_sku_id);
|
||
const qty = toNumber(item.item_quantity);
|
||
const stockInfo = stockInfoMap.get(stockId);
|
||
const name = stockInfo ? stockInfo.item_name : `SKU#${stockId}`;
|
||
return `【${qty}】${name}`;
|
||
})
|
||
.join('+');
|
||
}
|
||
|
||
/**
|
||
* 校验子商品的有效性(必须存在于 wms_stock_warehouse、状态正常、未删除)。
|
||
*
|
||
* @param {number[]} stockIds 待校验的 stock_id 数组。
|
||
* @return {Promise<Object>} 校验结果,{ ok: boolean, message?: string, stockInfoMap?: Map }。
|
||
*/
|
||
async validateItems(stockIds) {
|
||
const { ctx, app } = this;
|
||
const { Op } = app.Sequelize;
|
||
const uniqueIds = [ ...new Set(stockIds.filter(id => toNumber(id) > 0)) ];
|
||
|
||
if (uniqueIds.length === 0) {
|
||
return { ok: false, message: '子商品列表不能为空' };
|
||
}
|
||
|
||
const rows = await ctx.model.StockWarehouse.findAll({
|
||
where: {
|
||
id: { [Op.in]: uniqueIds },
|
||
is_valid: 'Y',
|
||
deleted_at: null,
|
||
},
|
||
attributes: [ 'id', 'item_name', 'store_id', 'item_code' ],
|
||
raw: true,
|
||
});
|
||
|
||
const validMap = new Map();
|
||
for (const row of Array.isArray(rows) ? rows : []) {
|
||
validMap.set(toNumber(row.id), {
|
||
id: toNumber(row.id),
|
||
item_name: String(row.item_name || ''),
|
||
store_id: toNumber(row.store_id),
|
||
item_code: String(row.item_code || ''),
|
||
});
|
||
}
|
||
|
||
// 找出哪些 stock_id 不在有效列表中
|
||
const invalidIds = uniqueIds.filter(id => !validMap.has(id));
|
||
if (invalidIds.length > 0) {
|
||
return { ok: false, message: `以下子商品不存在或已停用:${invalidIds.join(', ')}` };
|
||
}
|
||
|
||
// 校验是否所有子商品属于同一个货主(owner_id / store_id)
|
||
const ownerIds = new Set();
|
||
for (const [ , info ] of validMap) {
|
||
ownerIds.add(info.store_id);
|
||
}
|
||
if (ownerIds.size > 1) {
|
||
return { ok: false, message: '所有子商品必须属于同一个货主,不允许跨货主组合' };
|
||
}
|
||
|
||
return { ok: true, stockInfoMap: validMap };
|
||
}
|
||
|
||
/**
|
||
* 从 stockInfoMap 中提取 targetStoreId。
|
||
*
|
||
* @param {Map<number, Object>} stockInfoMap stockId → { store_id } 的映射。
|
||
* @return {number} 目标货主ID,如果无法确定则返回 0。
|
||
*/
|
||
getTargetStoreIdFromMap(stockInfoMap) {
|
||
if (!stockInfoMap || stockInfoMap.size === 0) {
|
||
return 0;
|
||
}
|
||
const storeIds = new Set();
|
||
for (const [ , info ] of stockInfoMap) {
|
||
storeIds.add(info.store_id);
|
||
}
|
||
if (storeIds.size !== 1) {
|
||
return 0;
|
||
}
|
||
return storeIds.values().next().value;
|
||
}
|
||
|
||
/**
|
||
* 自定义编码货主唯一性校验(创建时)。
|
||
* 通过 items 反查 store_id,再查询是否存在相同 custom_code + 同货主的非删除记录。
|
||
*
|
||
* @param {string} customCode 自定义编码。
|
||
* @param {Map<number, Object>} stockInfoMap 当前 items 的 stockId → { store_id } 映射。
|
||
* @throws {Error} 如果自定义编码在同一货主内已存在。
|
||
*/
|
||
async checkCustomCodeUniqueForCreate(customCode, stockInfoMap) {
|
||
const { ctx } = this;
|
||
const targetStoreId = this.getTargetStoreIdFromMap(stockInfoMap);
|
||
if (targetStoreId <= 0) {
|
||
return; // 无法确定货主,跳过校验
|
||
}
|
||
|
||
// 查出所有 status != 0 且 custom_code 相同的 combo_id
|
||
const sameCodeRows = await ctx.model.query(
|
||
`SELECT id FROM wms_combo_goods
|
||
WHERE custom_code = :customCode AND status != 0`,
|
||
{
|
||
replacements: { customCode },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
}
|
||
);
|
||
|
||
if (!Array.isArray(sameCodeRows) || sameCodeRows.length === 0) {
|
||
return; // 无重复
|
||
}
|
||
|
||
const conflictComboIds = sameCodeRows.map(r => toNumber(r.id)).filter(id => id > 0);
|
||
if (conflictComboIds.length === 0) {
|
||
return;
|
||
}
|
||
|
||
// 查这些 combo_id 的子商品对应的 stock_id
|
||
const conflictItemRows = await ctx.model.query(
|
||
`SELECT DISTINCT cgi.item_goods_sku_id
|
||
FROM wms_combo_goods_item cgi
|
||
WHERE cgi.combo_id IN (:comboIds)`,
|
||
{
|
||
replacements: { comboIds: conflictComboIds },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
}
|
||
);
|
||
|
||
if (!Array.isArray(conflictItemRows) || conflictItemRows.length === 0) {
|
||
return;
|
||
}
|
||
|
||
const conflictStockIds = conflictItemRows
|
||
.map(r => toNumber(r.item_goods_sku_id))
|
||
.filter(id => id > 0);
|
||
|
||
if (conflictStockIds.length === 0) {
|
||
return;
|
||
}
|
||
|
||
// 查出这些 stock_id 对应的 store_id
|
||
const { Op } = ctx.app.Sequelize;
|
||
const conflictStocks = await ctx.model.StockWarehouse.findAll({
|
||
where: { id: { [Op.in]: conflictStockIds } },
|
||
attributes: [ 'store_id' ],
|
||
raw: true,
|
||
});
|
||
|
||
const conflictStoreIds = new Set();
|
||
for (const row of (Array.isArray(conflictStocks) ? conflictStocks : [])) {
|
||
conflictStoreIds.add(toNumber(row.store_id));
|
||
}
|
||
|
||
if (conflictStoreIds.has(targetStoreId)) {
|
||
throw new Error('自定义编码已存在');
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 自定义编码货主唯一性校验(更新时,排除自身 id)。
|
||
* 通过已有子商品反查 store_id,再查询是否存在相同 custom_code + 同货主的非删除记录(排除自身)。
|
||
*
|
||
* @param {string} customCode 自定义编码。
|
||
* @param {number} comboId 当前组合商品ID(排除自身)。
|
||
* @param {Object|null} itemValidation 如已做过 validateItems,传入结果复用 stockInfoMap。
|
||
* @throws {Error} 如果自定义编码在同一货主内已存在。
|
||
*/
|
||
async checkCustomCodeUniqueForUpdate(customCode, comboId, itemValidation) {
|
||
const { ctx } = this;
|
||
let targetStoreId = 0;
|
||
|
||
// 优先使用传入的 itemValidation 中的 stockInfoMap
|
||
if (itemValidation && itemValidation.ok && itemValidation.stockInfoMap) {
|
||
targetStoreId = this.getTargetStoreIdFromMap(itemValidation.stockInfoMap);
|
||
}
|
||
|
||
// 如果无法从传入 items 确定货主,则从已有子商品反查
|
||
if (targetStoreId <= 0) {
|
||
const existingItems = await ctx.model.query(
|
||
`SELECT cgi.item_goods_sku_id
|
||
FROM wms_combo_goods_item cgi
|
||
WHERE cgi.combo_id = :comboId`,
|
||
{
|
||
replacements: { comboId },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
}
|
||
);
|
||
|
||
if (Array.isArray(existingItems) && existingItems.length > 0) {
|
||
const stockIds = existingItems
|
||
.map(r => toNumber(r.item_goods_sku_id))
|
||
.filter(id => id > 0);
|
||
if (stockIds.length > 0) {
|
||
const stockInfoMap = await this.fetchStockInfoMap(stockIds);
|
||
targetStoreId = this.getTargetStoreIdFromMap(stockInfoMap);
|
||
}
|
||
}
|
||
}
|
||
|
||
if (targetStoreId <= 0) {
|
||
return; // 无法确定货主,跳过校验
|
||
}
|
||
|
||
// 查出所有 status != 0 且 custom_code 相同且 id != comboId 的记录
|
||
const sameCodeRows = await ctx.model.query(
|
||
`SELECT id FROM wms_combo_goods
|
||
WHERE custom_code = :customCode AND status != 0 AND id != :comboId`,
|
||
{
|
||
replacements: { customCode, comboId },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
}
|
||
);
|
||
|
||
if (!Array.isArray(sameCodeRows) || sameCodeRows.length === 0) {
|
||
return; // 无重复
|
||
}
|
||
|
||
const conflictComboIds = sameCodeRows.map(r => toNumber(r.id)).filter(id => id > 0);
|
||
if (conflictComboIds.length === 0) {
|
||
return;
|
||
}
|
||
|
||
// 查这些冲突 combo_id 的子商品对应的 store_id
|
||
const conflictItemRows = await ctx.model.query(
|
||
`SELECT DISTINCT cgi.item_goods_sku_id
|
||
FROM wms_combo_goods_item cgi
|
||
WHERE cgi.combo_id IN (:comboIds)`,
|
||
{
|
||
replacements: { comboIds: conflictComboIds },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
}
|
||
);
|
||
|
||
if (!Array.isArray(conflictItemRows) || conflictItemRows.length === 0) {
|
||
return;
|
||
}
|
||
|
||
const conflictStockIds = conflictItemRows
|
||
.map(r => toNumber(r.item_goods_sku_id))
|
||
.filter(id => id > 0);
|
||
|
||
if (conflictStockIds.length === 0) {
|
||
return;
|
||
}
|
||
|
||
const { Op } = ctx.app.Sequelize;
|
||
const conflictStocks = await ctx.model.StockWarehouse.findAll({
|
||
where: { id: { [Op.in]: conflictStockIds } },
|
||
attributes: [ 'store_id' ],
|
||
raw: true,
|
||
});
|
||
|
||
const conflictStoreIds = new Set();
|
||
for (const row of (Array.isArray(conflictStocks) ? conflictStocks : [])) {
|
||
conflictStoreIds.add(toNumber(row.store_id));
|
||
}
|
||
|
||
if (conflictStoreIds.has(targetStoreId)) {
|
||
throw new Error('自定义编码已存在');
|
||
}
|
||
}
|
||
|
||
// ---------- 1. 列表查询 ----------
|
||
|
||
/**
|
||
* 组合商品列表查询(分页)。
|
||
*
|
||
* @param {Object} options 查询选项。
|
||
* @param {number} [options.page=1] 页码。
|
||
* @param {number} [options.pageSize=20] 每页大小。
|
||
* @param {string} [options.combo_code] 组合商品编码筛选。
|
||
* @param {string} [options.combo_name] 组合商品名称筛选(模糊)。
|
||
* @param {number} [options.status] 状态筛选。
|
||
* @param {number} [options.warehouse_id] 仓库ID筛选。
|
||
* @return {Promise<Object>} 分页列表结果。
|
||
*/
|
||
async list(options = {}) {
|
||
const { ctx } = this;
|
||
const page = Math.max(1, toNumber(options.page, 1));
|
||
const pageSize = Math.min(200, Math.max(1, toNumber(options.pageSize, 20)));
|
||
|
||
// 构建 where 子句与 replacements
|
||
const { whereClause, replacements } = this.buildListWhere(options);
|
||
|
||
// 查询总数
|
||
const countSql = `SELECT COUNT(*) AS cnt FROM wms_combo_goods WHERE ${whereClause}`;
|
||
const countRows = await ctx.model.query(countSql, {
|
||
replacements,
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
});
|
||
const total = toNumber(countRows && countRows[0] && countRows[0].cnt, 0);
|
||
|
||
// 查询主表分页数据
|
||
const offset = (page - 1) * pageSize;
|
||
const listSql = `SELECT * FROM wms_combo_goods WHERE ${whereClause}
|
||
ORDER BY id DESC LIMIT ${offset}, ${pageSize}`;
|
||
const mainRows = await ctx.model.query(listSql, {
|
||
replacements,
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
});
|
||
|
||
const list = Array.isArray(mainRows) ? mainRows : [];
|
||
|
||
if (list.length === 0) {
|
||
return { list: [], total, page, pageSize };
|
||
}
|
||
|
||
// 批量查询明细
|
||
const comboIds = list.map(row => toNumber(row.id)).filter(id => id > 0);
|
||
const itemRows = comboIds.length > 0
|
||
? await ctx.model.query(
|
||
'SELECT * FROM wms_combo_goods_item WHERE combo_id IN (:comboIds) ORDER BY sort_order ASC, id ASC',
|
||
{
|
||
replacements: { comboIds },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
}
|
||
)
|
||
: [];
|
||
|
||
// 按 combo_id 分组明细
|
||
const itemsByComboId = new Map();
|
||
for (const item of Array.isArray(itemRows) ? itemRows : []) {
|
||
const comboId = toNumber(item.combo_id);
|
||
if (!itemsByComboId.has(comboId)) {
|
||
itemsByComboId.set(comboId, []);
|
||
}
|
||
itemsByComboId.get(comboId).push({
|
||
id: toNumber(item.id),
|
||
combo_id: comboId,
|
||
item_goods_sku_id: toNumber(item.item_goods_sku_id),
|
||
item_quantity: toNumber(item.item_quantity),
|
||
sort_order: toNumber(item.sort_order),
|
||
});
|
||
}
|
||
|
||
// 收集所有 stock_id 以批量获取商品名称
|
||
const allStockIds = [];
|
||
for (const [ , items ] of itemsByComboId) {
|
||
for (const item of items) {
|
||
allStockIds.push(item.item_goods_sku_id);
|
||
}
|
||
}
|
||
const stockInfoMap = await this.fetchStockInfoMap(allStockIds);
|
||
|
||
// 组装最终列表
|
||
const resultList = list.map(row => {
|
||
const comboId = toNumber(row.id);
|
||
const items = itemsByComboId.get(comboId) || [];
|
||
return {
|
||
id: comboId,
|
||
combo_code: String(row.combo_code || ''),
|
||
combo_name: String(row.combo_name || ''),
|
||
combo_sku_id: toNumber(row.combo_sku_id),
|
||
custom_code: row.custom_code || null,
|
||
status: toNumber(row.status),
|
||
warehouse_id: toNumber(row.warehouse_id),
|
||
remark: String(row.remark || ''),
|
||
creator_id: toNumber(row.creator_id),
|
||
editor_id: toNumber(row.editor_id),
|
||
created_at: row.created_at,
|
||
updated_at: row.updated_at,
|
||
items,
|
||
simpleNotation: this.buildSimpleNotation(items),
|
||
nameNotation: this.buildNameNotation(items, stockInfoMap),
|
||
};
|
||
});
|
||
|
||
return { list: resultList, total, page, pageSize };
|
||
}
|
||
|
||
/**
|
||
* 为列表查询构建参数化的 WHERE 子句。
|
||
*
|
||
* @param {Object} options 查询选项。
|
||
* @return {Object} 包含 whereClause(string)与 replacements(Object)的对象。
|
||
*/
|
||
buildListWhere(options) {
|
||
const clauses = [];
|
||
const replacements = {};
|
||
|
||
if (options.combo_code) {
|
||
clauses.push('combo_code = :comboCode');
|
||
replacements.comboCode = String(options.combo_code).trim();
|
||
}
|
||
if (options.combo_name) {
|
||
clauses.push('combo_name LIKE :comboName');
|
||
replacements.comboName = `%${String(options.combo_name).trim()}%`;
|
||
}
|
||
if (options.status !== undefined && options.status !== null && options.status !== '') {
|
||
clauses.push('status = :status');
|
||
replacements.status = toNumber(options.status);
|
||
}
|
||
if (options.warehouse_id !== undefined && options.warehouse_id !== null && options.warehouse_id !== '') {
|
||
clauses.push('warehouse_id = :warehouseId');
|
||
replacements.warehouseId = toNumber(options.warehouse_id);
|
||
}
|
||
|
||
return {
|
||
whereClause: clauses.length > 0 ? clauses.join(' AND ') : '1=1',
|
||
replacements,
|
||
};
|
||
}
|
||
|
||
// ---------- 2. 创建组合商品 ----------
|
||
|
||
/**
|
||
* 创建组合商品(含明细),使用事务保证原子性。
|
||
*
|
||
* @param {Object} options 创建参数。
|
||
* @param {string} options.combo_code 组合商品编码。
|
||
* @param {string} options.combo_name 组合商品名称。
|
||
* @param {number} [options.warehouse_id] 仓库ID。
|
||
* @param {string} [options.remark] 备注。
|
||
* @param {string} [options.custom_code] 自定义编码。
|
||
* @param {Object[]} options.items 子商品明细数组 [{item_goods_sku_id, item_quantity}]。
|
||
* @param {number} [options.creator_id] 创建人ID。
|
||
* @return {Promise<Object>} 创建结果,包含 id、combo_code、combo_name、custom_code。
|
||
*/
|
||
async create(options = {}) {
|
||
const { ctx } = this;
|
||
const { combo_code, combo_name, items } = options;
|
||
const warehouseId = toNumber(options.warehouse_id);
|
||
const remark = String(options.remark || '');
|
||
const customCode = options.custom_code ? String(options.custom_code).trim() : '';
|
||
const creatorId = toNumber(options.creator_id || ctx.user?.id || 0);
|
||
|
||
// 参数基础校验
|
||
if (!combo_code || !String(combo_code).trim()) {
|
||
throw new Error('组合商品编码不能为空');
|
||
}
|
||
if (!combo_name || !String(combo_name).trim()) {
|
||
throw new Error('组合商品名称不能为空');
|
||
}
|
||
if (!Array.isArray(items) || items.length === 0) {
|
||
throw new Error('子商品列表不能为空');
|
||
}
|
||
|
||
const trimmedCode = String(combo_code).trim();
|
||
const trimmedName = String(combo_name).trim();
|
||
|
||
// 唯一性校验
|
||
const existing = await ctx.model.query(
|
||
'SELECT id FROM wms_combo_goods WHERE combo_code = :comboCode LIMIT 1',
|
||
{
|
||
replacements: { comboCode: trimmedCode },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
}
|
||
);
|
||
if (Array.isArray(existing) && existing.length > 0) {
|
||
throw new Error(`组合商品编码 "${trimmedCode}" 已存在`);
|
||
}
|
||
|
||
// 子商品有效性校验
|
||
const stockIds = items.map(item => toNumber(item.item_goods_sku_id)).filter(id => id > 0);
|
||
const validation = await this.validateItems(stockIds);
|
||
if (!validation.ok) {
|
||
throw new Error(validation.message);
|
||
}
|
||
|
||
// 自定义编码货主唯一性校验
|
||
if (customCode) {
|
||
await this.checkCustomCodeUniqueForCreate(customCode, validation.stockInfoMap);
|
||
}
|
||
|
||
// 事务写入
|
||
const transaction = await ctx.model.transaction();
|
||
|
||
try {
|
||
// 插入主表
|
||
const insertResult = await ctx.model.query(
|
||
`INSERT INTO wms_combo_goods (combo_code, combo_name, warehouse_id, remark, custom_code, status, creator_id, editor_id)
|
||
VALUES (:comboCode, :comboName, :warehouseId, :remark, :customCode, 1, :creatorId, :creatorId)`,
|
||
{
|
||
replacements: {
|
||
comboCode: trimmedCode,
|
||
comboName: trimmedName,
|
||
warehouseId: warehouseId > 0 ? warehouseId : null,
|
||
remark,
|
||
customCode: customCode || null,
|
||
creatorId: creatorId > 0 ? creatorId : null,
|
||
},
|
||
transaction,
|
||
}
|
||
);
|
||
|
||
const insertHead = Array.isArray(insertResult) ? insertResult[0] : null;
|
||
const comboId = toNumber(
|
||
(typeof insertHead === 'number' && insertHead > 0) ? insertHead
|
||
: (insertHead && (insertHead.insertId || insertHead.lastID || insertHead.id))
|
||
|| (insertResult && insertResult.insertId)
|
||
|| 0
|
||
);
|
||
if (comboId <= 0) {
|
||
throw new Error('创建组合商品主记录失败');
|
||
}
|
||
|
||
// 批量插入明细
|
||
if (items.length > 0) {
|
||
const itemValues = items.map((item, index) => {
|
||
const skuId = toNumber(item.item_goods_sku_id);
|
||
const qty = Math.max(1, toNumber(item.item_quantity, 1));
|
||
const sortOrder = toNumber(item.sort_order, index);
|
||
return `(${comboId}, ${skuId}, ${qty}, ${sortOrder})`;
|
||
}).join(', ');
|
||
|
||
await ctx.model.query(
|
||
`INSERT INTO wms_combo_goods_item (combo_id, item_goods_sku_id, item_quantity, sort_order) VALUES ${itemValues}`,
|
||
{ transaction }
|
||
);
|
||
}
|
||
|
||
await transaction.commit();
|
||
|
||
return {
|
||
id: comboId,
|
||
combo_code: trimmedCode,
|
||
combo_name: trimmedName,
|
||
custom_code: customCode || null,
|
||
};
|
||
} catch (error) {
|
||
await transaction.rollback();
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
// ---------- 3. 编辑组合商品 ----------
|
||
|
||
/**
|
||
* 编辑组合商品(含明细替换),使用事务保证原子性。
|
||
*
|
||
* @param {Object} options 编辑参数。
|
||
* @param {number} options.id 组合商品ID。
|
||
* @param {string} [options.combo_name] 组合商品名称。
|
||
* @param {number} [options.warehouse_id] 仓库ID。
|
||
* @param {string} [options.remark] 备注。
|
||
* @param {string} [options.custom_code] 自定义编码。
|
||
* @param {number} [options.status] 状态 1-启用 0-停用。
|
||
* @param {Object[]} [options.items] 子商品明细数组。
|
||
* @param {number} [options.editor_id] 编辑人ID。
|
||
* @return {Promise<Object>} 编辑结果,包含 id。
|
||
*/
|
||
async update(options = {}) {
|
||
const { ctx } = this;
|
||
const comboId = toNumber(options.id);
|
||
const editorId = toNumber(options.editor_id || ctx.user?.id || 0);
|
||
|
||
if (comboId <= 0) {
|
||
throw new Error('组合商品ID不能为空');
|
||
}
|
||
|
||
// 校验记录是否存在
|
||
const existingRows = await ctx.model.query(
|
||
'SELECT id, combo_code, combo_name FROM wms_combo_goods WHERE id = :comboId LIMIT 1',
|
||
{
|
||
replacements: { comboId },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
}
|
||
);
|
||
if (!Array.isArray(existingRows) || existingRows.length === 0) {
|
||
throw new Error('组合商品不存在');
|
||
}
|
||
|
||
// 如果传入了 items,校验子商品有效性
|
||
const items = options.items;
|
||
let itemValidation = null;
|
||
if (items !== undefined && Array.isArray(items) && items.length > 0) {
|
||
const stockIds = items.map(item => toNumber(item.item_goods_sku_id)).filter(id => id > 0);
|
||
itemValidation = await this.validateItems(stockIds);
|
||
if (!itemValidation.ok) {
|
||
throw new Error(itemValidation.message);
|
||
}
|
||
}
|
||
|
||
// 构建主表更新 set 子句
|
||
const setClauses = [];
|
||
const replacements = { comboId };
|
||
if (options.combo_name !== undefined) {
|
||
const name = String(options.combo_name).trim();
|
||
if (!name) {
|
||
throw new Error('组合商品名称不能为空');
|
||
}
|
||
setClauses.push('combo_name = :comboName');
|
||
replacements.comboName = name;
|
||
}
|
||
if (options.warehouse_id !== undefined) {
|
||
const wid = toNumber(options.warehouse_id);
|
||
setClauses.push('warehouse_id = :warehouseId');
|
||
replacements.warehouseId = wid > 0 ? wid : null;
|
||
}
|
||
if (options.remark !== undefined) {
|
||
setClauses.push('remark = :remark');
|
||
replacements.remark = String(options.remark);
|
||
}
|
||
if (options.custom_code !== undefined) {
|
||
const customCode = options.custom_code ? String(options.custom_code).trim() : '';
|
||
setClauses.push('custom_code = :customCode');
|
||
replacements.customCode = customCode || null;
|
||
}
|
||
if (options.status !== undefined) {
|
||
const st = toNumber(options.status);
|
||
setClauses.push('status = :status');
|
||
replacements.status = st === 1 ? 1 : 0;
|
||
}
|
||
if (editorId > 0) {
|
||
setClauses.push('editor_id = :editorId');
|
||
replacements.editorId = editorId;
|
||
}
|
||
|
||
// 自定义编码货主唯一性校验(排除自身 id)
|
||
if (options.custom_code !== undefined && options.custom_code && String(options.custom_code).trim()) {
|
||
const customCode = String(options.custom_code).trim();
|
||
// 获取目标 store_id:优先从传入的 items 的 stockInfoMap 获取,否则查已有子商品
|
||
await this.checkCustomCodeUniqueForUpdate(customCode, comboId, itemValidation);
|
||
}
|
||
|
||
// 事务执行
|
||
const transaction = await ctx.model.transaction();
|
||
|
||
try {
|
||
// 更新主表
|
||
if (setClauses.length > 0) {
|
||
await ctx.model.query(
|
||
`UPDATE wms_combo_goods SET ${setClauses.join(', ')} WHERE id = :comboId`,
|
||
{ replacements, transaction }
|
||
);
|
||
}
|
||
|
||
// 如果传入了 items,先删旧明细再插入新明细
|
||
if (items !== undefined) {
|
||
await ctx.model.query(
|
||
'DELETE FROM wms_combo_goods_item WHERE combo_id = :comboId',
|
||
{ replacements: { comboId }, transaction }
|
||
);
|
||
|
||
if (Array.isArray(items) && items.length > 0) {
|
||
const itemValues = items.map((item, index) => {
|
||
const skuId = toNumber(item.item_goods_sku_id);
|
||
const qty = Math.max(1, toNumber(item.item_quantity, 1));
|
||
const sortOrder = toNumber(item.sort_order, index);
|
||
return `(${comboId}, ${skuId}, ${qty}, ${sortOrder})`;
|
||
}).join(', ');
|
||
|
||
await ctx.model.query(
|
||
`INSERT INTO wms_combo_goods_item (combo_id, item_goods_sku_id, item_quantity, sort_order) VALUES ${itemValues}`,
|
||
{ transaction }
|
||
);
|
||
}
|
||
}
|
||
|
||
await transaction.commit();
|
||
|
||
return { id: comboId };
|
||
} catch (error) {
|
||
await transaction.rollback();
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
// ---------- 4. 删除组合商品 ----------
|
||
|
||
/**
|
||
* 删除组合商品(软删除:status = 0)。
|
||
*
|
||
* @param {Object} options 删除参数。
|
||
* @param {number} options.id 组合商品ID。
|
||
* @return {Promise<Object>} 删除结果。
|
||
*/
|
||
async delete(options = {}) {
|
||
const { ctx } = this;
|
||
const comboId = toNumber(options.id);
|
||
|
||
if (comboId <= 0) {
|
||
throw new Error('组合商品ID不能为空');
|
||
}
|
||
|
||
// 校验记录是否存在
|
||
const existingRows = await ctx.model.query(
|
||
'SELECT id FROM wms_combo_goods WHERE id = :comboId LIMIT 1',
|
||
{
|
||
replacements: { comboId },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
}
|
||
);
|
||
if (!Array.isArray(existingRows) || existingRows.length === 0) {
|
||
throw new Error('组合商品不存在');
|
||
}
|
||
|
||
// 软删除:将 status 置为 0
|
||
await ctx.model.query(
|
||
'UPDATE wms_combo_goods SET status = 0 WHERE id = :comboId',
|
||
{
|
||
replacements: { comboId },
|
||
type: ctx.model.QueryTypes.UPDATE,
|
||
}
|
||
);
|
||
|
||
return { id: comboId };
|
||
}
|
||
|
||
// ---------- 5. 关键字搜索 ----------
|
||
|
||
/**
|
||
* 关键字搜索组合商品(模糊匹配 custom_code、combo_code 或 combo_name,自定义编码优先排序,限制返回条数)。
|
||
*
|
||
* @param {Object} options 搜索选项。
|
||
* @param {string} options.keyword 搜索关键字。
|
||
* @param {number} [options.limit=20] 最大返回条数。
|
||
* @return {Promise<Object>} 搜索结果列表。
|
||
*/
|
||
async search(options = {}) {
|
||
const { ctx } = this;
|
||
const keyword = String(options.keyword || '').trim();
|
||
const limit = Math.min(100, Math.max(1, toNumber(options.limit, 20)));
|
||
|
||
if (!keyword) {
|
||
return { list: [] };
|
||
}
|
||
|
||
const rows = await ctx.model.query(
|
||
`SELECT * FROM wms_combo_goods
|
||
WHERE status = 1
|
||
AND (custom_code LIKE :keywordLike
|
||
OR combo_code LIKE :keywordLike
|
||
OR combo_name LIKE :keywordLike)
|
||
ORDER BY (CASE WHEN custom_code LIKE :keywordLike THEN 0 ELSE 1 END) ASC,
|
||
id DESC
|
||
LIMIT :limit`,
|
||
{
|
||
replacements: {
|
||
keywordLike: `%${keyword}%`,
|
||
limit,
|
||
},
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
}
|
||
);
|
||
|
||
const list = Array.isArray(rows) ? rows : [];
|
||
|
||
if (list.length === 0) {
|
||
return { list: [] };
|
||
}
|
||
|
||
// 批量查询明细
|
||
const comboIds = list.map(row => toNumber(row.id)).filter(id => id > 0);
|
||
const itemRows = comboIds.length > 0
|
||
? await ctx.model.query(
|
||
'SELECT * FROM wms_combo_goods_item WHERE combo_id IN (:comboIds) ORDER BY sort_order ASC, id ASC',
|
||
{
|
||
replacements: { comboIds },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
}
|
||
)
|
||
: [];
|
||
|
||
const itemsByComboId = new Map();
|
||
for (const item of Array.isArray(itemRows) ? itemRows : []) {
|
||
const cid = toNumber(item.combo_id);
|
||
if (!itemsByComboId.has(cid)) {
|
||
itemsByComboId.set(cid, []);
|
||
}
|
||
itemsByComboId.get(cid).push({
|
||
id: toNumber(item.id),
|
||
combo_id: cid,
|
||
item_goods_sku_id: toNumber(item.item_goods_sku_id),
|
||
item_quantity: toNumber(item.item_quantity),
|
||
sort_order: toNumber(item.sort_order),
|
||
});
|
||
}
|
||
|
||
// 批量获取商品信息
|
||
const allStockIds = [];
|
||
for (const [ , items ] of itemsByComboId) {
|
||
for (const item of items) {
|
||
allStockIds.push(item.item_goods_sku_id);
|
||
}
|
||
}
|
||
const stockInfoMap = await this.fetchStockInfoMap(allStockIds);
|
||
|
||
const resultList = list.map(row => {
|
||
const cid = toNumber(row.id);
|
||
const items = itemsByComboId.get(cid) || [];
|
||
return {
|
||
id: cid,
|
||
combo_code: String(row.combo_code || ''),
|
||
combo_name: String(row.combo_name || ''),
|
||
combo_sku_id: toNumber(row.combo_sku_id),
|
||
custom_code: row.custom_code || null,
|
||
status: toNumber(row.status),
|
||
warehouse_id: toNumber(row.warehouse_id),
|
||
remark: String(row.remark || ''),
|
||
creator_id: toNumber(row.creator_id),
|
||
editor_id: toNumber(row.editor_id),
|
||
items,
|
||
simpleNotation: this.buildSimpleNotation(items),
|
||
nameNotation: this.buildNameNotation(items, stockInfoMap),
|
||
};
|
||
});
|
||
|
||
return { list: resultList };
|
||
}
|
||
|
||
/**
|
||
* 按 id 或 custom_code 搜索组合商品,返回含明细和简记字段的结果。
|
||
*
|
||
* @param {Object} options 查询选项
|
||
* @param {number} [options.id] 组合商品主键ID,精确查询单条
|
||
* @param {string} [options.custom_code] 自定义编码,模糊匹配
|
||
* @return {Promise<Object>} 包含 list 数组的结果对象,每条含 items、simpleNotation、nameNotation
|
||
*/
|
||
async searchByIdOrCode(options = {}) {
|
||
const { ctx } = this;
|
||
const comboId = toNumber(options.id);
|
||
const customCode = String(options.custom_code || '').trim();
|
||
|
||
// 优先按 id 精确查询
|
||
if (comboId > 0) {
|
||
const rows = await ctx.model.query(
|
||
'SELECT * FROM wms_combo_goods WHERE id = :id AND status = 1',
|
||
{
|
||
replacements: { id: comboId },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
}
|
||
);
|
||
const list = Array.isArray(rows) ? rows : [];
|
||
return this.enrichComboList(list);
|
||
}
|
||
|
||
// 按 custom_code 模糊查询
|
||
if (customCode) {
|
||
const sqlQuery = [
|
||
'SELECT * FROM wms_combo_goods',
|
||
'WHERE status = 1',
|
||
'AND custom_code LIKE :codeLike',
|
||
'ORDER BY id DESC',
|
||
'LIMIT 50',
|
||
].join(' ');
|
||
const rows = await ctx.model.query(
|
||
sqlQuery,
|
||
{
|
||
replacements: { codeLike: `%${customCode}%` },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
}
|
||
);
|
||
const list = Array.isArray(rows) ? rows : [];
|
||
return this.enrichComboList(list);
|
||
}
|
||
|
||
// 无有效查询条件时走通用搜索
|
||
return this.search({ keyword: '' });
|
||
}
|
||
|
||
/**
|
||
* 为组合商品列表批量填充子商品明细、simpleNotation 和 nameNotation。
|
||
*
|
||
* @param {Object[]} list 组合商品原始行数组
|
||
* @return {Promise<Object>} 包含 list 数组的富化结果
|
||
*/
|
||
async enrichComboList(list) {
|
||
if (list.length === 0) {
|
||
return { list: [] };
|
||
}
|
||
|
||
// 批量查询明细
|
||
const comboIds = list.map(row => toNumber(row.id)).filter(id => id > 0);
|
||
const itemRows = comboIds.length > 0
|
||
? await this.ctx.model.query(
|
||
'SELECT * FROM wms_combo_goods_item WHERE combo_id IN (:comboIds) ORDER BY sort_order ASC, id ASC',
|
||
{
|
||
replacements: { comboIds },
|
||
type: this.ctx.model.QueryTypes.SELECT,
|
||
}
|
||
)
|
||
: [];
|
||
|
||
const itemsByComboId = new Map();
|
||
for (const item of Array.isArray(itemRows) ? itemRows : []) {
|
||
const cid = toNumber(item.combo_id);
|
||
if (!itemsByComboId.has(cid)) {
|
||
itemsByComboId.set(cid, []);
|
||
}
|
||
itemsByComboId.get(cid).push({
|
||
id: toNumber(item.id),
|
||
combo_id: cid,
|
||
item_goods_sku_id: toNumber(item.item_goods_sku_id),
|
||
item_quantity: toNumber(item.item_quantity),
|
||
sort_order: toNumber(item.sort_order),
|
||
});
|
||
}
|
||
|
||
// 批量获取商品信息
|
||
const allStockIds = [];
|
||
for (const [ , items ] of itemsByComboId) {
|
||
for (const item of items) {
|
||
allStockIds.push(item.item_goods_sku_id);
|
||
}
|
||
}
|
||
const stockInfoMap = await this.fetchStockInfoMap(allStockIds);
|
||
|
||
const resultList = list.map(row => {
|
||
const cid = toNumber(row.id);
|
||
const items = itemsByComboId.get(cid) || [];
|
||
return {
|
||
id: cid,
|
||
combo_code: String(row.combo_code || ''),
|
||
combo_name: String(row.combo_name || ''),
|
||
combo_sku_id: toNumber(row.combo_sku_id),
|
||
custom_code: row.custom_code || null,
|
||
status: toNumber(row.status),
|
||
warehouse_id: toNumber(row.warehouse_id),
|
||
remark: String(row.remark || ''),
|
||
creator_id: toNumber(row.creator_id),
|
||
editor_id: toNumber(row.editor_id),
|
||
items,
|
||
simpleNotation: this.buildSimpleNotation(items),
|
||
nameNotation: this.buildNameNotation(items, stockInfoMap),
|
||
};
|
||
});
|
||
|
||
return { list: resultList };
|
||
}
|
||
}
|
||
|
||
module.exports = ComboGoodsService;
|