oms/backend/app/lib/attributeUsage.js
liufumingren d22f3e1f0a feat(backend): 新增商品分类/品牌/单位字典与属性菜单
- 按主体隔离的分类/品牌/单位 CRUD 与 /select 下拉接口
- 商品模型增加 brand_id / unit_id,属性被商品引用时禁止删除(attributeUsage)
- 迁移:建三张字典表、商品表加字段、种子属性菜单、is_system 保护内置项

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-30 23:06:09 +08:00

42 lines
1.6 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
/**
* 为商品属性(分类 / 品牌 / 单位)列表行附加「被商品使用次数(used_count)」。
* 用于前端判断该属性是否已被商品引用:被引用(used_count > 0)时禁止删除。
*
* 单次按 id 分组聚合(而非逐行查询),避免 N+1:
* 以商品表上引用该属性主键的字段(category_id / brand_id / unit_id)做 IN 聚合。
*
* 注意:按属性主键全局统计(不限定 principal_id)。原因:
* - 属性主键全局唯一,按 id 聚合天然准确;
* - 系统默认属性(is_system=1)可被任意主体商品引用,按当前主体统计会漏算。
*
* @param {Egg.Context} ctx egg context(需 principalCheck 已写入 ctx.state.principalId)
* @param {string} column 商品表上引用该属性主键的字段名
* @param {Array} rows 商品属性模型实例数组(findAndCountAll 的 rows)
* @return {Promise<Array>} 附加 used_count 的 plain 对象数组
*/
async function attachUsedCount(ctx, column, rows) {
const Op = ctx.app.Sequelize.Op;
const plain = rows.map(r => (r && r.toJSON ? r.toJSON() : r));
const ids = plain.map(r => Number(r.id)).filter(Boolean);
const usedMap = new Map();
if (ids.length) {
const records = await ctx.model.Product.findAll({
where: { [column]: { [Op.in]: ids } },
attributes: [ column ],
raw: true,
});
for (const rec of records) {
const key = Number(rec[column]);
usedMap.set(key, (usedMap.get(key) || 0) + 1);
}
}
return plain.map(r => ({ ...r, used_count: usedMap.get(Number(r.id)) || 0 }));
}
module.exports = { attachUsedCount };