- 按主体隔离的分类/品牌/单位 CRUD 与 /select 下拉接口 - 商品模型增加 brand_id / unit_id,属性被商品引用时禁止删除(attributeUsage) - 迁移:建三张字典表、商品表加字段、种子属性菜单、is_system 保护内置项 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
241 lines
8.3 KiB
JavaScript
241 lines
8.3 KiB
JavaScript
'use strict';
|
||
|
||
const { Controller } = require('egg');
|
||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||
|
||
/** 库存类型:与 product_stocks.item_type 对齐(ZC=正品 / CC=残次品) */
|
||
const STOCK_TYPE_CC = 'CC';
|
||
|
||
/** 无库存记录时的库存字段默认值 */
|
||
function emptyStockFields() {
|
||
return { zc_available: 0, zc_locked: 0, cc_available: 0, cc_locked: 0 };
|
||
}
|
||
|
||
/**
|
||
* 为商品附加库存字段(数据源为 product_stocks,按 item_type 聚合):
|
||
* - zc_available 正品可用 / zc_locked 正品锁定
|
||
* - cc_available 次品可用 / cc_locked 次品锁定
|
||
* @param {Object} ctx egg context
|
||
* @param {Number} principalId 所属主体ID
|
||
* @param {Array} products 商品 model 实例或 plain 对象数组
|
||
* @return {Promise<Array>} 附带库存字段的商品 plain 对象数组
|
||
*/
|
||
async function attachStockFields(ctx, principalId, products) {
|
||
const list = products.map(p => (p && p.toJSON ? p.toJSON() : p));
|
||
const productIds = list.map(p => Number(p.id)).filter(Boolean);
|
||
const stockMap = new Map();
|
||
|
||
if (productIds.length) {
|
||
const stocks = await ctx.model.ProductStock.findAll({
|
||
where: { principal_id: principalId, product_id: { [ctx.app.Sequelize.Op.in]: productIds } },
|
||
attributes: [ 'product_id', 'item_type', 'available', 'lock_quantity' ],
|
||
});
|
||
for (const s of stocks) {
|
||
const pid = Number(s.product_id);
|
||
const cur = stockMap.get(pid) || emptyStockFields();
|
||
if (s.item_type === STOCK_TYPE_CC) {
|
||
cur.cc_available = Number(s.available) || 0;
|
||
cur.cc_locked = Number(s.lock_quantity) || 0;
|
||
} else {
|
||
cur.zc_available = Number(s.available) || 0;
|
||
cur.zc_locked = Number(s.lock_quantity) || 0;
|
||
}
|
||
stockMap.set(pid, cur);
|
||
}
|
||
}
|
||
|
||
return list.map(p => ({ ...p, ...(stockMap.get(Number(p.id)) || emptyStockFields()) }));
|
||
}
|
||
|
||
/**
|
||
* @controller ProductController 商品管理
|
||
*/
|
||
class ProductController extends Controller {
|
||
/**
|
||
* @summary 商品列表
|
||
* @description 分页查询商品,支持按主体、关键词与状态过滤
|
||
* @router get /api/products
|
||
* @apikey
|
||
* @request query integer page 页码,默认 1
|
||
* @request query integer pageSize 每页条数,默认 20
|
||
* @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体)
|
||
* @request query string keyword 关键词,匹配商品编码或名称
|
||
* @request query string category_name 分类名称,精确匹配
|
||
* @request query string brand_name 品牌名称,精确匹配
|
||
* @request query string stock_unit 库存单位,精确匹配
|
||
* @request query integer status 状态:1上架 0下架,不传则不过滤
|
||
* @response 200 productListResponse success
|
||
*/
|
||
async index() {
|
||
const { ctx } = this;
|
||
const Op = this.app.Sequelize.Op;
|
||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||
const { keyword, category_name: categoryName, brand_name: brandName, stock_unit: stockUnit, status } = ctx.query;
|
||
const principalId = ctx.state.principalId;
|
||
|
||
const where = {};
|
||
where.principal_id = principalId;
|
||
if (keyword) {
|
||
where[Op.or] = [
|
||
{ item_code: { [Op.like]: `%${keyword}%` } },
|
||
{ goods_code: { [Op.like]: `%${keyword}%` } },
|
||
{ barcode: { [Op.like]: `%${keyword}%` } },
|
||
{ item_name: { [Op.like]: `%${keyword}%` } },
|
||
];
|
||
}
|
||
if (categoryName) where.category_name = categoryName;
|
||
if (brandName) where.brand_name = brandName;
|
||
if (stockUnit) where.stock_unit = stockUnit;
|
||
if (status !== undefined && status !== '') where.status = Number(status);
|
||
|
||
const { count, rows } = await ctx.model.Product.findAndCountAll({
|
||
where,
|
||
offset,
|
||
limit,
|
||
order: [[ 'id', 'DESC' ]],
|
||
});
|
||
|
||
// 附带库存字段(正品/次品的可用与锁定数量),取自 product_stocks
|
||
const list = await attachStockFields(ctx, principalId, rows);
|
||
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) };
|
||
}
|
||
|
||
/**
|
||
* @summary 商品详情
|
||
* @description 按主键查询商品
|
||
* @router get /api/products/{id}
|
||
* @apikey
|
||
* @request path integer *id 商品主键ID
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async show() {
|
||
const { ctx } = this;
|
||
const product = await ctx.model.Product.findByPk(ctx.params.id);
|
||
|
||
if (!product) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '商品不存在' };
|
||
return;
|
||
}
|
||
|
||
const [ data ] = await attachStockFields(ctx, product.principal_id, [ product ]);
|
||
ctx.body = { code: 0, message: 'success', data };
|
||
}
|
||
|
||
/**
|
||
* @summary 新增商品
|
||
* @description 同一主体下商品编码 item_code 唯一
|
||
* @router post /api/products
|
||
* @apikey
|
||
* @request body createProductRequest *body
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async create() {
|
||
const { ctx } = this;
|
||
const {
|
||
principal_id: principalId,
|
||
item_code: itemCode,
|
||
item_name: itemName,
|
||
retail_price: retailPrice,
|
||
} = ctx.request.body;
|
||
|
||
if (!principalId || !itemCode || !itemName || retailPrice === undefined) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: 'principal_id、item_code、item_name、retail_price 为必填项' };
|
||
return;
|
||
}
|
||
|
||
const exist = await ctx.model.Product.findOne({ where: { principal_id: principalId, item_code: itemCode } });
|
||
if (exist) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '该主体下商品编码已存在' };
|
||
return;
|
||
}
|
||
|
||
const product = await ctx.model.Product.create(ctx.request.body);
|
||
ctx.body = { code: 0, message: 'success', data: { id: product.id } };
|
||
}
|
||
|
||
/**
|
||
* @summary 更新商品
|
||
* @description 未传入的字段保持原值
|
||
* @router put /api/products/{id}
|
||
* @apikey
|
||
* @request path integer *id 商品主键ID
|
||
* @request body updateProductRequest *body
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async update() {
|
||
const { ctx } = this;
|
||
const product = await ctx.model.Product.findByPk(ctx.params.id);
|
||
|
||
if (!product) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '商品不存在' };
|
||
return;
|
||
}
|
||
|
||
// 主体归属不可通过更新篡改,防止把资源移动到其它主体
|
||
delete ctx.request.body.principal_id;
|
||
await product.update(ctx.request.body);
|
||
ctx.body = { code: 0, message: 'success', data: { id: product.id } };
|
||
}
|
||
|
||
/**
|
||
* @summary 商品快速搜索(聚合)
|
||
* @description 按 商品编码 / 货品编码 / 条码 / 商品名称 聚合模糊匹配,仅返回启用商品,供出入库明细快速选择
|
||
* @router get /api/products/search
|
||
* @apikey
|
||
* @request query string keyword 关键词,匹配商品编码/货品编码/条码/商品名称
|
||
* @response 200 productSearchResponse success
|
||
*/
|
||
async search() {
|
||
const { ctx } = this;
|
||
const Op = this.app.Sequelize.Op;
|
||
const keyword = (ctx.query.keyword || '').trim();
|
||
const principalId = ctx.state.principalId;
|
||
|
||
const where = { principal_id: principalId, status: 1 };
|
||
if (keyword) {
|
||
where[Op.or] = [
|
||
{ item_code: { [Op.like]: `%${keyword}%` } },
|
||
{ goods_code: { [Op.like]: `%${keyword}%` } },
|
||
{ barcode: { [Op.like]: `%${keyword}%` } },
|
||
{ item_name: { [Op.like]: `%${keyword}%` } },
|
||
];
|
||
}
|
||
|
||
const rows = await ctx.model.Product.findAll({
|
||
where,
|
||
attributes: [ 'id', 'item_code', 'goods_code', 'barcode', 'item_name', 'sku_property', 'stock_unit', 'status' ],
|
||
limit: 50,
|
||
order: [[ 'id', 'DESC' ]],
|
||
});
|
||
ctx.body = { code: 0, message: 'success', data: rows };
|
||
}
|
||
|
||
/**
|
||
* @summary 删除商品
|
||
* @description 软删除商品(设置 deleted_at);同一主体下商品编码唯一校验忽略已删除记录,故已删除商品编码可再次使用
|
||
* @router delete /api/products/{id}
|
||
* @apikey
|
||
* @request path integer *id 商品主键ID
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async destroy() {
|
||
const { ctx } = this;
|
||
const product = await ctx.model.Product.findByPk(ctx.params.id);
|
||
|
||
if (!product) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '商品不存在' };
|
||
return;
|
||
}
|
||
|
||
await product.destroy();
|
||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||
}
|
||
}
|
||
|
||
module.exports = ProductController;
|