'use strict'; const { Controller } = require('egg'); const ExcelJS = require('exceljs'); const { parsePagination, buildPageResult } = require('../lib/pagination'); const { IMPORT_COLUMNS, parseImportFile, normalizeRow } = require('../lib/productImport'); /** 库存类型:与 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} 附带库存字段的商品 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); await ctx.service.operationLog.record({ targetType: 'product', targetId: product.id, principalId, action: 'create', title: `新增商品:${product.item_name || ''}(${product.item_code || ''})`, detail: { item_code: product.item_code, item_name: product.item_name, sku_property: product.sku_property, retail_price: product.retail_price, }, }); 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; } // 主体归属不可通过更新篡改,防止把资源移动到其它主体 const before = { item_code: product.item_code, item_name: product.item_name, sku_property: product.sku_property, retail_price: product.retail_price, status: product.status, }; delete ctx.request.body.principal_id; await product.update(ctx.request.body); // 操作记录:写清改了哪些字段(前后值) const changed = Object.keys(before).filter(key => String(before[key] ?? '') !== String(product[key] ?? '')); if (changed.length) { await ctx.service.operationLog.record({ targetType: 'product', targetId: product.id, principalId: product.principal_id, action: 'update', title: `修改商品:${product.item_name || ''}(${product.item_code || ''})— 变更字段 ${changed.join('、')}`, detail: changed.reduce((acc, key) => ({ ...acc, [key]: { before: before[key], after: product[key] } }), {}), }); } // 商品编码/名称/规格变化后,重算绑定该商品的待审核订单明细与商品摘要(已审核订单不受影响) await this.rebuildBoundOrders(product.id, product.principal_id); ctx.body = { code: 0, message: 'success', data: { id: product.id } }; } /** * 重建绑定到该商品的店铺商品所属订单的明细(仅待审核/异常) * @param {number} productId 系统商品ID * @param {number} principalId 所属主体ID * @return {Promise} 重建的明细行数 */ async rebuildBoundOrders(productId, principalId) { const { ctx } = this; const shopProducts = await ctx.model.ShopProduct.findAll({ where: { principal_id: principalId, product_id: productId, bind_type: 1 }, attributes: [ 'id' ], raw: true, }); return ctx.service.orderItemResolve.rebuildOrdersByShopProducts(shopProducts.map(row => Number(row.id))); } /** * @summary 下载商品批量导入模板 * @description 生成仅含表头的 xlsx 模板(商品编码 / 商品名称 / 货物编码 / SKU规格 / 分类 / 品牌 / 条码 / 单位 / 零售价 / 成本价 / 标签价 / 备注) * @router get /api/products/import-template * @apikey * @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体) * @response 200 baseResponse 文件二进制流(xlsx 模板,Content-Type 为 excel 类型) */ async importTemplate() { const { ctx } = this; const workbook = new ExcelJS.Workbook(); const sheet = workbook.addWorksheet('商品导入模板'); sheet.columns = IMPORT_COLUMNS.map(col => ({ header: col.label, key: col.field, width: col.type === 'money' ? 12 : Math.min(30, Math.max(12, col.label.length * 4)), })); sheet.getRow(1).font = { bold: true }; sheet.getRow(1).alignment = { vertical: 'middle' }; sheet.views = [{ state: 'frozen', ySplit: 1 }]; const buffer = await workbook.xlsx.writeBuffer(); ctx.set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); ctx.set('Content-Disposition', 'attachment; filename="product-import-template.xlsx"'); ctx.body = Buffer.from(buffer); } /** * @summary 批量导入商品 * @description 上传 xlsx(表单字段 file,第一行为表头)。只接受 12 个字段: * 商品编码 / 商品名称 / 货物编码 / SKU规格 / 分类 / 品牌 / 条码 / 单位 / 零售价 / 成本价 / 标签价 / 备注; * 同一主体下商品编码已存在则更新(空单元格不覆盖原值,软删除的会恢复),否则新建 * @router post /api/products/import * @apikey * @request formData file *file xlsx 文件 * @request formData integer principal_id 所属主体ID(必填,需当前账号已绑定该主体) * @response 200 productImportResponse success */ async importProducts() { const { ctx } = this; const Op = this.app.Sequelize.Op; const principalId = ctx.state.principalId; const files = ctx.request.files || []; const file = files.find(item => item.field === 'file') || files[0]; if (!file) { ctx.status = 400; ctx.body = { code: 400, message: '未接收到上传文件(表单字段名 file)' }; return; } if (!/\.xlsx$/i.test(file.filename || '')) { await ctx.cleanupRequestFiles(); ctx.status = 400; ctx.body = { code: 400, message: '仅支持 .xlsx 文件,请使用导入模板填写' }; return; } let parsed; try { parsed = await parseImportFile(file.filepath); } catch (err) { await ctx.cleanupRequestFiles(); ctx.status = 400; ctx.body = { code: 400, message: `文件解析失败:${err.message}` }; return; } await ctx.cleanupRequestFiles(); if (parsed.headerError) { ctx.status = 400; ctx.body = { code: 400, message: parsed.headerError }; return; } if (!parsed.rows.length) { ctx.status = 400; ctx.body = { code: 400, message: '文件中没有可导入的数据行' }; return; } // 1) 逐行校验 + 收集商品编码 const errors = []; const validRows = []; const seenCodes = new Set(); let duplicated = 0; for (const { rowNumber, raw } of parsed.rows) { const { data, errors: rowErrors } = normalizeRow(raw); if (rowErrors.length) { errors.push({ row: rowNumber, item_code: data.item_code || '', message: rowErrors.join(';') }); continue; } if (seenCodes.has(data.item_code)) { duplicated++; errors.push({ row: rowNumber, item_code: data.item_code, message: '文件内商品编码重复,已按最后一行处理' }); // 保留最后一行:先删掉前面的同编码行 const idx = validRows.findIndex(item => item.data.item_code === data.item_code); if (idx >= 0) validRows.splice(idx, 1); } seenCodes.add(data.item_code); validRows.push({ rowNumber, data }); } if (!validRows.length) { ctx.body = { code: 0, message: '没有可导入的有效数据', data: { total: parsed.rows.length, created: 0, updated: 0, failed: errors.length, errors, ignored_columns: parsed.ignoredColumns, duplicated }, }; return; } // 2) 批量取已存在商品(含软删除,编码唯一键包含已删除行) const codes = validRows.map(item => item.data.item_code); const existMap = new Map(); for (let i = 0; i < codes.length; i += 500) { const chunk = codes.slice(i, i + 500); const rows = await ctx.model.Product.findAll({ where: { principal_id: principalId, item_code: { [Op.in]: chunk } }, paranoid: false, }); for (const row of rows) existMap.set(row.item_code, row); } // 3) 逐行写入(同一事务,任一行异常回滚该行前的内容不做半途提交) const transaction = await ctx.model.transaction(); let created = 0; let updated = 0; let restored = 0; const logRows = []; try { for (const { rowNumber, data } of validRows) { const exist = existMap.get(data.item_code); try { if (exist) { const patch = {}; for (const [ key, value ] of Object.entries(data)) { if (value === undefined || value === '') continue; if (String(exist[key] ?? '') !== String(value)) patch[key] = value; } if (exist.deleted_at) { await exist.restore({ transaction }); restored++; } if (Object.keys(patch).length) { await exist.update(patch, { transaction }); } updated++; logRows.push({ targetType: 'product', targetId: exist.id, action: 'update', title: `批量导入更新商品:${data.item_name || exist.item_name || ''}(${data.item_code})${Object.keys(patch).length ? `— 变更 ${Object.keys(patch).join('、')}` : ''}`, detail: { row: rowNumber, changed: Object.keys(patch) }, }); } else { if (!data.item_name) { errors.push({ row: rowNumber, item_code: data.item_code, message: '商品名称不能为空(新增商品必填)' }); continue; } const product = await ctx.model.Product.create({ ...data, principal_id: principalId, create_from: 'self', }, { transaction }); created++; logRows.push({ targetType: 'product', targetId: product.id, action: 'create', title: `批量导入新增商品:${product.item_name || ''}(${product.item_code})`, detail: { row: rowNumber }, }); } } catch (err) { errors.push({ row: rowNumber, item_code: data.item_code, message: err.message }); } } await transaction.commit(); } catch (err) { await transaction.rollback(); ctx.status = 500; ctx.body = { code: 500, message: `导入失败:${err.message}` }; return; } // 4) 操作日志 + 绑定了这些商品的待审核订单重算 await ctx.service.operationLog.recordMany(logRows, { source: 'ui' }); const touchedIds = [ ...new Set(logRows.filter(row => row.action === 'update').map(row => Number(row.targetId))) ]; for (const productId of touchedIds) { await this.rebuildBoundOrders(productId, principalId); } ctx.body = { code: 0, message: `导入完成:新增 ${created},更新 ${updated}${restored ? `(含恢复已删除 ${restored})` : ''}${errors.length ? `,失败 ${errors.length}` : ''}`, data: { total: parsed.rows.length, created, updated, restored, failed: errors.length, duplicated, errors, ignored_columns: parsed.ignoredColumns, }, }; } /** * @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; } const snapshot = { item_code: product.item_code, item_name: product.item_name }; await product.destroy(); // 删除后记录也随之无法按对象查询,仍需留痕(按删除前的ID写入) await ctx.service.operationLog.record({ targetType: 'product', targetId: product.id, principalId: product.principal_id, action: 'delete', title: `删除商品:${snapshot.item_name || ''}(${snapshot.item_code || ''})`, detail: snapshot, }); ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } }; } } module.exports = ProductController;