feat(backend): 商品、店铺、组合商品、仓库与库存模块
- 商品/商品图片、店铺、店铺商品、组合商品及明细 - 仓库、仓库商品(WMS itemId 映射)、仓库接口配置与字段定义(warehouseApi/warehouseApiField) - 库存:stock_items、product_stocks(ZC/CC 双维度)与库存重算工具(utils/recalcStock.js) - 库存单据与对接日志:stock orders、api_outbound_logs - 相关迁移:shops/shop_products/stock_orders/warehouses/warehouse_apis/warehouse_products/product_stocks/files-images 等表与字段
This commit is contained in:
parent
8597cf5ac9
commit
cbd16752a5
53
backend/app/controller/apiOutboundLog.js
Normal file
53
backend/app/controller/apiOutboundLog.js
Normal file
@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
|
||||
/**
|
||||
* @controller ApiOutboundLogController 对外 API 调用日志
|
||||
* 记录 OMS → 外部 WMS 的调用(index.ping / singleitem.synchronize 等),数据按主体隔离
|
||||
*/
|
||||
class ApiOutboundLogController extends Controller {
|
||||
/**
|
||||
* @summary 对外 API 调用日志列表
|
||||
* @description 分页查询当前主体下的对外调用记录,支持按仓库、接口配置、方法、关键词过滤
|
||||
* @router get /api/outbound-logs
|
||||
* @apikey
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query integer warehouse_id 仓库ID,不传则返回该主体下全部
|
||||
* @request query integer warehouse_api_id 接口配置ID,不传则不过滤
|
||||
* @request query string method WMS 方法名,如 index.ping / singleitem.synchronize
|
||||
* @request query string keyword 关键词,匹配请求地址/业务提示/异常信息
|
||||
* @response 200 apiOutboundLogListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||||
const { warehouse_id: warehouseId, warehouse_api_id: apiId, method, keyword } = ctx.query;
|
||||
|
||||
const where = { principal_id: ctx.state.principalId };
|
||||
if (warehouseId) where.warehouse_id = Number(warehouseId);
|
||||
if (apiId) where.warehouse_api_id = Number(apiId);
|
||||
if (method) where.method = method;
|
||||
if (keyword) {
|
||||
where[Op.or] = [
|
||||
{ url: { [Op.like]: `%${keyword}%` } },
|
||||
{ business_message: { [Op.like]: `%${keyword}%` } },
|
||||
{ error: { [Op.like]: `%${keyword}%` } },
|
||||
];
|
||||
}
|
||||
|
||||
const { count, rows } = await ctx.model.ApiOutboundLog.findAndCountAll({
|
||||
where,
|
||||
offset,
|
||||
limit,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ApiOutboundLogController;
|
||||
@ -1,6 +1,62 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
|
||||
/** 明细里冗余返回的系统商品可选字段,便于前端直接展示 */
|
||||
const PRODUCT_ATTRS = [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit', 'retail_price' ];
|
||||
|
||||
/**
|
||||
* 归一化组合明细:过滤非法行、同一商品去重合并为一条(数量取整且大于 0)。
|
||||
* @param {Array} items 原始明细 [{ product_id, quantity }]
|
||||
* @return {Array} 归一化后的明细
|
||||
*/
|
||||
function normalizeItems(items) {
|
||||
if (!Array.isArray(items)) return [];
|
||||
const map = new Map();
|
||||
for (const it of items) {
|
||||
const productId = Number(it && it.product_id);
|
||||
const quantity = Number(it && it.quantity);
|
||||
if (!productId || !quantity || quantity <= 0) continue;
|
||||
map.set(productId, Math.floor(quantity));
|
||||
}
|
||||
return Array.from(map, ([ product_id, quantity ]) => ({ product_id, quantity }));
|
||||
}
|
||||
|
||||
/**
|
||||
* 用给定明细覆盖组合商品的全部明细关系(先清空再写入)。
|
||||
* @param {Object} ctx egg context
|
||||
* @param {number} comboProductId 组合商品ID
|
||||
* @param {number} principalId 所属主体ID
|
||||
* @param {Array} itemList 归一化后的明细
|
||||
* @param {Object} transaction 事务
|
||||
*/
|
||||
async function replaceComboItems(ctx, comboProductId, principalId, itemList, transaction) {
|
||||
await ctx.model.ComboProductItem.destroy({ where: { combo_product_id: comboProductId }, transaction });
|
||||
if (!itemList.length) return;
|
||||
await ctx.model.ComboProductItem.bulkCreate(
|
||||
itemList.map(it => ({
|
||||
principal_id: principalId,
|
||||
combo_product_id: comboProductId,
|
||||
product_id: it.product_id,
|
||||
quantity: it.quantity,
|
||||
})),
|
||||
{ transaction }
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 组合商品详情/列表统一的明细关联(含系统商品信息)
|
||||
* @param {Object} ctx egg context
|
||||
* @return {Object} sequelize include 配置
|
||||
*/
|
||||
function itemsInclude(ctx) {
|
||||
return {
|
||||
model: ctx.model.ComboProductItem,
|
||||
as: 'items',
|
||||
include: [{ model: ctx.model.Product, as: 'product', attributes: PRODUCT_ATTRS }],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @controller ComboProductController 组合商品管理
|
||||
@ -8,7 +64,7 @@ const { Controller } = require('egg');
|
||||
class ComboProductController extends Controller {
|
||||
/**
|
||||
* @summary 组合商品列表
|
||||
* @description 分页查询组合商品,支持按主体、关键词与状态过滤
|
||||
* @description 分页查询组合商品,支持按主体、关键词与状态过滤;items 为组合明细关系
|
||||
* @router get /api/combo-products
|
||||
* @apikey
|
||||
* @request query integer page 页码,默认 1
|
||||
@ -21,13 +77,11 @@ class ComboProductController extends Controller {
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const page = Number(ctx.query.page || 1);
|
||||
const pageSize = Number(ctx.query.pageSize || 20);
|
||||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||||
const { keyword, status } = ctx.query;
|
||||
const principalId = ctx.state.principalId;
|
||||
|
||||
const where = {};
|
||||
where.principal_id = principalId;
|
||||
const where = { principal_id: principalId };
|
||||
if (keyword) {
|
||||
where[Op.or] = [
|
||||
{ code: { [Op.like]: `%${keyword}%` } },
|
||||
@ -38,17 +92,19 @@ class ComboProductController extends Controller {
|
||||
|
||||
const { count, rows } = await ctx.model.ComboProduct.findAndCountAll({
|
||||
where,
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
offset,
|
||||
limit,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
distinct: true,
|
||||
include: [ itemsInclude(ctx) ],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } };
|
||||
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 组合商品详情
|
||||
* @description 按主键查询组合商品,items 为组合明细 JSON
|
||||
* @description 按主键查询组合商品,items 为组合明细关系(系统商品ID + 数量)
|
||||
* @router get /api/combo-products/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 组合商品主键ID
|
||||
@ -56,7 +112,9 @@ class ComboProductController extends Controller {
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const combo = await ctx.model.ComboProduct.findByPk(ctx.params.id);
|
||||
const combo = await ctx.model.ComboProduct.findByPk(ctx.params.id, {
|
||||
include: [ itemsInclude(ctx) ],
|
||||
});
|
||||
|
||||
if (!combo) {
|
||||
ctx.status = 404;
|
||||
@ -69,7 +127,7 @@ class ComboProductController extends Controller {
|
||||
|
||||
/**
|
||||
* @summary 新增组合商品
|
||||
* @description 同一主体下组合商品编码 code 唯一;items 为组合明细
|
||||
* @description 同一主体下组合商品编码 code 唯一;items 为组合明细 [{ product_id, quantity }],写入关系表
|
||||
* @router post /api/combo-products
|
||||
* @apikey
|
||||
* @request body createComboProductRequest *body
|
||||
@ -77,7 +135,7 @@ class ComboProductController extends Controller {
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
const { principal_id: principalId, code, name, price } = ctx.request.body;
|
||||
const { principal_id: principalId, code, name, price, items } = ctx.request.body;
|
||||
|
||||
if (!principalId || !code || !name || price === undefined) {
|
||||
ctx.status = 400;
|
||||
@ -92,13 +150,32 @@ class ComboProductController extends Controller {
|
||||
return;
|
||||
}
|
||||
|
||||
const combo = await ctx.model.ComboProduct.create(ctx.request.body);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: combo.id } };
|
||||
const itemList = normalizeItems(items);
|
||||
const transaction = await ctx.model.transaction();
|
||||
try {
|
||||
const combo = await ctx.model.ComboProduct.create(
|
||||
{
|
||||
principal_id: principalId,
|
||||
code,
|
||||
name,
|
||||
price,
|
||||
status: ctx.request.body.status,
|
||||
remark: ctx.request.body.remark,
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
await replaceComboItems(ctx, combo.id, principalId, itemList, transaction);
|
||||
await transaction.commit();
|
||||
ctx.body = { code: 0, message: 'success', data: { id: combo.id } };
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 更新组合商品
|
||||
* @description 未传入的字段保持原值;items 传 JSON 数组覆盖原明细
|
||||
* @description 未传入的字段保持原值;传入 items 时以之覆盖关系表中的组合明细
|
||||
* @router put /api/combo-products/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 组合商品主键ID
|
||||
@ -115,14 +192,30 @@ class ComboProductController extends Controller {
|
||||
return;
|
||||
}
|
||||
|
||||
delete ctx.request.body.principal_id;
|
||||
await combo.update(ctx.request.body);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: combo.id } };
|
||||
const body = { ...ctx.request.body };
|
||||
// 主体归属不可通过更新篡改,防止把资源移动到其它主体
|
||||
delete body.principal_id;
|
||||
const hasItems = Object.prototype.hasOwnProperty.call(body, 'items');
|
||||
const itemList = normalizeItems(body.items);
|
||||
delete body.items;
|
||||
|
||||
const transaction = await ctx.model.transaction();
|
||||
try {
|
||||
await combo.update(body, { transaction });
|
||||
if (hasItems) {
|
||||
await replaceComboItems(ctx, combo.id, combo.principal_id, itemList, transaction);
|
||||
}
|
||||
await transaction.commit();
|
||||
ctx.body = { code: 0, message: 'success', data: { id: combo.id } };
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 删除组合商品
|
||||
* @description 物理删除组合商品
|
||||
* @description 物理删除组合商品及其组合明细
|
||||
* @router delete /api/combo-products/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 组合商品主键ID
|
||||
@ -138,8 +231,16 @@ class ComboProductController extends Controller {
|
||||
return;
|
||||
}
|
||||
|
||||
await combo.destroy();
|
||||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||||
const transaction = await ctx.model.transaction();
|
||||
try {
|
||||
await ctx.model.ComboProductItem.destroy({ where: { combo_product_id: combo.id }, transaction });
|
||||
await combo.destroy({ transaction });
|
||||
await transaction.commit();
|
||||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,6 +1,51 @@
|
||||
'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 商品管理
|
||||
@ -15,37 +60,40 @@ class ProductController extends Controller {
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体)
|
||||
* @request query string keyword 关键词,匹配商品编码或名称
|
||||
* @request query string category 分类,精确匹配
|
||||
* @request query string category_name 分类名称,精确匹配
|
||||
* @request query integer status 状态:1上架 0下架,不传则不过滤
|
||||
* @response 200 productListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const page = Number(ctx.query.page || 1);
|
||||
const pageSize = Number(ctx.query.pageSize || 20);
|
||||
const { keyword, category, status } = ctx.query;
|
||||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||||
const { keyword, category_name: categoryName, status } = ctx.query;
|
||||
const principalId = ctx.state.principalId;
|
||||
|
||||
const where = {};
|
||||
where.principal_id = principalId;
|
||||
if (keyword) {
|
||||
where[Op.or] = [
|
||||
{ code: { [Op.like]: `%${keyword}%` } },
|
||||
{ name: { [Op.like]: `%${keyword}%` } },
|
||||
{ item_code: { [Op.like]: `%${keyword}%` } },
|
||||
{ goods_code: { [Op.like]: `%${keyword}%` } },
|
||||
{ barcode: { [Op.like]: `%${keyword}%` } },
|
||||
{ item_name: { [Op.like]: `%${keyword}%` } },
|
||||
];
|
||||
}
|
||||
if (category) where.category = category;
|
||||
if (categoryName) where.category_name = categoryName;
|
||||
if (status !== undefined && status !== '') where.status = Number(status);
|
||||
|
||||
const { count, rows } = await ctx.model.Product.findAndCountAll({
|
||||
where,
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
offset,
|
||||
limit,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } };
|
||||
// 附带库存字段(正品/次品的可用与锁定数量),取自 product_stocks
|
||||
const list = await attachStockFields(ctx, principalId, rows);
|
||||
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) };
|
||||
}
|
||||
|
||||
/**
|
||||
@ -66,12 +114,13 @@ class ProductController extends Controller {
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: product };
|
||||
const [ data ] = await attachStockFields(ctx, product.principal_id, [ product ]);
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 新增商品
|
||||
* @description 同一主体下商品编码 code 唯一
|
||||
* @description 同一主体下商品编码 item_code 唯一
|
||||
* @router post /api/products
|
||||
* @apikey
|
||||
* @request body createProductRequest *body
|
||||
@ -79,15 +128,20 @@ class ProductController extends Controller {
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
const { principal_id: principalId, code, name, price } = ctx.request.body;
|
||||
const {
|
||||
principal_id: principalId,
|
||||
item_code: itemCode,
|
||||
item_name: itemName,
|
||||
retail_price: retailPrice,
|
||||
} = ctx.request.body;
|
||||
|
||||
if (!principalId || !code || !name || price === undefined) {
|
||||
if (!principalId || !itemCode || !itemName || retailPrice === undefined) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'principal_id、code、name、price 为必填项' };
|
||||
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, code } });
|
||||
const exist = await ctx.model.Product.findOne({ where: { principal_id: principalId, item_code: itemCode } });
|
||||
if (exist) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '该主体下商品编码已存在' };
|
||||
@ -123,9 +177,42 @@ class ProductController extends Controller {
|
||||
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 物理删除商品;被组合商品引用时需先解除引用
|
||||
* @description 软删除商品(设置 deleted_at);同一主体下商品编码唯一校验忽略已删除记录,故已删除商品编码可再次使用
|
||||
* @router delete /api/products/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 商品主键ID
|
||||
|
||||
243
backend/app/controller/shop.js
Normal file
243
backend/app/controller/shop.js
Normal file
@ -0,0 +1,243 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
|
||||
/** OMS 内创建的店铺编码前缀:用于区分「OMS 自动生成」与「平台店铺ID」 */
|
||||
const CODE_PREFIX = 'OMS';
|
||||
|
||||
/** 生成店铺编码:OMS + yyMMddHHmmss + 4 位随机数(如 OMS2609111530123456) */
|
||||
function genShopCode() {
|
||||
const pad = num => String(num).padStart(2, '0');
|
||||
const d = new Date();
|
||||
const ts =
|
||||
`${pad(d.getFullYear() % 100)}${pad(d.getMonth() + 1)}${pad(d.getDate())}` +
|
||||
`${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
|
||||
const rand = Math.floor(1000 + Math.random() * 9000);
|
||||
return `${CODE_PREFIX}${ts}${rand}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @controller ShopController 店铺管理
|
||||
*/
|
||||
class ShopController extends Controller {
|
||||
/**
|
||||
* @summary 店铺列表
|
||||
* @description 分页查询店铺,支持名称/编码模糊搜索、平台与状态过滤
|
||||
* @router get /api/shops
|
||||
* @apikey
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体)
|
||||
* @request query string keyword 关键词,匹配店铺名称或编码
|
||||
* @request query string platform 平台标识,如 taobao/pdd/douyin/jd
|
||||
* @request query integer status 状态:1启用 0禁用,不传则不过滤
|
||||
* @response 200 shopListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||||
const { keyword, platform, status } = ctx.query;
|
||||
|
||||
const where = {};
|
||||
where.principal_id = ctx.state.principalId;
|
||||
if (keyword) {
|
||||
where[Op.or] = [
|
||||
{ name: { [Op.like]: `%${keyword}%` } },
|
||||
{ code: { [Op.like]: `%${keyword}%` } },
|
||||
];
|
||||
}
|
||||
if (platform) where.platform = platform;
|
||||
if (status !== undefined && status !== '') where.status = Number(status);
|
||||
|
||||
const { count, rows } = await ctx.model.Shop.findAndCountAll({
|
||||
where,
|
||||
offset,
|
||||
limit,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 店铺详情
|
||||
* @description 按主键查询店铺基本信息,并附带店铺商品、订单的关联统计,供详情面板展示
|
||||
* @router get /api/shops/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 店铺主键ID
|
||||
* @response 200 shopDetailResponse success
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const Op = ctx.app.Sequelize.Op;
|
||||
const shop = await ctx.model.Shop.findByPk(ctx.params.id);
|
||||
|
||||
if (!shop) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '店铺不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
const shopId = shop.id;
|
||||
const [ shopProductCount, boundCount, orderCount, orderAmount, latestOrder ] = await Promise.all([
|
||||
ctx.model.ShopProduct.count({ where: { shop_id: shopId } }),
|
||||
ctx.model.ShopProduct.count({ where: { shop_id: shopId, bind_type: { [Op.ne]: 0 } } }),
|
||||
ctx.model.Order.count({ where: { shop_id: shopId } }),
|
||||
ctx.model.Order.sum('total_amount', { where: { shop_id: shopId } }),
|
||||
ctx.model.Order.findOne({
|
||||
where: { shop_id: shopId },
|
||||
attributes: [ 'created_at' ],
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
raw: true,
|
||||
}),
|
||||
]);
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
message: 'success',
|
||||
data: {
|
||||
...shop.get({ plain: true }),
|
||||
stats: {
|
||||
shop_product_count: shopProductCount,
|
||||
shop_product_bound_count: boundCount,
|
||||
order_count: orderCount,
|
||||
order_amount: Number(orderAmount || 0),
|
||||
latest_order_at: latestOrder ? latestOrder.created_at : null,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 新增店铺
|
||||
* @description name 必填;code 留空时自动生成 OMS 前缀编码(表示该店铺由 OMS 创建),
|
||||
* 传入 code 时校验同一主体下唯一
|
||||
* @router post /api/shops
|
||||
* @apikey
|
||||
* @request body createShopRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
const { name, principal_id: principalId } = ctx.request.body;
|
||||
|
||||
if (!name) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'name 为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
// 已有编码(如平台店铺ID)直接用;未填则生成 OMS 前缀编码
|
||||
const code = String(ctx.request.body.code || '').trim();
|
||||
let shopCode = code;
|
||||
|
||||
if (code) {
|
||||
const exist = await ctx.model.Shop.findOne({ where: { principal_id: principalId, code } });
|
||||
if (exist) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '该主体下店铺编码已存在' };
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
shopCode = await this.nextShopCode(principalId);
|
||||
if (!shopCode) {
|
||||
ctx.status = 500;
|
||||
ctx.body = { code: 500, message: '店铺编码生成失败,请重试' };
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const shop = await ctx.model.Shop.create({ ...ctx.request.body, code: shopCode });
|
||||
ctx.body = { code: 0, message: 'success', data: { id: shop.id, code: shop.code } };
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成同主体下唯一的店铺编码
|
||||
* @param {number} principalId 主体ID
|
||||
* @return {Promise<string|null>} 编码,重试多次仍冲突时返回 null
|
||||
*/
|
||||
async nextShopCode(principalId) {
|
||||
const { ctx } = this;
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const code = genShopCode();
|
||||
const exist = await ctx.model.Shop.findOne({ where: { principal_id: principalId, code } });
|
||||
if (!exist) return code;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 更新店铺
|
||||
* @description 未传入的字段保持原值;code 留空表示不修改
|
||||
* @router put /api/shops/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 店铺主键ID
|
||||
* @request body updateShopRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const Op = ctx.app.Sequelize.Op;
|
||||
const shop = await ctx.model.Shop.findByPk(ctx.params.id);
|
||||
|
||||
if (!shop) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '店铺不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
delete ctx.request.body.principal_id;
|
||||
|
||||
// 编码留空视为不修改;改动时校验同主体唯一,避免撞唯一索引报 500
|
||||
const code = String(ctx.request.body.code || '').trim();
|
||||
if (code) {
|
||||
const exist = await ctx.model.Shop.findOne({
|
||||
where: { principal_id: shop.principal_id, code, id: { [Op.ne]: shop.id } },
|
||||
});
|
||||
if (exist) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '该主体下店铺编码已存在' };
|
||||
return;
|
||||
}
|
||||
ctx.request.body.code = code;
|
||||
} else {
|
||||
delete ctx.request.body.code;
|
||||
}
|
||||
|
||||
await shop.update(ctx.request.body);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: shop.id, code: shop.code } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 删除店铺
|
||||
* @description 物理删除店铺,其下店铺商品会一并删除;存在订单引用时请先处理
|
||||
* @router delete /api/shops/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 店铺主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const shop = await ctx.model.Shop.findByPk(ctx.params.id);
|
||||
|
||||
if (!shop) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '店铺不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
const orderCount = await ctx.model.Order.count({ where: { shop_id: shop.id } });
|
||||
if (orderCount) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: `该店铺下仍有 ${orderCount} 个订单,不能删除` };
|
||||
return;
|
||||
}
|
||||
|
||||
await shop.destroy();
|
||||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ShopController;
|
||||
240
backend/app/controller/shopProduct.js
Normal file
240
backend/app/controller/shopProduct.js
Normal file
@ -0,0 +1,240 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
|
||||
/**
|
||||
* @controller ShopProductController 店铺商品管理
|
||||
* 采集自各平台店铺的商品,可单向绑定系统商品(products)或组合商品(combo_products)
|
||||
*/
|
||||
class ShopProductController extends Controller {
|
||||
/**
|
||||
* @summary 店铺商品列表
|
||||
* @description 分页查询店铺商品,支持按店铺、绑定状态、关键词(标题/商家编码/平台商品ID)过滤
|
||||
* @router get /api/shop-products
|
||||
* @apikey
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体)
|
||||
* @request query integer shop_id 店铺ID,不传则不过滤
|
||||
* @request query integer bind_type 绑定类型:0未绑定 1系统商品 2组合商品
|
||||
* @request query integer status 状态:1在售 0下架
|
||||
* @request query string keyword 关键词,匹配标题、商家编码或平台商品ID
|
||||
* @response 200 shopProductListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||||
const { shop_id: shopId, bind_type: bindType, status, keyword } = ctx.query;
|
||||
|
||||
const where = {};
|
||||
where.principal_id = ctx.state.principalId;
|
||||
if (shopId) where.shop_id = Number(shopId);
|
||||
if (bindType !== undefined && bindType !== '') where.bind_type = Number(bindType);
|
||||
if (status !== undefined && status !== '') where.status = Number(status);
|
||||
if (keyword) {
|
||||
where[Op.or] = [
|
||||
{ title: { [Op.like]: `%${keyword}%` } },
|
||||
{ outer_code: { [Op.like]: `%${keyword}%` } },
|
||||
{ outer_item_id: { [Op.like]: `%${keyword}%` } },
|
||||
];
|
||||
}
|
||||
|
||||
const { count, rows } = await ctx.model.ShopProduct.findAndCountAll({
|
||||
where,
|
||||
offset,
|
||||
limit,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
include: [
|
||||
{ model: ctx.model.Shop, as: 'shop', attributes: [ 'id', 'name', 'platform' ] },
|
||||
{ model: ctx.model.Product, as: 'product', attributes: [ 'id', 'item_code', 'item_name' ] },
|
||||
{ model: ctx.model.ComboProduct, as: 'comboProduct', attributes: [ 'id', 'code', 'name' ] },
|
||||
],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 店铺商品详情
|
||||
* @description 按主键查询,带出店铺、绑定的系统商品与组合商品
|
||||
* @router get /api/shop-products/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const item = await ctx.model.ShopProduct.findByPk(ctx.params.id, {
|
||||
include: [
|
||||
{ model: ctx.model.Shop, as: 'shop', attributes: [ 'id', 'name', 'platform' ] },
|
||||
{ model: ctx.model.Product, as: 'product', attributes: [ 'id', 'item_code', 'item_name' ] },
|
||||
{ model: ctx.model.ComboProduct, as: 'comboProduct', attributes: [ 'id', 'code', 'name' ] },
|
||||
],
|
||||
});
|
||||
|
||||
if (!item) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '店铺商品不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: item };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 录入/采集店铺商品
|
||||
* @description shop_id 与 outer_item_id 必填;同一店铺下平台商品ID+规格ID唯一,重复录入时更新采集信息
|
||||
* @router post /api/shop-products
|
||||
* @apikey
|
||||
* @request body createShopProductRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
const { shop_id: shopId, outer_item_id: outerItemId, outer_sku_id: outerSkuId, principal_id: principalId } = ctx.request.body;
|
||||
|
||||
if (!shopId || !outerItemId) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'shop_id 与 outer_item_id 为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
// 店铺必须存在且属于当前主体,防止跨主体挂接
|
||||
const shop = await ctx.model.Shop.findOne({ where: { id: shopId, principal_id: principalId } });
|
||||
if (!shop) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '店铺不存在或不属于当前主体' };
|
||||
return;
|
||||
}
|
||||
|
||||
const exist = await ctx.model.ShopProduct.findOne({
|
||||
where: { shop_id: shopId, outer_item_id: outerItemId, outer_sku_id: outerSkuId || null },
|
||||
});
|
||||
if (exist) {
|
||||
await exist.update({ ...ctx.request.body, synced_at: new Date() });
|
||||
ctx.body = { code: 0, message: 'success', data: { id: exist.id, updated: true } };
|
||||
return;
|
||||
}
|
||||
|
||||
const item = await ctx.model.ShopProduct.create({
|
||||
...ctx.request.body,
|
||||
synced_at: new Date(),
|
||||
});
|
||||
ctx.body = { code: 0, message: 'success', data: { id: item.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 更新店铺商品
|
||||
* @description 可修改采集信息;绑定关系建议使用专用绑定接口
|
||||
* @router put /api/shop-products/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 主键ID
|
||||
* @request body updateShopProductRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const item = await ctx.model.ShopProduct.findByPk(ctx.params.id);
|
||||
|
||||
if (!item) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '店铺商品不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
delete ctx.request.body.principal_id;
|
||||
await item.update(ctx.request.body);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: item.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 绑定系统商品或组合商品
|
||||
* @description 单向绑定:bind_type=1 绑系统商品(传 product_id)、2 绑组合商品(传 combo_product_id)、0 解绑;
|
||||
* 绑定的商品必须属于当前主体
|
||||
* @router post /api/shop-products/{id}/bind
|
||||
* @apikey
|
||||
* @request path integer *id 店铺商品主键ID
|
||||
* @request body bindShopProductRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async bind() {
|
||||
const { ctx } = this;
|
||||
const { bind_type: bindType, product_id: productId, combo_product_id: comboProductId } = ctx.request.body;
|
||||
const principalId = ctx.state.principalId;
|
||||
|
||||
const item = await ctx.model.ShopProduct.findByPk(ctx.params.id);
|
||||
if (!item) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '店铺商品不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
const type = Number(bindType);
|
||||
if (![ 0, 1, 2 ].includes(type)) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'bind_type 只能为 0未绑定 1系统商品 2组合商品' };
|
||||
return;
|
||||
}
|
||||
|
||||
const data = { bind_type: type, product_id: null, combo_product_id: null };
|
||||
|
||||
if (type === 1) {
|
||||
if (!productId) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '绑定系统商品时 product_id 为必填项' };
|
||||
return;
|
||||
}
|
||||
const product = await ctx.model.Product.findOne({ where: { id: productId, principal_id: principalId } });
|
||||
if (!product) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '系统商品不存在或不属于当前主体' };
|
||||
return;
|
||||
}
|
||||
data.product_id = Number(productId);
|
||||
}
|
||||
|
||||
if (type === 2) {
|
||||
if (!comboProductId) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '绑定组合商品时 combo_product_id 为必填项' };
|
||||
return;
|
||||
}
|
||||
const combo = await ctx.model.ComboProduct.findOne({ where: { id: comboProductId, principal_id: principalId } });
|
||||
if (!combo) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '组合商品不存在或不属于当前主体' };
|
||||
return;
|
||||
}
|
||||
data.combo_product_id = Number(comboProductId);
|
||||
}
|
||||
|
||||
await item.update(data);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: item.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 删除店铺商品
|
||||
* @description 物理删除采集到的店铺商品
|
||||
* @router delete /api/shop-products/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const item = await ctx.model.ShopProduct.findByPk(ctx.params.id);
|
||||
|
||||
if (!item) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '店铺商品不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
await item.destroy();
|
||||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ShopProductController;
|
||||
241
backend/app/controller/stockItem.js
Normal file
241
backend/app/controller/stockItem.js
Normal file
@ -0,0 +1,241 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const recalcStock = require('../utils/recalcStock');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
|
||||
/**
|
||||
* 应/已数量由系统维护(应=明细数量,已=WMS 回推),禁止前端直接写入。
|
||||
*/
|
||||
const QTY_MANAGED_FIELDS = [ 'plan_in_qty', 'actual_in_qty', 'plan_out_qty', 'actual_out_qty' ];
|
||||
|
||||
/**
|
||||
* 明细仅在所属单据处于「待处理(1)」时可增删改;
|
||||
* 单据一经审核(2) 及之后明细即锁定,避免审核后篡改导致库存与对账不一致。
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Number} billType 1入库 2出库
|
||||
* @param {Number} billId 单据头ID
|
||||
* @return {Promise<{ok: boolean, message?: string}>}
|
||||
*/
|
||||
async function assertItemsEditable(ctx, billType, billId) {
|
||||
const OrderModel = Number(billType) === 1 ? ctx.model.InboundOrder : ctx.model.OutboundOrder;
|
||||
const order = await OrderModel.findByPk(billId);
|
||||
if (!order) return { ok: false, message: '所属单据不存在' };
|
||||
if (order.status !== 1) {
|
||||
return { ok: false, message: '单据已审核或已结束,明细已锁定,不允许增删改' };
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* @controller StockItemController 出入库明细管理
|
||||
* 明细挂在 stock_items 表,由 bill_type(1入库 2出库)+ bill_id 区分归属单据
|
||||
*/
|
||||
class StockItemController extends Controller {
|
||||
/**
|
||||
* @summary 明细列表
|
||||
* @description 按 bill_id + bill_type 查询明细(必填),带出系统商品/组合商品
|
||||
* @router get /api/stock-items
|
||||
* @apikey
|
||||
* @request query integer bill_id 所属单据ID(必填)
|
||||
* @request query integer bill_type 单据类型(必填):1入库 2出库
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 50
|
||||
* @response 200 stockItemListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const { page, pageSize, offset, limit } = parsePagination(ctx.query, { defaultPageSize: 50 });
|
||||
const { bill_id: billId, bill_type: billType } = ctx.query;
|
||||
|
||||
if (!billId || !billType) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'bill_id 与 bill_type 均为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
const where = { bill_id: Number(billId), bill_type: Number(billType), principal_id: ctx.state.principalId };
|
||||
const { count, rows } = await ctx.model.StockItem.findAndCountAll({
|
||||
where,
|
||||
offset,
|
||||
limit,
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
include: [
|
||||
{ model: ctx.model.Product, as: 'product', attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ] },
|
||||
{ model: ctx.model.ComboProduct, as: 'comboProduct', attributes: [ 'id', 'code', 'name' ] },
|
||||
],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 明细详情
|
||||
* @router get /api/stock-items/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 明细主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const item = await ctx.model.StockItem.findByPk(ctx.params.id, {
|
||||
include: [
|
||||
{ model: ctx.model.Product, as: 'product', attributes: [ 'id', 'item_code', 'item_name' ] },
|
||||
{ model: ctx.model.ComboProduct, as: 'comboProduct', attributes: [ 'id', 'code', 'name' ] },
|
||||
],
|
||||
});
|
||||
if (!item) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '明细不存在' };
|
||||
return;
|
||||
}
|
||||
ctx.body = { code: 0, message: 'success', data: item };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 新增明细
|
||||
* @router post /api/stock-items
|
||||
* @apikey
|
||||
* @request body createStockItemRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
const { bill_id: billId, bill_type: billType, product_id: productId } = ctx.request.body;
|
||||
if (!billId || !billType) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'bill_id 与 bill_type 均为必填项' };
|
||||
return;
|
||||
}
|
||||
// 明细锁定校验:单据已审核及之后不允许再新增明细
|
||||
const editable = await assertItemsEditable(ctx, billType, billId);
|
||||
if (!editable.ok) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: editable.message };
|
||||
return;
|
||||
}
|
||||
// 关联系统商品时必须启用,禁用商品不可绑定到明细
|
||||
let product = null;
|
||||
if (productId) {
|
||||
product = await ctx.model.Product.findByPk(productId);
|
||||
if (!product || product.status !== 1) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '商品不存在或已禁用,无法关联' };
|
||||
return;
|
||||
}
|
||||
}
|
||||
const data = {
|
||||
...ctx.request.body,
|
||||
principal_id: ctx.state.principalId,
|
||||
quantity: ctx.request.body.quantity || 0,
|
||||
total_amount: Number((Number(ctx.request.body.quantity || 0) * Number(ctx.request.body.price || 0)).toFixed(2)),
|
||||
};
|
||||
// 应/已数量由系统维护:应数量取明细数量,已数量默认 0(由 WMS 回推写入)
|
||||
for (const f of QTY_MANAGED_FIELDS) delete data[f];
|
||||
if (Number(billType) === 1) data.plan_in_qty = data.quantity;
|
||||
else data.plan_out_qty = data.quantity;
|
||||
// 绑定商品时以商品快照覆盖名称/编码/规格/单位(未填才覆盖)
|
||||
if (product) {
|
||||
data.product_id = product.id;
|
||||
data.name = ctx.request.body.name || product.item_name;
|
||||
data.code = ctx.request.body.code || product.item_code;
|
||||
data.spec = ctx.request.body.spec || product.sku_property;
|
||||
data.unit = ctx.request.body.unit || product.stock_unit;
|
||||
}
|
||||
const item = await ctx.model.StockItem.create(data);
|
||||
await recalcStock(ctx, Number(billType), Number(billId));
|
||||
ctx.body = { code: 0, message: 'success', data: { id: item.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 更新明细
|
||||
* @router put /api/stock-items/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 明细主键ID
|
||||
* @request body updateStockItemRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const item = await ctx.model.StockItem.findByPk(ctx.params.id);
|
||||
if (!item) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '明细不存在' };
|
||||
return;
|
||||
}
|
||||
// 明细锁定校验:单据已审核及之后不允许修改明细
|
||||
const editable = await assertItemsEditable(ctx, item.bill_type, item.bill_id);
|
||||
if (!editable.ok) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: editable.message };
|
||||
return;
|
||||
}
|
||||
const body = { ...ctx.request.body };
|
||||
delete body.principal_id;
|
||||
for (const f of QTY_MANAGED_FIELDS) delete body[f];
|
||||
// 变更关联商品时校验启用状态,并以商品快照覆盖名称/编码/规格/单位
|
||||
if (body.product_id !== undefined) {
|
||||
const pid = body.product_id;
|
||||
if (pid) {
|
||||
const product = await ctx.model.Product.findByPk(pid);
|
||||
if (!product || product.status !== 1) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '商品不存在或已禁用,无法关联' };
|
||||
return;
|
||||
}
|
||||
body.name = body.name || product.item_name;
|
||||
body.code = body.code || product.item_code;
|
||||
body.spec = body.spec || product.sku_property;
|
||||
body.unit = body.unit || product.stock_unit;
|
||||
} else {
|
||||
body.name = body.name || null;
|
||||
body.code = body.code || null;
|
||||
body.spec = body.spec || null;
|
||||
body.unit = body.unit || null;
|
||||
}
|
||||
}
|
||||
if (body.quantity !== undefined || body.price !== undefined) {
|
||||
const qty = body.quantity != null ? body.quantity : item.quantity;
|
||||
const price = body.price != null ? body.price : item.price;
|
||||
body.total_amount = Number((Number(qty || 0) * Number(price || 0)).toFixed(2));
|
||||
}
|
||||
// 数量变动时同步「应」数量(已数量仍由 WMS 回推维护)
|
||||
if (body.quantity !== undefined) {
|
||||
const qty = Number(body.quantity) || 0;
|
||||
if (Number(item.bill_type) === 1) body.plan_in_qty = qty;
|
||||
else body.plan_out_qty = qty;
|
||||
}
|
||||
await item.update(body);
|
||||
await recalcStock(ctx, item.bill_type, item.bill_id);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: item.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 删除明细
|
||||
* @router delete /api/stock-items/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 明细主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const item = await ctx.model.StockItem.findByPk(ctx.params.id);
|
||||
if (!item) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '明细不存在' };
|
||||
return;
|
||||
}
|
||||
// 明细锁定校验:单据已审核及之后不允许删除明细
|
||||
const editable = await assertItemsEditable(ctx, item.bill_type, item.bill_id);
|
||||
if (!editable.ok) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: editable.message };
|
||||
return;
|
||||
}
|
||||
await item.destroy();
|
||||
await recalcStock(ctx, item.bill_type, item.bill_id);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = StockItemController;
|
||||
209
backend/app/controller/warehouse.js
Normal file
209
backend/app/controller/warehouse.js
Normal file
@ -0,0 +1,209 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
|
||||
/** 仓库编码前缀:编码由系统自动生成,无需人工填写 */
|
||||
const CODE_PREFIX = 'WH';
|
||||
|
||||
/** 生成仓库编码:WH + yyMMddHHmmss + 4 位随机数(如 WH2609111530123456) */
|
||||
function genWarehouseCode() {
|
||||
const pad = num => String(num).padStart(2, '0');
|
||||
const d = new Date();
|
||||
const ts =
|
||||
`${pad(d.getFullYear() % 100)}${pad(d.getMonth() + 1)}${pad(d.getDate())}` +
|
||||
`${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
|
||||
const rand = Math.floor(1000 + Math.random() * 9000);
|
||||
return `${CODE_PREFIX}${ts}${rand}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @controller WarehouseController 仓库管理
|
||||
* 仅管理仓库基础信息;接口配置见 WarehouseApiController
|
||||
*/
|
||||
class WarehouseController extends Controller {
|
||||
/**
|
||||
* @summary 仓库列表
|
||||
* @description 分页查询仓库,并带出其接口配置(一个仓库可有多条接口配置)
|
||||
* @router get /api/warehouses
|
||||
* @apikey
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query string code 仓库编码,支持模糊匹配
|
||||
* @request query string name 仓库名称,支持模糊匹配
|
||||
* @request query integer status 状态:1启用 0禁用,不传则不过滤
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||||
const { code, name, status } = ctx.query;
|
||||
const principalId = ctx.state.principalId;
|
||||
|
||||
const where = { principal_id: principalId };
|
||||
if (code) where.code = { [Op.like]: `%${code}%` };
|
||||
if (name) where.name = { [Op.like]: `%${name}%` };
|
||||
if (status !== undefined && status !== '') where.status = Number(status);
|
||||
|
||||
const { count, rows } = await ctx.model.Warehouse.findAndCountAll({
|
||||
where,
|
||||
offset,
|
||||
limit,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.WarehouseApi,
|
||||
as: 'apis',
|
||||
attributes: [ 'id', 'name', 'type', 'base_url', 'app_key', 'status' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 仓库下拉(仅启用)
|
||||
* @router get /api/warehouses/select
|
||||
* @apikey
|
||||
*/
|
||||
async select() {
|
||||
const { ctx } = this;
|
||||
const rows = await ctx.model.Warehouse.findAll({
|
||||
where: { principal_id: ctx.state.principalId, status: 1, deleted_at: null },
|
||||
attributes: [ 'id', 'code', 'name' ],
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
ctx.body = { code: 0, message: 'success', data: rows };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 仓库详情
|
||||
* @description 按主键查询仓库基本信息,并附带接口配置、入库/出库单的关联统计,供详情面板展示
|
||||
* @router get /api/warehouses/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 仓库主键ID
|
||||
* @response 200 warehouseDetailResponse success
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const w = await ctx.model.Warehouse.findByPk(ctx.params.id);
|
||||
if (!w) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '仓库不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
const warehouseId = w.id;
|
||||
const [ apiCount, apiEnabledCount, inboundCount, outboundCount ] = await Promise.all([
|
||||
ctx.model.WarehouseApi.count({ where: { warehouse_id: warehouseId } }),
|
||||
ctx.model.WarehouseApi.count({ where: { warehouse_id: warehouseId, status: 1 } }),
|
||||
ctx.model.InboundOrder.count({ where: { warehouse_id: warehouseId } }),
|
||||
ctx.model.OutboundOrder.count({ where: { warehouse_id: warehouseId } }),
|
||||
]);
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
message: 'success',
|
||||
data: {
|
||||
...w.get({ plain: true }),
|
||||
stats: {
|
||||
api_count: apiCount,
|
||||
api_enabled_count: apiEnabledCount,
|
||||
inbound_order_count: inboundCount,
|
||||
outbound_order_count: outboundCount,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 新增仓库
|
||||
* @description 仅创建仓库基础信息,接口配置请在仓库创建后单独维护;
|
||||
* 仓库编码由系统自动生成(WH 前缀),无需且不接受前端传入
|
||||
* @router post /api/warehouses
|
||||
* @apikey
|
||||
* @request body createWarehouseRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
const { principal_id: principalId, name, type, status, remark } = ctx.request.body;
|
||||
if (!principalId || !name) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'principal_id、name 为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
const code = await this.nextWarehouseCode(principalId);
|
||||
if (!code) {
|
||||
ctx.status = 500;
|
||||
ctx.body = { code: 500, message: '仓库编码生成失败,请重试' };
|
||||
return;
|
||||
}
|
||||
|
||||
const w = await ctx.model.Warehouse.create({ principal_id: principalId, code, name, type, status, remark });
|
||||
ctx.body = { code: 0, message: 'success', data: { id: w.id, code: w.code } };
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成同主体下唯一的仓库编码
|
||||
* @param {number} principalId 主体ID
|
||||
* @return {Promise<string|null>} 编码,重试多次仍冲突时返回 null
|
||||
*/
|
||||
async nextWarehouseCode(principalId) {
|
||||
const { ctx } = this;
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const code = genWarehouseCode();
|
||||
const exist = await ctx.model.Warehouse.findOne({ where: { principal_id: principalId, code } });
|
||||
if (!exist) return code;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 更新仓库
|
||||
* @description 仅更新仓库基础信息(编码自动生成、不可修改),接口配置请在接口配置中维护
|
||||
* @router put /api/warehouses/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 仓库主键ID
|
||||
* @request body updateWarehouseRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const w = await ctx.model.Warehouse.findByPk(ctx.params.id);
|
||||
if (!w) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '仓库不存在' };
|
||||
return;
|
||||
}
|
||||
const { name, type, status, remark } = ctx.request.body;
|
||||
await w.update({ name, type, status, remark });
|
||||
ctx.body = { code: 0, message: 'success', data: { id: w.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 删除仓库(软删除)
|
||||
* @description 软删除仓库,同时清理其接口配置与商品推送绑定
|
||||
* @router delete /api/warehouses/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 仓库主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const w = await ctx.model.Warehouse.findByPk(ctx.params.id);
|
||||
if (!w) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '仓库不存在' };
|
||||
return;
|
||||
}
|
||||
await ctx.model.WarehouseApi.destroy({ where: { warehouse_id: w.id } });
|
||||
await ctx.model.WarehouseProduct.destroy({ where: { warehouse_id: w.id } });
|
||||
await w.destroy();
|
||||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WarehouseController;
|
||||
210
backend/app/controller/warehouseApi.js
Normal file
210
backend/app/controller/warehouseApi.js
Normal file
@ -0,0 +1,210 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
const { buildCallbackUrl } = require('../lib/openapiCallback');
|
||||
|
||||
/**
|
||||
* 仓库接口的接口类型取值:当前系统只对接「类奇门JSON接口」这一种
|
||||
* 后续若接入其他类型(标准奇门、自研协议等),在此扩展取值并同步 contracts/前端选项
|
||||
*/
|
||||
const API_TYPE_QIMEN = 'qimen';
|
||||
|
||||
/**
|
||||
* @controller WarehouseApiController 仓库接口配置管理
|
||||
* 仓库接口配置归属某个仓库,一个仓库可配置多条接口;接口类型由系统固定为类奇门JSON接口
|
||||
*/
|
||||
class WarehouseApiController extends Controller {
|
||||
/**
|
||||
* @summary 仓库接口配置列表
|
||||
* @description 分页查询某仓库下的接口配置,支持按仓库、状态与关键词过滤
|
||||
* @router get /api/warehouse-apis
|
||||
* @apikey
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体)
|
||||
* @request query integer warehouse_id 仓库ID,不传则返回该主体下全部配置
|
||||
* @request query integer status 状态:1启用 0禁用,不传则不过滤
|
||||
* @request query string keyword 关键词,匹配配置名称或基础地址
|
||||
* @response 200 warehouseApiListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||||
const { warehouse_id: warehouseId, status, keyword } = ctx.query;
|
||||
|
||||
const where = { principal_id: ctx.state.principalId };
|
||||
if (warehouseId) where.warehouse_id = Number(warehouseId);
|
||||
if (status !== undefined && status !== '') where.status = Number(status);
|
||||
if (keyword) {
|
||||
where[Op.or] = [
|
||||
{ name: { [Op.like]: `%${keyword}%` } },
|
||||
{ base_url: { [Op.like]: `%${keyword}%` } },
|
||||
];
|
||||
}
|
||||
|
||||
const { count, rows } = await ctx.model.WarehouseApi.findAndCountAll({
|
||||
where,
|
||||
offset,
|
||||
limit,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
include: [
|
||||
{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] },
|
||||
],
|
||||
});
|
||||
|
||||
// 附带对外回调地址(外部系统据此回调 OMS,协议见 app/controller/openapi.js)
|
||||
const list = rows.map(row => {
|
||||
const plain = row.get({ plain: true });
|
||||
plain.callback_url = buildCallbackUrl(ctx);
|
||||
return plain;
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 仓库接口配置详情
|
||||
* @router get /api/warehouse-apis/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 接口配置主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const item = await ctx.model.WarehouseApi.findByPk(ctx.params.id);
|
||||
if (!item) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '接口配置不存在' };
|
||||
return;
|
||||
}
|
||||
const data = item.get({ plain: true });
|
||||
// 附带对外回调地址(外部系统据此回调 OMS)
|
||||
data.callback_url = buildCallbackUrl(ctx);
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 新增仓库接口配置
|
||||
* @description warehouse_id 与 name 必填;仓库必须属于当前主体;接口类型由服务端固定为类奇门JSON接口(qimen);
|
||||
* 配置项值不在此接口维护,请使用 PUT /api/warehouse-apis/{id}/fields
|
||||
* @router post /api/warehouse-apis
|
||||
* @apikey
|
||||
* @request body createWarehouseApiRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
const { principal_id: principalId, warehouse_id: warehouseId, name } = ctx.request.body;
|
||||
|
||||
if (!warehouseId || !name) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'warehouse_id、name 为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
const warehouse = await ctx.model.Warehouse.findOne({ where: { id: warehouseId, principal_id: principalId } });
|
||||
if (!warehouse) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '仓库不存在或不属于当前主体' };
|
||||
return;
|
||||
}
|
||||
|
||||
// 接口类型仅支持类奇门JSON接口,忽略入参由服务端固定写入;extra 由字段值接口维护
|
||||
const payload = { ...ctx.request.body, principal_id: principalId, type: API_TYPE_QIMEN };
|
||||
delete payload.extra;
|
||||
const item = await ctx.model.WarehouseApi.create(payload);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: item.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 更新仓库接口配置
|
||||
* @description 未传入的字段保持原值;不支持通过更新变更归属仓库、主体、接口类型(服务端固定)与配置项值
|
||||
* @router put /api/warehouse-apis/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 接口配置主键ID
|
||||
* @request body updateWarehouseApiRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const item = await ctx.model.WarehouseApi.findByPk(ctx.params.id);
|
||||
if (!item) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '接口配置不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
delete ctx.request.body.principal_id;
|
||||
delete ctx.request.body.warehouse_id;
|
||||
// 接口类型由服务端固定,不随更新变更
|
||||
delete ctx.request.body.type;
|
||||
// 配置项值由配置项接口维护,不随接口配置更新
|
||||
delete ctx.request.body.extra;
|
||||
await item.update(ctx.request.body);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: item.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 删除仓库接口配置
|
||||
* @description 物理删除接口配置,并清空该仓库下的商品推送绑定(warehouse_products)
|
||||
* @router delete /api/warehouse-apis/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 接口配置主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const item = await ctx.model.WarehouseApi.findByPk(ctx.params.id);
|
||||
if (!item) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '接口配置不存在' };
|
||||
return;
|
||||
}
|
||||
// 接口删除后该仓库的商品推送状态不再有效,一并清空绑定数据
|
||||
await ctx.model.WarehouseProduct.destroy({ where: { warehouse_id: item.warehouse_id } });
|
||||
await item.destroy();
|
||||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 测试连接(类奇门JSON接口)
|
||||
* @description 调用 WMS 基础模块心跳接口 index.ping,验证 base_url 可达且 WMS 可用;
|
||||
* 返回外层始终成功(code=0),由 data.ok 标识 ping 是否成功,便于前端直接提示
|
||||
* @router post /api/warehouse-apis/{id}/test
|
||||
* @apikey
|
||||
* @request path integer *id 接口配置主键ID
|
||||
* @response 200 warehouseApiTestResponse success
|
||||
*/
|
||||
async test() {
|
||||
const { ctx } = this;
|
||||
const id = Number(ctx.params.id);
|
||||
const item = await ctx.model.WarehouseApi.findOne({ where: { id, principal_id: ctx.state.principalId } });
|
||||
if (!item) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '接口配置不存在' };
|
||||
return;
|
||||
}
|
||||
if (!item.base_url || !item.app_key || !item.app_secret) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '接口未配置完整(base_url / app_key / app_secret)' };
|
||||
return;
|
||||
}
|
||||
|
||||
const QimenWmsClient = require('../lib/wms/qimenClient');
|
||||
const client = new QimenWmsClient(item, this.app);
|
||||
try {
|
||||
const resp = await client.ping();
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
message: 'success',
|
||||
data: { ok: client.isSuccess(resp), code: resp.code, message: resp.message, wms: resp },
|
||||
};
|
||||
} catch (err) {
|
||||
ctx.body = { code: 0, message: 'success', data: { ok: false, error: err.message } };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WarehouseApiController;
|
||||
98
backend/app/controller/warehouseApiField.js
Normal file
98
backend/app/controller/warehouseApiField.js
Normal file
@ -0,0 +1,98 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const {
|
||||
FIELD_TYPE_LIST,
|
||||
listGroupDefs,
|
||||
listFieldDefs,
|
||||
normalizeFieldValues,
|
||||
} = require('../lib/warehouseApiFields');
|
||||
|
||||
/**
|
||||
* @controller WarehouseApiFieldController 仓库接口配置项
|
||||
* 配置项定义(分组 + 字段清单 + 类型)硬编码在 app/lib/warehouseApiFields.js;
|
||||
* 配置项值由本组接口整体覆盖读写,落库在 warehouse_apis.extra
|
||||
*/
|
||||
class WarehouseApiFieldController extends Controller {
|
||||
/**
|
||||
* @summary 配置项定义(硬编码分组、字段清单与类型枚举)
|
||||
* @description 前端按 group 分组渲染小标题、按 type 渲染对应的表单控件;不需要传主体
|
||||
* @router get /api/warehouse-api-fields
|
||||
* @apikey
|
||||
* @response 200 warehouseApiFieldSchemaResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
message: 'success',
|
||||
data: {
|
||||
types: FIELD_TYPE_LIST,
|
||||
groups: listGroupDefs(),
|
||||
fields: listFieldDefs(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 查询某个接口配置的配置项值
|
||||
* @description 统一走模型 getFieldValues() 读取,返回 { 字段名: 值 } JSON 对象,未配置的字段返回硬编码默认值
|
||||
* @router get /api/warehouse-apis/{id}/fields
|
||||
* @apikey
|
||||
* @request path integer *id 接口配置主键ID
|
||||
* @response 200 warehouseApiFieldValuesResponse success
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const item = await this.findApi(ctx.params.id);
|
||||
if (!item) return;
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
message: 'success',
|
||||
data: { api_id: Number(item.id), values: item.getFieldValues() },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 保存某个接口配置的配置项值
|
||||
* @description 按字段类型校验后整体覆盖保存;字段 key 需在硬编码清单内
|
||||
* @router put /api/warehouse-apis/{id}/fields
|
||||
* @apikey
|
||||
* @request path integer *id 接口配置主键ID
|
||||
* @request body updateWarehouseApiFieldValuesRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const item = await this.findApi(ctx.params.id);
|
||||
if (!item) return;
|
||||
|
||||
const { values, errors } = normalizeFieldValues(ctx.request.body.values);
|
||||
if (errors.length) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: errors.join(';') };
|
||||
return;
|
||||
}
|
||||
|
||||
await item.update({ extra: values });
|
||||
ctx.body = { code: 0, message: 'success', data: { api_id: Number(item.id) } };
|
||||
}
|
||||
|
||||
/**
|
||||
* 按主键取接口配置,不存在时写 404 响应
|
||||
* @param {String|Number} id 接口配置主键
|
||||
* @return {Object|null} 接口配置实例
|
||||
*/
|
||||
async findApi(id) {
|
||||
const { ctx } = this;
|
||||
const item = await ctx.model.WarehouseApi.findByPk(id);
|
||||
if (!item) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '接口配置不存在' };
|
||||
return null;
|
||||
}
|
||||
return item;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WarehouseApiFieldController;
|
||||
459
backend/app/controller/warehouseProduct.js
Normal file
459
backend/app/controller/warehouseProduct.js
Normal file
@ -0,0 +1,459 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
const QimenWmsClient = require('../lib/wms/qimenClient');
|
||||
const stock = require('../utils/stock');
|
||||
|
||||
/** 仓库接口类型:当前系统仅对接类奇门JSON接口 */
|
||||
const API_TYPE_QIMEN = 'qimen';
|
||||
|
||||
/**
|
||||
* @controller WarehouseProductController 仓库-商品关联
|
||||
* 关联表(warehouse_products)只记录商品是否已推送到某个仓库;
|
||||
* 列表以商品为主体左关联出推送状态,未建立关联的商品即「未推送」
|
||||
*/
|
||||
class WarehouseProductController extends Controller {
|
||||
/**
|
||||
* @summary 仓库下的商品列表(含是否已推送状态)
|
||||
* @description 以当前主体下的商品为主体,左关联 warehouse_products 得出该仓库的推送状态;
|
||||
* 未建立关联的商品视为未推送;仓库或接口配置被删除时其关联数据会被清空
|
||||
* @router get /api/warehouses/{id}/products
|
||||
* @apikey
|
||||
* @request path integer *id 仓库主键ID
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query string keyword 关键词,匹配商品编码/货物编码/条码/商品名称
|
||||
* @response 200 warehouseProductListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const warehouseId = Number(ctx.params.id);
|
||||
const principalId = ctx.state.principalId;
|
||||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||||
const { keyword, pushed } = ctx.query;
|
||||
|
||||
const where = { principal_id: principalId };
|
||||
|
||||
// 库存标签页:仅返回已推送到该仓库(已同步)的商品
|
||||
if (pushed === '1' || pushed === 1 || pushed === true || pushed === 'true') {
|
||||
const pushedLinks = await ctx.model.WarehouseProduct.findAll({
|
||||
where: { warehouse_id: warehouseId, principal_id: principalId, pushed: 1 },
|
||||
attributes: [ 'product_id' ],
|
||||
});
|
||||
const pushedIds = pushedLinks.map(l => Number(l.product_id));
|
||||
where.id = { [Op.in]: pushedIds };
|
||||
}
|
||||
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 { count, rows } = await ctx.model.Product.findAndCountAll({
|
||||
where,
|
||||
offset,
|
||||
limit,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
// 关联数据按当前页商品批量取出再合并:避免 hasMany include 影响分页语义
|
||||
const productIds = rows.map(row => Number(row.id));
|
||||
const links = productIds.length
|
||||
? await ctx.model.WarehouseProduct.findAll({
|
||||
where: { warehouse_id: warehouseId, product_id: { [Op.in]: productIds } },
|
||||
attributes: [ 'product_id', 'pushed', 'pushed_at', 'wms_item_id' ],
|
||||
})
|
||||
: [];
|
||||
const linkMap = new Map(links.map(link => [ Number(link.product_id), link ]));
|
||||
|
||||
// 一并带出系统库存(副表 product_stocks,按 item_type 分多行:ZC=正品 / CC=残次品)
|
||||
const stocks = productIds.length
|
||||
? await ctx.model.ProductStock.findAll({
|
||||
where: { principal_id: principalId, product_id: { [Op.in]: productIds } },
|
||||
attributes: [ 'product_id', 'item_type', 'quantity', 'lock_quantity', 'available' ],
|
||||
})
|
||||
: [];
|
||||
const stockMap = new Map();
|
||||
for (const s of stocks) {
|
||||
const pid = Number(s.product_id);
|
||||
if (!stockMap.has(pid)) stockMap.set(pid, {});
|
||||
stockMap.get(pid)[s.item_type] = s;
|
||||
}
|
||||
|
||||
const list = rows.map(row => {
|
||||
const item = row.get({ plain: true });
|
||||
const link = linkMap.get(Number(item.id));
|
||||
const stockRows = stockMap.get(Number(item.id)) || {};
|
||||
const zc = stockRows['ZC'];
|
||||
const cc = stockRows['CC'];
|
||||
return {
|
||||
id: item.id,
|
||||
item_code: item.item_code,
|
||||
goods_code: item.goods_code,
|
||||
item_name: item.item_name,
|
||||
sku_property: item.sku_property,
|
||||
barcode: item.barcode,
|
||||
image: item.image,
|
||||
status: item.status,
|
||||
pushed: link ? Number(link.pushed) === 1 : false,
|
||||
pushed_at: link ? link.pushed_at : null,
|
||||
wms_item_id: link ? link.wms_item_id : null,
|
||||
// 正品库存(ZC)
|
||||
good_quantity: zc ? Number(zc.quantity) : 0,
|
||||
good_lock_quantity: zc ? Number(zc.lock_quantity) : 0,
|
||||
good_available: zc ? Number(zc.available) : 0,
|
||||
// 残次品库存(CC)
|
||||
defect_quantity: cc ? Number(cc.quantity) : 0,
|
||||
defect_lock_quantity: cc ? Number(cc.lock_quantity) : 0,
|
||||
defect_available: cc ? Number(cc.available) : 0,
|
||||
};
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 商品资料推送(推送到仓库 WMS)
|
||||
* @description 将指定商品推送到该仓库的 WMS(类奇门JSON接口 singleitem.synchronize);
|
||||
* 推送成功的商品在 warehouse_products 标记 pushed=1;逐个推送并汇总结果
|
||||
* @router post /api/warehouses/{id}/products/push
|
||||
* @apikey
|
||||
* @request path integer *id 仓库主键ID
|
||||
* @request body warehouseProductPushRequest *body
|
||||
* @response 200 warehouseProductPushResponse success
|
||||
*/
|
||||
async push() {
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(ctx.params.id);
|
||||
const principalId = ctx.state.principalId;
|
||||
const { product_ids: productIds } = ctx.request.body || {};
|
||||
|
||||
if (!Array.isArray(productIds) || productIds.length === 0) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'product_ids 不能为空' };
|
||||
return;
|
||||
}
|
||||
|
||||
// 取该仓库下启用的类奇门接口配置(优先第一条)
|
||||
const api = await ctx.model.WarehouseApi.findOne({
|
||||
where: { warehouse_id: warehouseId, principal_id: principalId, type: API_TYPE_QIMEN, status: 1 },
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
});
|
||||
if (!api) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '该仓库未配置启用的类奇门接口(缺少 app_key / app_secret / base_url)' };
|
||||
return;
|
||||
}
|
||||
|
||||
const client = new QimenWmsClient(api, this.app);
|
||||
const results = [];
|
||||
let success = 0;
|
||||
|
||||
for (const pid of productIds) {
|
||||
const product = await ctx.model.Product.findOne({
|
||||
where: { id: Number(pid), principal_id: principalId },
|
||||
});
|
||||
if (!product) {
|
||||
results.push({ product_id: Number(pid), success: false, message: '商品不存在或不属于当前主体' });
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const resp = await client.pushItem(product);
|
||||
if (client.isSuccess(resp)) {
|
||||
success += 1;
|
||||
const wmsItemId = QimenWmsClient.extractItemId(resp);
|
||||
const [ link, created ] = await ctx.model.WarehouseProduct.findOrCreate({
|
||||
where: { warehouse_id: warehouseId, product_id: product.id },
|
||||
defaults: { principal_id: principalId, pushed: 1, pushed_at: new Date(), wms_item_id: wmsItemId },
|
||||
});
|
||||
if (!created) await link.update({ pushed: 1, pushed_at: new Date(), wms_item_id: wmsItemId });
|
||||
results.push({ product_id: product.id, item_code: product.item_code, success: true, message: resp.message || '推送成功' });
|
||||
} else {
|
||||
results.push({ product_id: product.id, item_code: product.item_code, success: false, message: `WMS 返回失败: ${resp.message || resp.code}` });
|
||||
}
|
||||
} catch (err) {
|
||||
results.push({ product_id: product.id, item_code: product.item_code, success: false, message: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
message: 'success',
|
||||
data: { total: productIds.length, success, failed: productIds.length - success, results },
|
||||
};
|
||||
}
|
||||
|
||||
async wmsInventory() {
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(ctx.params.id);
|
||||
const principalId = ctx.state.principalId;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const { product_ids: productIds } = ctx.request.body || {};
|
||||
|
||||
// 取该仓库下启用的类奇门接口配置(优先第一条)
|
||||
const api = await ctx.model.WarehouseApi.findOne({
|
||||
where: { warehouse_id: warehouseId, principal_id: principalId, type: API_TYPE_QIMEN, status: 1 },
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
});
|
||||
if (!api) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '该仓库未配置启用的类奇门接口(缺少 app_key / app_secret / base_url)' };
|
||||
return;
|
||||
}
|
||||
|
||||
// 取已推送的关联记录(wms_item_id 可能为空:推送发生在字段上线之前)
|
||||
const where = { warehouse_id: warehouseId, principal_id: principalId, pushed: 1 };
|
||||
if (Array.isArray(productIds) && productIds.length) {
|
||||
where.product_id = { [Op.in]: productIds.map(Number) };
|
||||
}
|
||||
const links = await ctx.model.WarehouseProduct.findAll({
|
||||
where,
|
||||
attributes: [ 'id', 'product_id', 'wms_item_id' ],
|
||||
});
|
||||
if (!links.length) {
|
||||
ctx.body = { code: 0, message: 'success', data: { inventories: {} } };
|
||||
return;
|
||||
}
|
||||
|
||||
const client = new QimenWmsClient(api, this.app);
|
||||
const itemIdToProductId = {};
|
||||
const itemIds = [];
|
||||
const needSync = [];
|
||||
|
||||
for (const link of links) {
|
||||
if (link.wms_item_id != null) {
|
||||
const itemId = Number(link.wms_item_id);
|
||||
itemIdToProductId[itemId] = Number(link.product_id);
|
||||
itemIds.push(itemId);
|
||||
} else {
|
||||
needSync.push(link);
|
||||
}
|
||||
}
|
||||
|
||||
// 未记录 wms_item_id 的(多为早期推送),用 itemCode 重新同步一次取回 WMS 内部 itemId(幂等,会写 openapi 日志)
|
||||
if (needSync.length) {
|
||||
const pidList = needSync.map(l => Number(l.product_id));
|
||||
const products = await ctx.model.Product.findAll({ where: { id: { [Op.in]: pidList } } });
|
||||
const productMap = new Map(products.map(p => [ Number(p.id), p ]));
|
||||
for (const link of needSync) {
|
||||
const product = productMap.get(Number(link.product_id));
|
||||
if (!product) continue;
|
||||
try {
|
||||
const resp = await client.pushItem(product);
|
||||
const wmsItemId = QimenWmsClient.extractItemId(resp);
|
||||
if (wmsItemId != null) {
|
||||
await link.update({ wms_item_id: wmsItemId });
|
||||
const itemId = Number(wmsItemId);
|
||||
itemIdToProductId[itemId] = Number(link.product_id);
|
||||
itemIds.push(itemId);
|
||||
} else {
|
||||
ctx.logger.warn(`[wmsInventory] 商品 ${link.product_id} 重新同步未返回 itemId`);
|
||||
}
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[wmsInventory] 商品 ${link.product_id} 重新同步失败:${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!itemIds.length) {
|
||||
ctx.body = { code: 0, message: 'success', data: { inventories: {} } };
|
||||
return;
|
||||
}
|
||||
|
||||
// 批量查询 WMS 库存(会写 openapi 日志)
|
||||
let items = [];
|
||||
try {
|
||||
items = await client.queryInventory(itemIds);
|
||||
} catch (err) {
|
||||
ctx.status = 502;
|
||||
ctx.body = { code: 502, message: err.message };
|
||||
return;
|
||||
}
|
||||
|
||||
const inventories = {};
|
||||
for (const it of items) {
|
||||
const itemId = Number(it.itemId);
|
||||
const pid = itemIdToProductId[itemId];
|
||||
if (!pid) continue;
|
||||
const quantity = Number(it.quantity) || 0;
|
||||
const lockQuantity = Number(it.lockQuantity) || 0;
|
||||
const defectQuantity = Number(it.defectQuantity) || 0;
|
||||
const defectLockQuantity = Number(it.defectLockQuantity) || 0;
|
||||
inventories[pid] = {
|
||||
item_id: itemId,
|
||||
good_quantity: quantity,
|
||||
good_lock_quantity: lockQuantity,
|
||||
good_available: Math.max(0, quantity - lockQuantity),
|
||||
defect_quantity: defectQuantity,
|
||||
defect_lock_quantity: defectLockQuantity,
|
||||
defect_available: Math.max(0, defectQuantity - defectLockQuantity),
|
||||
};
|
||||
}
|
||||
ctx.body = { code: 0, message: 'success', data: { inventories } };
|
||||
}
|
||||
|
||||
/**
|
||||
* 库存同步:将系统库存覆盖为「外部 WMS 库存」(按正品 / 残次品两个维度分别比较)
|
||||
* 对每个维度:系统数量 < 外部 => 已完成入库单(增加系统库存)
|
||||
* 系统数量 > 外部 => 已完成出库单(减少系统库存,仅减总数量不动锁定)
|
||||
* 相等 => 跳过
|
||||
* @router post /api/warehouses/{id}/inventory/sync
|
||||
* @apikey
|
||||
* @request path integer *id 仓库主键ID
|
||||
* @request body warehouseInventorySyncRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async syncInventory() {
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(ctx.params.id);
|
||||
const principalId = ctx.state.principalId;
|
||||
const items = (ctx.request.body && ctx.request.body.items) || [];
|
||||
if (!Array.isArray(items) || items.length === 0) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'items 不能为空' };
|
||||
return;
|
||||
}
|
||||
|
||||
// 过滤出合法的「商品ID + 外部WMS 正品/残次数量」
|
||||
const valid = items
|
||||
.map(it => ({
|
||||
product_id: Number(it.product_id),
|
||||
wms_good_quantity: Number(it.wms_good_quantity),
|
||||
wms_defect_quantity: Number(it.wms_defect_quantity),
|
||||
}))
|
||||
.filter(it => it.product_id && (!Number.isNaN(it.wms_good_quantity) || !Number.isNaN(it.wms_defect_quantity)));
|
||||
|
||||
if (!valid.length) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '未找到有效的 product_id / wms 数量' };
|
||||
return;
|
||||
}
|
||||
|
||||
const productIds = [ ...new Set(valid.map(v => v.product_id)) ];
|
||||
const products = await ctx.model.Product.findAll({
|
||||
where: { id: { [ctx.app.Sequelize.Op.in]: productIds }, principal_id: principalId, status: 1 },
|
||||
attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ],
|
||||
});
|
||||
const productMap = new Map(products.map(p => [ Number(p.id), p ]));
|
||||
|
||||
const stocks = await ctx.model.ProductStock.findAll({
|
||||
where: { principal_id: principalId, product_id: { [ctx.app.Sequelize.Op.in]: productIds } },
|
||||
});
|
||||
const stockMap = new Map();
|
||||
for (const s of stocks) {
|
||||
const pid = Number(s.product_id);
|
||||
if (!stockMap.has(pid)) stockMap.set(pid, {});
|
||||
stockMap.get(pid)[s.item_type] = s;
|
||||
}
|
||||
|
||||
let inboundCount = 0;
|
||||
let outboundCount = 0;
|
||||
let skipped = 0;
|
||||
const created = [];
|
||||
|
||||
const transaction = await ctx.model.transaction();
|
||||
try {
|
||||
// 对单个维度(正品 / 残次品)做一次同步:各自生成入/出库单
|
||||
const syncPair = async (product, systemQty, wmsQty, kindLabel, incFn, decFn) => {
|
||||
const diff = wmsQty - systemQty;
|
||||
if (Math.abs(diff) < 1e-9) { skipped += 1; return; } // 相同不处理
|
||||
const billNo = await this.genSyncBillNo(principalId);
|
||||
const qty = Math.abs(diff);
|
||||
const baseItem = {
|
||||
principal_id: principalId,
|
||||
shop_id: warehouseId,
|
||||
product_id: product.id,
|
||||
name: product.item_name,
|
||||
code: product.item_code,
|
||||
spec: product.sku_property,
|
||||
quantity: qty,
|
||||
total_amount: 0,
|
||||
};
|
||||
if (diff > 0) {
|
||||
const order = await ctx.model.InboundOrder.create({
|
||||
bill_no: billNo,
|
||||
principal_id: principalId,
|
||||
warehouse_id: warehouseId,
|
||||
inbound_type: 'QTRK',
|
||||
status: 4,
|
||||
operator: '库存同步',
|
||||
created_by: ctx.userId,
|
||||
remark: `库存同步(${kindLabel} WMS ${wmsQty} vs 系统 ${systemQty})`,
|
||||
item_total: qty,
|
||||
item_kind: 1,
|
||||
total_amount: 0,
|
||||
}, { transaction });
|
||||
await ctx.model.StockItem.create({ ...baseItem, bill_type: 1, bill_id: order.id }, { transaction });
|
||||
await incFn(ctx, principalId, product.id, qty, transaction);
|
||||
inboundCount += 1;
|
||||
created.push({ type: 'inbound', kind: kindLabel, id: order.id, bill_no: billNo, product_id: product.id, quantity: qty });
|
||||
} else {
|
||||
const order = await ctx.model.OutboundOrder.create({
|
||||
bill_no: billNo,
|
||||
principal_id: principalId,
|
||||
warehouse_id: warehouseId,
|
||||
outbound_type: 'QTCK',
|
||||
status: 4,
|
||||
customer: '库存同步',
|
||||
operator: '库存同步',
|
||||
created_by: ctx.userId,
|
||||
remark: `库存同步(${kindLabel} WMS ${wmsQty} vs 系统 ${systemQty})`,
|
||||
item_total: qty,
|
||||
item_kind: 1,
|
||||
total_amount: 0,
|
||||
}, { transaction });
|
||||
await ctx.model.StockItem.create({ ...baseItem, bill_type: 2, bill_id: order.id }, { transaction });
|
||||
await decFn(ctx, principalId, product.id, qty, transaction);
|
||||
outboundCount += 1;
|
||||
created.push({ type: 'outbound', kind: kindLabel, id: order.id, bill_no: billNo, product_id: product.id, quantity: qty });
|
||||
}
|
||||
};
|
||||
|
||||
for (const it of valid) {
|
||||
const product = productMap.get(it.product_id);
|
||||
if (!product) { skipped += 1; continue; } // 商品不存在/禁用,跳过
|
||||
const stockRows = stockMap.get(it.product_id) || {};
|
||||
const systemGood = stockRows['ZC'] ? Number(stockRows['ZC'].quantity) : 0;
|
||||
const systemDefect = stockRows['CC'] ? Number(stockRows['CC'].quantity) : 0;
|
||||
// 正品维度
|
||||
await syncPair(product, systemGood, it.wms_good_quantity, '正品', stock.increase, stock.decrease);
|
||||
// 残次品维度
|
||||
await syncPair(product, systemDefect, it.wms_defect_quantity, '残次品', stock.increaseDefect, stock.decreaseDefect);
|
||||
}
|
||||
await transaction.commit();
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
message: 'success',
|
||||
data: { inbound_count: inboundCount, outbound_count: outboundCount, skipped, created },
|
||||
};
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
ctx.logger.error('[syncInventory] 失败', err);
|
||||
ctx.status = 500;
|
||||
ctx.body = { code: 500, message: '库存同步失败,请稍后重试' };
|
||||
}
|
||||
}
|
||||
|
||||
/** 生成同步专用单号,保证唯一(重试) */
|
||||
async genSyncBillNo(principalId) {
|
||||
const { ctx } = this;
|
||||
const pad = n => String(n).padStart(2, '0');
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const d = new Date();
|
||||
const ts = `${pad(d.getFullYear() % 100)}${pad(d.getMonth() + 1)}${pad(d.getDate())}${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
|
||||
const rand = Math.floor(1000 + Math.random() * 9000);
|
||||
const billNo = `SYNC${ts}${rand}`;
|
||||
const exist = await ctx.model.InboundOrder.findOne({ where: { bill_no: billNo } })
|
||||
|| await ctx.model.OutboundOrder.findOne({ where: { bill_no: billNo } });
|
||||
if (!exist) return billNo;
|
||||
}
|
||||
return `SYNC${Date.now()}${Math.floor(Math.random() * 10000)}`;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WarehouseProductController;
|
||||
556
backend/app/lib/warehouseApiFields.js
Normal file
556
backend/app/lib/warehouseApiFields.js
Normal file
@ -0,0 +1,556 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 仓库接口「配置项」定义(硬编码)
|
||||
*
|
||||
* 背景:接口配置(warehouse_apis)不再直接编辑自由 JSON 的扩展配置,
|
||||
* 而是拆成两部分的接口共同维护:
|
||||
* 1) 配置项定义(本文件,硬编码):GET /api/warehouse-api-fields 输出分组、字段清单与类型
|
||||
* 2) 字段值:GET/PUT /api/warehouse-apis/:id/fields 单独读写,
|
||||
* 以「字段名: 值」的 JSON 对象落库在 warehouse_apis.extra;
|
||||
* 读取统一走 readFieldValues()(模型 WarehouseApi#getFieldValues 封装),
|
||||
* 未配置的字段用本文件的硬编码 defaultValue 兜底
|
||||
*
|
||||
* 前端按 group 分组渲染小标题、按 type(字段类型枚举)渲染对应的表单控件,
|
||||
* 因此新增/调整字段只改这里即可。
|
||||
* 字段类型枚举:text 单行文本 / textarea 多行文本 / number 数字 / switch 开关 /
|
||||
* select 下拉(需 options) / password 密码 / json JSON 对象
|
||||
*/
|
||||
|
||||
/** 字段类型枚举(前端按此渲染表单控件,勿随意改名) */
|
||||
const FIELD_TYPES = {
|
||||
TEXT: 'text',
|
||||
TEXTAREA: 'textarea',
|
||||
NUMBER: 'number',
|
||||
SWITCH: 'switch',
|
||||
SELECT: 'select',
|
||||
PASSWORD: 'password',
|
||||
JSON: 'json',
|
||||
};
|
||||
|
||||
/** 字段类型枚举列表(供接口输出给前端) */
|
||||
const FIELD_TYPE_LIST = Object.values(FIELD_TYPES);
|
||||
|
||||
/**
|
||||
* 字段分组(前端按 group 渲染小标题,字段通过 group 归属到分组)
|
||||
* key:字段定义里的 group 取值
|
||||
* label:分组标题
|
||||
* description:分组说明(可放配置帮助文档链接)
|
||||
*/
|
||||
const FIELD_GROUPS = [
|
||||
{
|
||||
key: 'basic',
|
||||
label: '基础信息',
|
||||
description: '账号配置帮助文档:https://s.jkyun.biz/IMqcSIg',
|
||||
},
|
||||
{
|
||||
key: 'business',
|
||||
label: '业务设置',
|
||||
description: '业务设置奇门配置帮助文档',
|
||||
},
|
||||
{ key: 'submit', label: '递交设置' },
|
||||
{ key: 'callback', label: '回传设置' },
|
||||
];
|
||||
|
||||
/** 开关类型字段的默认值:默认不启用 */
|
||||
const SWITCH_OFF = false;
|
||||
|
||||
/**
|
||||
* 类奇门JSON接口的配置项清单(硬编码,按奇门仓储实际配置项维护)
|
||||
* key:落库(warehouse_apis.extra)时的字段名
|
||||
* group:所属分组(FIELD_GROUPS.key)
|
||||
* label:前端表单标签
|
||||
* type:字段类型,决定前端表单控件与后端校验规则
|
||||
* required:是否必填
|
||||
* defaultValue:未填写时的默认值
|
||||
* options:type=select 时的可选项
|
||||
* min/max:type=number 时的取值范围
|
||||
* description:字段说明(前端展示为提示文案)
|
||||
*/
|
||||
const WAREHOUSE_API_FIELDS = [
|
||||
/* ---------- 基础信息 ---------- */
|
||||
{
|
||||
key: 'owner_alias',
|
||||
group: 'basic',
|
||||
label: '货主别名',
|
||||
type: FIELD_TYPES.TEXT,
|
||||
placeholder: '如 天豹云仓新WMS',
|
||||
defaultValue: '天豹云仓新WMS',
|
||||
description: '推送给外部系统的货主别名',
|
||||
},
|
||||
{
|
||||
key: 'outsource_api_type',
|
||||
group: 'basic',
|
||||
label: '委外接口类型',
|
||||
type: FIELD_TYPES.TEXT,
|
||||
placeholder: '如 奇门-云谱WMS(appkey:23535631)',
|
||||
description: '对接的委外仓接口类型',
|
||||
},
|
||||
{
|
||||
key: 'customer_id',
|
||||
group: 'basic',
|
||||
label: '客户ID',
|
||||
type: FIELD_TYPES.TEXT,
|
||||
placeholder: '如 tbyc20260614',
|
||||
defaultValue: 'tbyc20260614',
|
||||
description: '外部系统分配的客户 ID',
|
||||
},
|
||||
{
|
||||
key: 'owner_code',
|
||||
group: 'basic',
|
||||
label: '货主编码',
|
||||
type: FIELD_TYPES.TEXT,
|
||||
required: true,
|
||||
placeholder: '如 tbyc20260614',
|
||||
defaultValue: 'tbyc20260614',
|
||||
description: '双方系统约定的货主(商家)编码',
|
||||
},
|
||||
|
||||
/* ---------- 业务设置 ---------- */
|
||||
{
|
||||
key: 'purchase_return_code_type',
|
||||
group: 'business',
|
||||
label: '采购退货代码类型',
|
||||
type: FIELD_TYPES.SELECT,
|
||||
defaultValue: 'CGTH',
|
||||
options: [{ label: '采购退货(CGTH)', value: 'CGTH' }],
|
||||
},
|
||||
{
|
||||
key: 'transfer_in_code_type',
|
||||
group: 'business',
|
||||
label: '调拨入库代码类型',
|
||||
type: FIELD_TYPES.TEXT,
|
||||
placeholder: '如 DBRK',
|
||||
defaultValue: 'DBRK',
|
||||
},
|
||||
{
|
||||
key: 'transfer_out_code_type',
|
||||
group: 'business',
|
||||
label: '调拨出库代码类型',
|
||||
type: FIELD_TYPES.TEXT,
|
||||
placeholder: '如 DBCK',
|
||||
defaultValue: 'DBCK',
|
||||
},
|
||||
{
|
||||
key: 'sku_sync_key',
|
||||
group: 'business',
|
||||
label: '货品同步SKU选择',
|
||||
type: FIELD_TYPES.SELECT,
|
||||
defaultValue: 'barcode',
|
||||
options: [{ label: '[条码]作为双方系统识别商品SKU(不推荐,改条码有风险)', value: 'barcode' }],
|
||||
},
|
||||
{
|
||||
key: 'barcode_sync_source',
|
||||
group: 'business',
|
||||
label: '货品同步条码选择',
|
||||
type: FIELD_TYPES.SELECT,
|
||||
defaultValue: 'product_barcode',
|
||||
options: [{ label: '货品档案条码', value: 'product_barcode' }],
|
||||
},
|
||||
{
|
||||
key: 'api_version',
|
||||
group: 'business',
|
||||
label: '接口版本号',
|
||||
type: FIELD_TYPES.SELECT,
|
||||
defaultValue: 'V2.0',
|
||||
options: [
|
||||
{ label: 'V2.0', value: 'V2.0' },
|
||||
{ label: 'V1.0', value: 'V1.0' },
|
||||
],
|
||||
},
|
||||
|
||||
/* ---------- 递交设置 ---------- */
|
||||
{
|
||||
key: 'item_name_with_spec',
|
||||
group: 'submit',
|
||||
label: '货品同步名称带规格',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'barcode_with_aux',
|
||||
group: 'submit',
|
||||
label: '货品同步条码带辅助条码',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'push_face_sheet',
|
||||
group: 'submit',
|
||||
label: '把物流面单数据传给WMS',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'order_info_not_push',
|
||||
group: 'submit',
|
||||
label: '递交订单时信息不传给仓库',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'shop_name_by_channel',
|
||||
group: 'submit',
|
||||
label: '销售单递交的店铺名称按渠道',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'price_shared_discount',
|
||||
group: 'submit',
|
||||
label: '递交使用分摊优惠后商品单价',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'platform_no_cut_length',
|
||||
group: 'submit',
|
||||
label: '截取电商平台订单号、支付单号长度',
|
||||
type: FIELD_TYPES.NUMBER,
|
||||
defaultValue: 0,
|
||||
min: 0,
|
||||
max: 50,
|
||||
description: '截取长度,0 表示不截取;订单号与支付单号同时生效',
|
||||
},
|
||||
{
|
||||
key: 'clear_logistics_no',
|
||||
group: 'submit',
|
||||
label: '已有物流单号的销售单,递交仓库发货时清空物流单号再进行递交',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'sync_order_custom_fields',
|
||||
group: 'submit',
|
||||
label: '订单级自定义字段同步递交给仓库',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'order_custom_fields_map',
|
||||
group: 'submit',
|
||||
label: '订单级自定义字段映射设置',
|
||||
type: FIELD_TYPES.JSON,
|
||||
description: '「设置」维护的映射,JSON 对象 { 订单字段: 仓库字段 }',
|
||||
},
|
||||
{
|
||||
key: 'sync_item_custom_fields',
|
||||
group: 'submit',
|
||||
label: '货品级自定义字段同步递交给仓库',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'item_custom_fields_map',
|
||||
group: 'submit',
|
||||
label: '货品级自定义字段映射设置',
|
||||
type: FIELD_TYPES.JSON,
|
||||
description: '「设置」维护的映射,JSON 对象 { 货品字段: 仓库字段 }',
|
||||
},
|
||||
{
|
||||
key: 'sender_company_use_shop',
|
||||
group: 'submit',
|
||||
label: '发件人公司使用店铺名称',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'consignment_doc_submit',
|
||||
group: 'submit',
|
||||
label: '寄售业务单据递交WMS,创建发货单或退货入库单',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'allow_invalid_item_order',
|
||||
group: 'submit',
|
||||
label: '允许无效货品订单递交仓库发货',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'order_flag_not_sync',
|
||||
group: 'submit',
|
||||
label: '订单标记无需同步递交给仓库',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'order_flag_setting',
|
||||
group: 'submit',
|
||||
label: '订单标记设置',
|
||||
type: FIELD_TYPES.JSON,
|
||||
description: '「设置」维护的订单标记规则,JSON 对象',
|
||||
},
|
||||
{
|
||||
key: 'outsource_logistics_by_number',
|
||||
group: 'submit',
|
||||
label: '以取号返回的实际物流公司递交委外仓,回传不改订单的物流公司',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'wechat_dropship',
|
||||
group: 'submit',
|
||||
label: '使用微信代发模式',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'wechat_supplier_id',
|
||||
group: 'submit',
|
||||
label: '微店供应商ID',
|
||||
type: FIELD_TYPES.TEXT,
|
||||
placeholder: '使用微信代发模式时填写',
|
||||
},
|
||||
{
|
||||
key: 'other_channel_flag_to_other',
|
||||
group: 'submit',
|
||||
label: '订单含指定标记时,递交委外仓的渠道为OTHER',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'other_channel_flag_setting',
|
||||
group: 'submit',
|
||||
label: '委外仓渠道为OTHER的设置',
|
||||
type: FIELD_TYPES.JSON,
|
||||
description: '「设置」维护需转为 OTHER 的订单标记,JSON 对象',
|
||||
},
|
||||
|
||||
/* ---------- 回传设置 ---------- */
|
||||
{
|
||||
key: 'stock_change_type_mapping',
|
||||
group: 'callback',
|
||||
label: '库存异动回传单据类型映射',
|
||||
type: FIELD_TYPES.JSON,
|
||||
description: '「设置」维护的单据类型映射,JSON 对象',
|
||||
},
|
||||
{
|
||||
key: 'stock_change_warehouse_strategy',
|
||||
group: 'callback',
|
||||
label: '库存异动仓库匹配策略',
|
||||
type: FIELD_TYPES.JSON,
|
||||
description: '「设置」维护的仓库匹配策略,JSON 对象',
|
||||
},
|
||||
{
|
||||
key: 'salereturn_stock_in_type',
|
||||
group: 'callback',
|
||||
label: '销退入库类型库存异动',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'callback_by_actual_stock',
|
||||
group: 'callback',
|
||||
label: '按实际库存异动回传',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'aftersale_defect_callback',
|
||||
group: 'callback',
|
||||
label: '生成售后异常件回传',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'use_wms_warehouse_code',
|
||||
group: 'callback',
|
||||
label: '使用仓储方的仓库编码',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'forbid_stock_change_modify_erp',
|
||||
group: 'callback',
|
||||
label: '不允许仓库通过库存异动方式修改ERP库存',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'outbound_by_actual_qty',
|
||||
group: 'callback',
|
||||
label: '按实发数量生成出库单',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'allow_order_flow_write_logistics',
|
||||
group: 'callback',
|
||||
label: '允许订单流水通知写入物流单号',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'order_flow_abnormal_to_abnormal',
|
||||
group: 'callback',
|
||||
label: '订单流水通知回传“异常”时,销售单转入异常订单',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'order_flow_cancel_force_cancel',
|
||||
group: 'callback',
|
||||
label: '订单流水通知回传“取消”时,销售单强制取消发货单',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'outbound_time_use_current',
|
||||
group: 'callback',
|
||||
label: '仓库发货回传时,销售单“发货时间”使用当前时间',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
{
|
||||
key: 'unique_code_allow_outsource',
|
||||
group: 'callback',
|
||||
label: '唯一码订单平台校验未通过时允许委外仓发货',
|
||||
type: FIELD_TYPES.SWITCH,
|
||||
defaultValue: SWITCH_OFF,
|
||||
},
|
||||
];
|
||||
|
||||
/** 字段 key 集合(用于校验入参) */
|
||||
const FIELD_KEYS = WAREHOUSE_API_FIELDS.map(field => field.key);
|
||||
|
||||
/**
|
||||
* 分组定义(深拷贝,避免调用方修改硬编码常量)
|
||||
* @return {Array} 分组列表
|
||||
*/
|
||||
function listGroupDefs() {
|
||||
return FIELD_GROUPS.map(group => ({ ...group }));
|
||||
}
|
||||
|
||||
/**
|
||||
* 字段定义(深拷贝,避免调用方修改硬编码常量)
|
||||
* @return {Array} 字段定义列表
|
||||
*/
|
||||
function listFieldDefs() {
|
||||
return WAREHOUSE_API_FIELDS.map(field => ({
|
||||
...field,
|
||||
options: field.options ? field.options.map(option => ({ ...option })) : undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 字段的硬编码默认值
|
||||
* @param {Object} field 字段定义
|
||||
* @return {*} 未声明 defaultValue 时返回 null
|
||||
*/
|
||||
function defaultValueOf(field) {
|
||||
return field.defaultValue === undefined ? null : field.defaultValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按类型把单个值归一化为可用的形态(读取用:容错,不抛错)
|
||||
* 值为空或类型不合法时,一律回落到硬编码默认值
|
||||
* @param {Object} field 字段定义
|
||||
* @param {*} raw extra 中该字段的原始值
|
||||
* @return {*} 归一化后的值
|
||||
*/
|
||||
function coerceFieldValue(field, raw) {
|
||||
if (raw === undefined || raw === null || raw === '') return defaultValueOf(field);
|
||||
switch (field.type) {
|
||||
case FIELD_TYPES.NUMBER: {
|
||||
const num = Number(raw);
|
||||
return Number.isFinite(num) ? num : defaultValueOf(field);
|
||||
}
|
||||
case FIELD_TYPES.SWITCH:
|
||||
return raw === true || raw === 1 || raw === '1' || raw === 'true';
|
||||
case FIELD_TYPES.JSON: {
|
||||
if (typeof raw !== 'string') return raw;
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch {
|
||||
return defaultValueOf(field);
|
||||
}
|
||||
}
|
||||
default:
|
||||
return typeof raw === 'object' ? raw : String(raw);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 【统一读取方法】从 extra 读取「字段名: 值」的 JSON 对象
|
||||
* - 存储即键值 JSON 对象(warehouse_apis.extra),此处是唯一读取出口,
|
||||
* 接口返回与后续推送业务都应调用它,不要各自解析 extra
|
||||
* - 未配置或值非法的字段,用硬编码 defaultValue 兜底(未声明默认值则为 null)
|
||||
* @param {Object|null} extra warehouse_apis.extra
|
||||
* @return {Object} { 字段key: 字段值 }
|
||||
*/
|
||||
function readFieldValues(extra) {
|
||||
const source = extra && typeof extra === 'object' && !Array.isArray(extra) ? extra : {};
|
||||
const values = {};
|
||||
for (const field of WAREHOUSE_API_FIELDS) {
|
||||
values[field.key] = coerceFieldValue(field, source[field.key]);
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并按类型归一化入参中的字段值
|
||||
* @param {Object} input 请求体 values
|
||||
* @return {{values: Object, errors: Array<String>}} 归一化后的值与错误信息
|
||||
*/
|
||||
function normalizeFieldValues(input) {
|
||||
const source = input && typeof input === 'object' && !Array.isArray(input) ? input : {};
|
||||
const values = {};
|
||||
const errors = [];
|
||||
|
||||
for (const key of Object.keys(source)) {
|
||||
if (!FIELD_KEYS.includes(key)) errors.push(`未知字段:${key}`);
|
||||
}
|
||||
|
||||
for (const field of WAREHOUSE_API_FIELDS) {
|
||||
const raw = source[field.key];
|
||||
if (raw === undefined || raw === null || raw === '') {
|
||||
if (field.required) errors.push(`${field.label}为必填项`);
|
||||
continue;
|
||||
}
|
||||
switch (field.type) {
|
||||
case FIELD_TYPES.NUMBER: {
|
||||
const num = Number(raw);
|
||||
if (!Number.isFinite(num)) errors.push(`${field.label}需为数字`);
|
||||
else if ((field.min !== undefined && num < field.min) || (field.max !== undefined && num > field.max)) {
|
||||
errors.push(`${field.label}取值范围为 ${field.min} ~ ${field.max}`);
|
||||
} else values[field.key] = num;
|
||||
break;
|
||||
}
|
||||
case FIELD_TYPES.SWITCH:
|
||||
values[field.key] = raw === true || raw === 1 || raw === '1' || raw === 'true';
|
||||
break;
|
||||
case FIELD_TYPES.SELECT: {
|
||||
const allowed = (field.options || []).map(option => option.value);
|
||||
if (!allowed.includes(raw)) errors.push(`${field.label}取值不在可选范围内`);
|
||||
else values[field.key] = raw;
|
||||
break;
|
||||
}
|
||||
case FIELD_TYPES.JSON: {
|
||||
try {
|
||||
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
||||
values[field.key] = parsed;
|
||||
} catch {
|
||||
errors.push(`${field.label}需为合法的 JSON`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
values[field.key] = String(raw);
|
||||
}
|
||||
}
|
||||
|
||||
return { values, errors };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
FIELD_TYPES,
|
||||
FIELD_TYPE_LIST,
|
||||
FIELD_GROUPS,
|
||||
WAREHOUSE_API_FIELDS,
|
||||
listGroupDefs,
|
||||
listFieldDefs,
|
||||
readFieldValues,
|
||||
normalizeFieldValues,
|
||||
};
|
||||
34
backend/app/model/apiOutboundLog.js
Normal file
34
backend/app/model/apiOutboundLog.js
Normal file
@ -0,0 +1,34 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 对外 API 请求记录模型,对应 api_outbound_logs 表
|
||||
* 记录 OMS 调用外部 WMS(index.ping / singleitem.synchronize 等)的请求与响应信息,用于排查
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} apiOutboundLog model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, INTEGER, TINYINT, TEXT, DATE } = app.Sequelize;
|
||||
|
||||
const ApiOutboundLog = app.model.define('api_outbound_log', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, comment: '所属主体ID' },
|
||||
warehouse_id: { type: BIGINT.UNSIGNED, comment: '关联仓库ID' },
|
||||
warehouse_api_id: { type: BIGINT.UNSIGNED, comment: '使用的接口配置ID' },
|
||||
api_type: { type: STRING(50), defaultValue: 'qimen', comment: '接口类型' },
|
||||
method: { type: STRING(100), allowNull: false, comment: 'WMS 方法名' },
|
||||
url: { type: TEXT, comment: '完整请求地址(sign 已脱敏)' },
|
||||
request_headers: { type: TEXT, comment: '请求头 JSON' },
|
||||
request_body: { type: TEXT, comment: '请求报文 JSON' },
|
||||
response_status: { type: INTEGER, comment: 'HTTP 状态码' },
|
||||
response_body: { type: TEXT, comment: '响应报文' },
|
||||
is_success: { type: TINYINT, defaultValue: 0, comment: '传输层是否成功:1是 0否' },
|
||||
business_code: { type: STRING(32), comment: 'WMS 业务码' },
|
||||
business_message: { type: STRING(255), comment: 'WMS 业务提示' },
|
||||
error: { type: TEXT, comment: '异常信息' },
|
||||
duration: { type: INTEGER, comment: '耗时(毫秒)' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
});
|
||||
|
||||
return ApiOutboundLog;
|
||||
};
|
||||
@ -6,7 +6,7 @@
|
||||
* @return {object} comboProduct model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, DECIMAL, JSON, DATE } = app.Sequelize;
|
||||
const { BIGINT, STRING, TINYINT, DECIMAL, DATE } = app.Sequelize;
|
||||
|
||||
const ComboProduct = app.model.define('combo_product', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
@ -14,7 +14,6 @@ module.exports = app => {
|
||||
code: { type: STRING(50), allowNull: false, comment: '组合商品编码' },
|
||||
name: { type: STRING(100), allowNull: false, comment: '组合商品名称' },
|
||||
price: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '组合商品售价' },
|
||||
items: { type: JSON, comment: '组合明细:[{ "product_id": 1, "quantity": 2 }]' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1上架 0下架' },
|
||||
remark: { type: STRING(255), comment: '备注' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
@ -23,6 +22,11 @@ module.exports = app => {
|
||||
|
||||
ComboProduct.associate = () => {
|
||||
app.model.ComboProduct.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
// 组合明细:一个组合商品包含多条「系统商品 + 数量」关系
|
||||
app.model.ComboProduct.hasMany(app.model.ComboProductItem, { foreignKey: 'combo_product_id', as: 'items' });
|
||||
// 反向关联:店铺商品单向绑定到该组合商品、订单明细解析到该组合商品
|
||||
app.model.ComboProduct.hasMany(app.model.ShopProduct, { foreignKey: 'combo_product_id', as: 'shopProducts' });
|
||||
app.model.ComboProduct.hasMany(app.model.OrderItem, { foreignKey: 'combo_product_id', as: 'orderItems' });
|
||||
};
|
||||
|
||||
return ComboProduct;
|
||||
|
||||
30
backend/app/model/comboProductItem.js
Normal file
30
backend/app/model/comboProductItem.js
Normal file
@ -0,0 +1,30 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 组合商品明细模型,对应 combo_product_items 表。
|
||||
* 存储组合商品与系统商品的组合关系(product_id + quantity),
|
||||
* 一个组合内同一系统商品仅有一条记录。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} comboProductItem model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, INTEGER, DATE } = app.Sequelize;
|
||||
|
||||
const ComboProductItem = app.model.define('combo_product_item', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
|
||||
combo_product_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属组合商品ID' },
|
||||
product_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '系统商品ID' },
|
||||
quantity: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 1, comment: '该商品在组合中的数量' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
});
|
||||
|
||||
ComboProductItem.associate = () => {
|
||||
app.model.ComboProductItem.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
app.model.ComboProductItem.belongsTo(app.model.ComboProduct, { foreignKey: 'combo_product_id', as: 'comboProduct' });
|
||||
app.model.ComboProductItem.belongsTo(app.model.Product, { foreignKey: 'product_id', as: 'product' });
|
||||
};
|
||||
|
||||
return ComboProductItem;
|
||||
};
|
||||
@ -1,33 +1,62 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 商品模型,对应 products 表
|
||||
* 商品模型,对应 products 表(字段命名与外部商品表对齐)
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} product model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, DECIMAL, DATE } = app.Sequelize;
|
||||
const { BIGINT, STRING, TINYINT, INTEGER, DECIMAL, DATE, ENUM, JSON } = app.Sequelize;
|
||||
|
||||
const Product = app.model.define('product', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
|
||||
code: { type: STRING(50), allowNull: false, comment: '商品编码' },
|
||||
name: { type: STRING(100), allowNull: false, comment: '商品名称' },
|
||||
type: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '商品类型' },
|
||||
category: { type: STRING(50), comment: '分类' },
|
||||
spec: { type: STRING(100), comment: '规格' },
|
||||
unit: { type: STRING(20), comment: '单位' },
|
||||
price: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '销售价' },
|
||||
item_code: { type: STRING(50), allowNull: false, comment: '商品编码' },
|
||||
goods_code: { type: STRING(100), comment: '货物编码' },
|
||||
item_name: { type: STRING(255), allowNull: false, comment: '商品名称' },
|
||||
sku_property: { type: STRING(100), comment: 'SKU规格' },
|
||||
stock_unit: { type: STRING(20), comment: '库存单位' },
|
||||
length: { type: DECIMAL(10, 2), defaultValue: 0, comment: '长度(cm)' },
|
||||
width: { type: DECIMAL(10, 2), defaultValue: 0, comment: '宽度(cm)' },
|
||||
height: { type: DECIMAL(10, 2), defaultValue: 0, comment: '高度(cm)' },
|
||||
volume: { type: DECIMAL(10, 2), defaultValue: 0, comment: '体积(cm³)' },
|
||||
gross_weight: { type: INTEGER, defaultValue: 0, comment: '毛重(g)' },
|
||||
net_weight: { type: INTEGER, defaultValue: 0, comment: '净重(g)' },
|
||||
category_id: { type: INTEGER, comment: '分类ID' },
|
||||
category_name: { type: STRING(100), comment: '分类名称' },
|
||||
item_type: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '商品类型' },
|
||||
tag_price: { type: DECIMAL(10, 2), defaultValue: 0, comment: '标价' },
|
||||
retail_price: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '零售价' },
|
||||
cost_price: { type: DECIMAL(12, 2), comment: '成本价' },
|
||||
image: { type: STRING(255), comment: '图片' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1上架 0下架' },
|
||||
is_area_sale: { type: STRING(1), defaultValue: 'N', comment: '是否区域销售' },
|
||||
is_sn_mgmt: { type: STRING(1), defaultValue: 'N', comment: '是否序列号管理' },
|
||||
is_shelf_life_mgmt: { type: STRING(1), defaultValue: 'N', comment: '是否保质期管理' },
|
||||
is_batch_mgmt: { type: STRING(1), defaultValue: 'N', comment: '是否批次管理' },
|
||||
barcode: { type: STRING(100), comment: '条码' },
|
||||
brand_name: { type: STRING(100), comment: '品牌名称' },
|
||||
image: { type: STRING(255), comment: '图片(主图,取 images 首张)' },
|
||||
images: { type: JSON, comment: '图片组(URL 数组,首张为主图)' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
|
||||
remark: { type: STRING(255), comment: '备注' },
|
||||
create_from: { type: ENUM('self', 'qimen', 'api'), comment: '数据来源' },
|
||||
stock_id: { type: BIGINT.UNSIGNED, comment: '库存ID' },
|
||||
warehouse_id: { type: BIGINT.UNSIGNED, comment: '仓库ID' },
|
||||
store_id: { type: BIGINT.UNSIGNED, comment: '门店ID' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
deleted_at: { type: DATE, comment: '软删除时间' },
|
||||
}, {
|
||||
paranoid: true,
|
||||
deletedAt: 'deleted_at',
|
||||
});
|
||||
|
||||
Product.associate = () => {
|
||||
app.model.Product.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
// 反向关联:店铺商品单向绑定到该商品、订单明细解析到该商品
|
||||
app.model.Product.hasMany(app.model.ShopProduct, { foreignKey: 'product_id', as: 'shopProducts' });
|
||||
app.model.Product.hasMany(app.model.OrderItem, { foreignKey: 'product_id', as: 'orderItems' });
|
||||
// 仓库-商品关联:该商品在各仓库的推送状态
|
||||
app.model.Product.hasMany(app.model.WarehouseProduct, { foreignKey: 'product_id', as: 'warehouseProducts' });
|
||||
};
|
||||
|
||||
return Product;
|
||||
|
||||
46
backend/app/model/productStock.js
Normal file
46
backend/app/model/productStock.js
Normal file
@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 商品系统库存副表,对应 product_stocks 表
|
||||
* 库存按 item_type(存储类型,与 WMS itemType 对齐)分多行存储:ZC=正品 / CC=残次品
|
||||
* 每个 (product_id, item_type) 一行:总数量(quantity) / 锁定数量(lock_quantity) / 可用数量(available = quantity - lock_quantity)
|
||||
* - 入库单完成 -> 增加对应类型 quantity
|
||||
* - 出库单推送 -> 增加对应类型 lock_quantity(占用可用)
|
||||
* - WMS 发货通知(notify.delivery) -> 扣减对应类型 quantity 与 lock_quantity
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} productStock model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, DECIMAL, DATE } = app.Sequelize;
|
||||
|
||||
const ProductStock = app.model.define('product_stock', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
|
||||
product_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '系统商品ID' },
|
||||
item_type: { type: STRING(4), allowNull: false, defaultValue: 'ZC', comment: '存储类型:ZC=正品 CC=残次品(与 WMS itemType 对齐)' },
|
||||
quantity: { type: DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '总数量' },
|
||||
lock_quantity: { type: DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '锁定数量' },
|
||||
available: { type: DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '可用数量 = 总数量 - 锁定数量' },
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
},
|
||||
}, {
|
||||
indexes: [
|
||||
{ unique: true, name: 'uniq_product_stock_type', fields: [ 'product_id', 'item_type' ] },
|
||||
],
|
||||
});
|
||||
|
||||
ProductStock.associate = () => {
|
||||
app.model.ProductStock.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
app.model.ProductStock.belongsTo(app.model.Product, { foreignKey: 'product_id', as: 'product' });
|
||||
};
|
||||
|
||||
return ProductStock;
|
||||
};
|
||||
34
backend/app/model/shop.js
Normal file
34
backend/app/model/shop.js
Normal file
@ -0,0 +1,34 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 店铺模型,对应 shops 表(归属于主体,一个主体可有多个平台店铺)
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} shop model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, JSON, DATE } = app.Sequelize;
|
||||
|
||||
const Shop = app.model.define('shop', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
|
||||
code: { type: STRING(50), allowNull: false, comment: '店铺编码(平台店铺ID或自定义编码,OMS 内新建时按 OMS 前缀自动生成)' },
|
||||
name: { type: STRING(100), allowNull: false, comment: '店铺名称' },
|
||||
platform: { type: STRING(50), comment: '所属平台:taobao/pdd/douyin/jd/other' },
|
||||
contact_name: { type: STRING(50), comment: '联系人' },
|
||||
contact_phone: { type: STRING(20), comment: '联系电话' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
|
||||
extra: { type: JSON, comment: '扩展配置 JSON:授权信息、接口参数等' },
|
||||
remark: { type: STRING(255), comment: '备注' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
});
|
||||
|
||||
Shop.associate = () => {
|
||||
app.model.Shop.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
app.model.Shop.hasMany(app.model.ShopProduct, { foreignKey: 'shop_id', as: 'shopProducts' });
|
||||
app.model.Shop.hasMany(app.model.Order, { foreignKey: 'shop_id', as: 'orders' });
|
||||
app.model.Shop.hasMany(app.model.OrderItem, { foreignKey: 'shop_id', as: 'orderItems' });
|
||||
};
|
||||
|
||||
return Shop;
|
||||
};
|
||||
43
backend/app/model/shopProduct.js
Normal file
43
backend/app/model/shopProduct.js
Normal file
@ -0,0 +1,43 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 店铺商品模型,对应 shop_products 表
|
||||
* 采集自平台店铺的商品,可单向绑定系统商品(products)或组合商品(combo_products):
|
||||
* bind_type:0未绑定 1系统商品 2组合商品;未绑定时两个商品ID均为空
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} shopProduct model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, DECIMAL, INTEGER, JSON, DATE } = app.Sequelize;
|
||||
|
||||
const ShopProduct = app.model.define('shop_product', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
|
||||
shop_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属店铺ID' },
|
||||
outer_item_id: { type: STRING(100), allowNull: false, comment: '平台商品ID' },
|
||||
outer_sku_id: { type: STRING(100), comment: '平台规格ID(SKU),无规格时为空' },
|
||||
title: { type: STRING(255), comment: '商品标题' },
|
||||
outer_code: { type: STRING(100), comment: '商家编码,用于与系统商品匹配' },
|
||||
spec: { type: STRING(255), comment: '规格' },
|
||||
image: { type: STRING(255), comment: '图片' },
|
||||
price: { type: DECIMAL(12, 2), comment: '店铺售价' },
|
||||
stock: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '采集到的库存' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '店铺商品状态:1在售 0下架' },
|
||||
bind_type: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '绑定类型:0未绑定 1系统商品 2组合商品' },
|
||||
product_id: { type: BIGINT.UNSIGNED, comment: '绑定的系统商品ID,未绑定为空' },
|
||||
combo_product_id: { type: BIGINT.UNSIGNED, comment: '绑定的组合商品ID,未绑定为空' },
|
||||
raw: { type: JSON, comment: '采集到的原始数据' },
|
||||
synced_at: { type: DATE, comment: '最近一次采集时间' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
});
|
||||
|
||||
ShopProduct.associate = () => {
|
||||
app.model.ShopProduct.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
app.model.ShopProduct.belongsTo(app.model.Shop, { foreignKey: 'shop_id', as: 'shop' });
|
||||
app.model.ShopProduct.belongsTo(app.model.Product, { foreignKey: 'product_id', as: 'product' });
|
||||
app.model.ShopProduct.belongsTo(app.model.ComboProduct, { foreignKey: 'combo_product_id', as: 'comboProduct' });
|
||||
};
|
||||
|
||||
return ShopProduct;
|
||||
};
|
||||
46
backend/app/model/stockItem.js
Normal file
46
backend/app/model/stockItem.js
Normal file
@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 出入库明细模型,对应 stock_items 表(出入库单据的共用副表)
|
||||
* bill_type 区分单据类型(1入库 2出库),bill_id 关联对应单据头
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} stockItem model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, DECIMAL, DATE } = app.Sequelize;
|
||||
|
||||
const StockItem = app.model.define('stock_item', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
|
||||
bill_type: { type: TINYINT, allowNull: false, comment: '单据类型:1入库 2出库' },
|
||||
bill_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '关联单据头ID' },
|
||||
shop_id: { type: BIGINT.UNSIGNED, comment: '店铺/仓库ID(冗余单据的店铺)' },
|
||||
product_id: { type: BIGINT.UNSIGNED, comment: '系统商品ID,为空表示仅登记名称' },
|
||||
combo_product_id: { type: BIGINT.UNSIGNED, comment: '组合商品ID' },
|
||||
shop_product_id: { type: BIGINT.UNSIGNED, comment: '店铺商品ID' },
|
||||
name: { type: STRING(255), comment: '商品名称(快照)' },
|
||||
code: { type: STRING(100), comment: '商品编码(快照)' },
|
||||
inventory_type: { type: STRING(10), allowNull: false, defaultValue: 'ZP', comment: '库存类型:ZP=正品 CC=残次(对齐 WMS 入库单行级 inventoryType)' },
|
||||
spec: { type: STRING(255), comment: '规格(快照)' },
|
||||
unit: { type: STRING(20), comment: '单位' },
|
||||
quantity: { type: DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '数量' },
|
||||
plan_in_qty: { type: DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '应入数量(入库明细,默认取明细数量)' },
|
||||
actual_in_qty: { type: DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '已入数量(入库明细,WMS 收货确认回推)' },
|
||||
plan_out_qty: { type: DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '应出数量(出库明细,默认取明细数量)' },
|
||||
actual_out_qty: { type: DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '已出数量(出库明细,WMS 发货回推)' },
|
||||
price: { type: DECIMAL(12, 2), comment: '单价' },
|
||||
total_amount: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '明细金额' },
|
||||
remark: { type: STRING(255), comment: '备注' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
});
|
||||
|
||||
StockItem.associate = () => {
|
||||
app.model.StockItem.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
app.model.StockItem.belongsTo(app.model.Product, { foreignKey: 'product_id', as: 'product' });
|
||||
app.model.StockItem.belongsTo(app.model.ComboProduct, { foreignKey: 'combo_product_id', as: 'comboProduct' });
|
||||
app.model.StockItem.belongsTo(app.model.ShopProduct, { foreignKey: 'shop_product_id', as: 'shopProduct' });
|
||||
};
|
||||
|
||||
return StockItem;
|
||||
};
|
||||
35
backend/app/model/warehouse.js
Normal file
35
backend/app/model/warehouse.js
Normal file
@ -0,0 +1,35 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 仓库模型,对应 warehouses 表
|
||||
* 仅保存仓库基础信息;接口配置拆分到 warehouse_apis(一个仓库可有多条接口配置)
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} warehouse model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize;
|
||||
|
||||
const Warehouse = app.model.define('warehouse', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
|
||||
code: { type: STRING(50), allowNull: false, comment: '仓库编码(系统自动生成,WH 前缀)' },
|
||||
name: { type: STRING(100), allowNull: false, comment: '仓库名称' },
|
||||
type: { type: STRING(50), comment: '仓库类型:wms/erp/other' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
|
||||
remark: { type: STRING(255), comment: '备注' },
|
||||
deleted_at: { type: DATE, comment: '软删除时间' },
|
||||
}, {
|
||||
paranoid: true,
|
||||
deletedAt: 'deleted_at',
|
||||
});
|
||||
|
||||
Warehouse.associate = () => {
|
||||
app.model.Warehouse.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
// 一个仓库可配置多个接口
|
||||
app.model.Warehouse.hasMany(app.model.WarehouseApi, { foreignKey: 'warehouse_id', as: 'apis' });
|
||||
// 仓库-商品关联:记录商品是否已推送到该仓库
|
||||
app.model.Warehouse.hasMany(app.model.WarehouseProduct, { foreignKey: 'warehouse_id', as: 'warehouseProducts' });
|
||||
};
|
||||
|
||||
return Warehouse;
|
||||
};
|
||||
46
backend/app/model/warehouseApi.js
Normal file
46
backend/app/model/warehouseApi.js
Normal file
@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
|
||||
const { readFieldValues } = require('../lib/warehouseApiFields');
|
||||
|
||||
/**
|
||||
* 仓库接口配置模型,对应 warehouse_apis 表
|
||||
* 一个仓库可有多条接口配置(当前对接方式统一为「类奇门JSON接口」)
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} warehouseApi model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, JSON, DATE } = app.Sequelize;
|
||||
|
||||
const WarehouseApi = app.model.define('warehouse_api', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
|
||||
warehouse_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属仓库ID' },
|
||||
name: { type: STRING(100), allowNull: false, comment: '接口配置名称' },
|
||||
type: { type: STRING(50), defaultValue: 'qimen', comment: '接口类型:qimen=类奇门JSON接口(当前系统仅支持这一种)' },
|
||||
base_url: { type: STRING(255), comment: '接口基础地址' },
|
||||
app_key: { type: STRING(100), comment: '应用Key' },
|
||||
app_secret: { type: STRING(255), comment: '应用密钥' },
|
||||
extra: { type: JSON, comment: '接口配置项值 JSON 对象:{ 字段名: 值 },未配置的字段按硬编码默认值读取' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
|
||||
remark: { type: STRING(255), comment: '备注' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
});
|
||||
|
||||
/**
|
||||
* 【统一读取方法】取本接口配置的配置项值
|
||||
* 返回 { 字段名: 值 } JSON 对象,未配置的字段用硬编码默认值兜底,
|
||||
* 调用方(接口返回、推送业务)统一走这里,不要直接解析 extra
|
||||
* @return {Object} { 字段key: 字段值 }
|
||||
*/
|
||||
WarehouseApi.prototype.getFieldValues = function getFieldValues() {
|
||||
return readFieldValues(this.extra);
|
||||
};
|
||||
|
||||
WarehouseApi.associate = () => {
|
||||
app.model.WarehouseApi.belongsTo(app.model.Warehouse, { foreignKey: 'warehouse_id', as: 'warehouse' });
|
||||
app.model.WarehouseApi.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
};
|
||||
|
||||
return WarehouseApi;
|
||||
};
|
||||
31
backend/app/model/warehouseProduct.js
Normal file
31
backend/app/model/warehouseProduct.js
Normal file
@ -0,0 +1,31 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 仓库-商品关联模型,对应 warehouse_products 表
|
||||
* 只做极简关联:记录某个商品是否已推送到某个仓库(pushed),不存商品快照
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} warehouseProduct model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, TINYINT, DATE } = app.Sequelize;
|
||||
|
||||
const WarehouseProduct = app.model.define('warehouse_product', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
|
||||
warehouse_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '仓库ID' },
|
||||
product_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '商品ID' },
|
||||
pushed: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '是否已推送到仓库:1是 0否' },
|
||||
pushed_at: { type: DATE, comment: '最近一次推送时间' },
|
||||
wms_item_id: { type: BIGINT.UNSIGNED, allowNull: true, comment: 'WMS 内部商品ID(singleitem.synchronize 返回),用于按 itemId 查询库存' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
});
|
||||
|
||||
WarehouseProduct.associate = () => {
|
||||
app.model.WarehouseProduct.belongsTo(app.model.Warehouse, { foreignKey: 'warehouse_id', as: 'warehouse' });
|
||||
app.model.WarehouseProduct.belongsTo(app.model.Product, { foreignKey: 'product_id', as: 'product' });
|
||||
app.model.WarehouseProduct.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
};
|
||||
|
||||
return WarehouseProduct;
|
||||
};
|
||||
27
backend/app/utils/recalcStock.js
Normal file
27
backend/app/utils/recalcStock.js
Normal file
@ -0,0 +1,27 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 重算出入库单据头的商品总数与商品种类数,并在明细增删改后回写
|
||||
* 商品总数 = 所有明细 quantity 之和;商品种类数 = 不重复商品数(同一商品计为一种)
|
||||
* @param {Egg.Context} ctx
|
||||
* @param {number} billType 1入库 2出库
|
||||
* @param {number} billId 单据头ID
|
||||
*/
|
||||
module.exports = async function recalcStock(ctx, billType, billId) {
|
||||
const items = await ctx.model.StockItem.findAll({
|
||||
where: { bill_type: billType, bill_id: billId },
|
||||
attributes: [ 'id', 'product_id', 'quantity' ],
|
||||
});
|
||||
let itemTotal = 0;
|
||||
const kinds = new Set();
|
||||
for (const it of items) {
|
||||
itemTotal = Number(itemTotal) + Number(it.quantity || 0);
|
||||
if (it.product_id) kinds.add(`p${it.product_id}`);
|
||||
else kinds.add(`i${it.id}`);
|
||||
}
|
||||
const model = billType === 1 ? ctx.model.InboundOrder : ctx.model.OutboundOrder;
|
||||
await model.update(
|
||||
{ item_total: itemTotal, item_kind: kinds.size },
|
||||
{ where: { id: billId } },
|
||||
);
|
||||
};
|
||||
55
backend/database/migrations/20260909001900-create-shops.js
Normal file
55
backend/database/migrations/20260909001900-create-shops.js
Normal file
@ -0,0 +1,55 @@
|
||||
'use strict';
|
||||
|
||||
/** 9. 店铺表:归属于具体主体,一个主体可有多个平台店铺 */
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable(
|
||||
'shops',
|
||||
{
|
||||
id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
autoIncrement: true,
|
||||
primaryKey: true,
|
||||
},
|
||||
principal_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属主体ID',
|
||||
references: { model: 'principals', key: 'id' },
|
||||
},
|
||||
code: { type: Sequelize.STRING(50), allowNull: false, comment: '店铺编码(平台店铺ID或自定义编码)' },
|
||||
name: { type: Sequelize.STRING(100), allowNull: false, comment: '店铺名称' },
|
||||
platform: { type: Sequelize.STRING(50), allowNull: true, comment: '所属平台:taobao/pdd/douyin/jd/other' },
|
||||
contact_name: { type: Sequelize.STRING(50), allowNull: true, comment: '联系人' },
|
||||
contact_phone: { type: Sequelize.STRING(20), allowNull: true, comment: '联系电话' },
|
||||
status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
|
||||
extra: { type: Sequelize.JSON, allowNull: true, comment: '扩展配置 JSON:授权信息、接口参数等' },
|
||||
remark: { type: Sequelize.STRING(255), allowNull: true, comment: '备注' },
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
},
|
||||
},
|
||||
{ charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '店铺表' }
|
||||
);
|
||||
|
||||
await queryInterface.addIndex('shops', {
|
||||
fields: [ 'principal_id', 'code' ],
|
||||
unique: true,
|
||||
name: 'uk_shops_principal_code',
|
||||
});
|
||||
await queryInterface.addIndex('shops', { fields: [ 'principal_id' ], name: 'idx_shops_principal' });
|
||||
await queryInterface.addIndex('shops', { fields: [ 'platform' ], name: 'idx_shops_platform' });
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable('shops');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,88 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 10. 店铺商品表:采集自各平台店铺的商品(SPU/SKU),归属于店铺;
|
||||
* 可单向绑定系统商品(products)或组合商品(combo_products),
|
||||
* 未绑定时 product_id / combo_product_id 为空,bind_type 为 0。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable(
|
||||
'shop_products',
|
||||
{
|
||||
id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
autoIncrement: true,
|
||||
primaryKey: true,
|
||||
},
|
||||
principal_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属主体ID',
|
||||
references: { model: 'principals', key: 'id' },
|
||||
},
|
||||
shop_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属店铺ID',
|
||||
references: { model: 'shops', key: 'id' },
|
||||
onDelete: 'CASCADE',
|
||||
},
|
||||
outer_item_id: { type: Sequelize.STRING(100), allowNull: false, comment: '平台商品ID' },
|
||||
outer_sku_id: { type: Sequelize.STRING(100), allowNull: true, comment: '平台规格ID(SKU),无规格时为空' },
|
||||
title: { type: Sequelize.STRING(255), allowNull: true, comment: '商品标题' },
|
||||
outer_code: { type: Sequelize.STRING(100), allowNull: true, comment: '商家编码,用于与系统商品匹配' },
|
||||
spec: { type: Sequelize.STRING(255), allowNull: true, comment: '规格' },
|
||||
image: { type: Sequelize.STRING(255), allowNull: true, comment: '图片' },
|
||||
price: { type: Sequelize.DECIMAL(12, 2), allowNull: true, comment: '店铺售价' },
|
||||
stock: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 0, comment: '采集到的库存' },
|
||||
status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1, comment: '店铺商品状态:1在售 0下架' },
|
||||
// 单向绑定:绑定系统商品或组合商品,二者互斥,均为空表示未绑定
|
||||
bind_type: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 0, comment: '绑定类型:0未绑定 1系统商品 2组合商品' },
|
||||
product_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '绑定的系统商品ID,未绑定为空',
|
||||
references: { model: 'products', key: 'id' },
|
||||
onDelete: 'SET NULL',
|
||||
},
|
||||
combo_product_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '绑定的组合商品ID,未绑定为空',
|
||||
references: { model: 'combo_products', key: 'id' },
|
||||
onDelete: 'SET NULL',
|
||||
},
|
||||
raw: { type: Sequelize.JSON, allowNull: true, comment: '采集到的原始数据' },
|
||||
synced_at: { type: Sequelize.DATE, allowNull: true, comment: '最近一次采集时间' },
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
},
|
||||
},
|
||||
{ charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '店铺商品表' }
|
||||
);
|
||||
|
||||
await queryInterface.addIndex('shop_products', {
|
||||
fields: [ 'shop_id', 'outer_item_id', 'outer_sku_id' ],
|
||||
unique: true,
|
||||
name: 'uk_shop_products_outer',
|
||||
});
|
||||
await queryInterface.addIndex('shop_products', { fields: [ 'principal_id' ], name: 'idx_shop_products_principal' });
|
||||
await queryInterface.addIndex('shop_products', { fields: [ 'shop_id', 'bind_type' ], name: 'idx_shop_products_shop_bind' });
|
||||
await queryInterface.addIndex('shop_products', { fields: [ 'outer_code' ], name: 'idx_shop_products_outer_code' });
|
||||
await queryInterface.addIndex('shop_products', { fields: [ 'product_id' ], name: 'idx_shop_products_product' });
|
||||
await queryInterface.addIndex('shop_products', { fields: [ 'combo_product_id' ], name: 'idx_shop_products_combo' });
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable('shop_products');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,143 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 22. 出入库与明细表:
|
||||
* - inbound_orders 入库单(单据头)
|
||||
* - outbound_orders 出库单(单据头)
|
||||
* - stock_items 出入库明细(共用表,bill_type 区分:1入库 2出库;bill_id 关联对应单据头)
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable(
|
||||
'inbound_orders',
|
||||
{
|
||||
id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: false, autoIncrement: true, primaryKey: true },
|
||||
bill_no: { type: Sequelize.STRING(50), allowNull: false, comment: '入库单号' },
|
||||
principal_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属主体ID',
|
||||
references: { model: 'principals', key: 'id' },
|
||||
},
|
||||
shop_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '来源店铺/仓库ID',
|
||||
references: { model: 'shops', key: 'id' },
|
||||
onDelete: 'SET NULL',
|
||||
},
|
||||
inbound_type: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1, comment: '入库类型:1采购入库 2退货入库 9其他' },
|
||||
status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1待入库 2已入库 3已取消' },
|
||||
supplier: { type: Sequelize.STRING(255), allowNull: true, comment: '供应商' },
|
||||
operator: { type: Sequelize.STRING(50), allowNull: true, comment: '操作人' },
|
||||
total_amount: { type: Sequelize.DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '单据总金额' },
|
||||
remark: { type: Sequelize.STRING(255), allowNull: true, comment: '备注' },
|
||||
created_at: { type: Sequelize.DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
|
||||
updated_at: { type: Sequelize.DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP') },
|
||||
},
|
||||
{ charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '入库单' }
|
||||
);
|
||||
await queryInterface.addIndex('inbound_orders', { fields: ['principal_id'], name: 'idx_inbound_orders_principal' });
|
||||
await queryInterface.addIndex('inbound_orders', { fields: ['shop_id'], name: 'idx_inbound_orders_shop' });
|
||||
await queryInterface.addIndex('inbound_orders', { fields: ['status'], name: 'idx_inbound_orders_status' });
|
||||
await queryInterface.addIndex('inbound_orders', { fields: ['bill_no'], unique: true, name: 'uk_inbound_orders_bill_no' });
|
||||
|
||||
await queryInterface.createTable(
|
||||
'outbound_orders',
|
||||
{
|
||||
id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: false, autoIncrement: true, primaryKey: true },
|
||||
bill_no: { type: Sequelize.STRING(50), allowNull: false, comment: '出库单号' },
|
||||
principal_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属主体ID',
|
||||
references: { model: 'principals', key: 'id' },
|
||||
},
|
||||
shop_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '目标店铺/仓库ID',
|
||||
references: { model: 'shops', key: 'id' },
|
||||
onDelete: 'SET NULL',
|
||||
},
|
||||
outbound_type: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1, comment: '出库类型:1销售出库 2退货出库 9其他' },
|
||||
status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1待出库 2已出库 3已取消' },
|
||||
customer: { type: Sequelize.STRING(255), allowNull: true, comment: '客户/收货方' },
|
||||
operator: { type: Sequelize.STRING(50), allowNull: true, comment: '操作人' },
|
||||
total_amount: { type: Sequelize.DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '单据总金额' },
|
||||
remark: { type: Sequelize.STRING(255), allowNull: true, comment: '备注' },
|
||||
created_at: { type: Sequelize.DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
|
||||
updated_at: { type: Sequelize.DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP') },
|
||||
},
|
||||
{ charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '出库单' }
|
||||
);
|
||||
await queryInterface.addIndex('outbound_orders', { fields: ['principal_id'], name: 'idx_outbound_orders_principal' });
|
||||
await queryInterface.addIndex('outbound_orders', { fields: ['shop_id'], name: 'idx_outbound_orders_shop' });
|
||||
await queryInterface.addIndex('outbound_orders', { fields: ['status'], name: 'idx_outbound_orders_status' });
|
||||
await queryInterface.addIndex('outbound_orders', { fields: ['bill_no'], unique: true, name: 'uk_outbound_orders_bill_no' });
|
||||
|
||||
await queryInterface.createTable(
|
||||
'stock_items',
|
||||
{
|
||||
id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: false, autoIncrement: true, primaryKey: true },
|
||||
principal_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属主体ID',
|
||||
references: { model: 'principals', key: 'id' },
|
||||
},
|
||||
bill_type: { type: Sequelize.TINYINT, allowNull: false, comment: '单据类型:1入库 2出库' },
|
||||
bill_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: false, comment: '关联单据头ID(inbound_orders / outbound_orders)' },
|
||||
shop_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '店铺/仓库ID(冗余单据的店铺)',
|
||||
references: { model: 'shops', key: 'id' },
|
||||
onDelete: 'SET NULL',
|
||||
},
|
||||
product_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '系统商品ID,为空表示仅登记名称',
|
||||
references: { model: 'products', key: 'id' },
|
||||
onDelete: 'SET NULL',
|
||||
},
|
||||
combo_product_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '组合商品ID',
|
||||
references: { model: 'combo_products', key: 'id' },
|
||||
onDelete: 'SET NULL',
|
||||
},
|
||||
shop_product_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '店铺商品ID',
|
||||
references: { model: 'shop_products', key: 'id' },
|
||||
onDelete: 'SET NULL',
|
||||
},
|
||||
name: { type: Sequelize.STRING(255), allowNull: true, comment: '商品名称(快照)' },
|
||||
code: { type: Sequelize.STRING(100), allowNull: true, comment: '商品编码(快照)' },
|
||||
spec: { type: Sequelize.STRING(255), allowNull: true, comment: '规格(快照)' },
|
||||
unit: { type: Sequelize.STRING(20), allowNull: true, comment: '单位' },
|
||||
quantity: { type: Sequelize.DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '数量' },
|
||||
price: { type: Sequelize.DECIMAL(12, 2), allowNull: true, comment: '单价' },
|
||||
total_amount: { type: Sequelize.DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '明细金额' },
|
||||
remark: { type: Sequelize.STRING(255), allowNull: true, comment: '备注' },
|
||||
created_at: { type: Sequelize.DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
|
||||
updated_at: { type: Sequelize.DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP') },
|
||||
},
|
||||
{ charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '出入库明细表' }
|
||||
);
|
||||
await queryInterface.addIndex('stock_items', { fields: ['bill_type', 'bill_id'], name: 'idx_stock_items_bill' });
|
||||
await queryInterface.addIndex('stock_items', { fields: ['principal_id'], name: 'idx_stock_items_principal' });
|
||||
await queryInterface.addIndex('stock_items', { fields: ['shop_id'], name: 'idx_stock_items_shop' });
|
||||
await queryInterface.addIndex('stock_items', { fields: ['product_id'], name: 'idx_stock_items_product' });
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable('stock_items');
|
||||
await queryInterface.dropTable('outbound_orders');
|
||||
await queryInterface.dropTable('inbound_orders');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,30 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 为入库单 / 出库单增加"创建人"字段,记录单据创建者的用户ID
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('inbound_orders', 'created_by', {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '创建人ID(关联 users)',
|
||||
references: { model: 'users', key: 'id' },
|
||||
onDelete: 'SET NULL',
|
||||
});
|
||||
await queryInterface.addColumn('outbound_orders', 'created_by', {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '创建人ID(关联 users)',
|
||||
references: { model: 'users', key: 'id' },
|
||||
onDelete: 'SET NULL',
|
||||
});
|
||||
await queryInterface.addIndex('inbound_orders', { fields: ['created_by'], name: 'idx_inbound_orders_created_by' });
|
||||
await queryInterface.addIndex('outbound_orders', { fields: ['created_by'], name: 'idx_outbound_orders_created_by' });
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.removeColumn('inbound_orders', 'created_by');
|
||||
await queryInterface.removeColumn('outbound_orders', 'created_by');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 新建仓库表,并把原外部接口(principal_external_apis)中的外部仓库数据迁移过来
|
||||
* principal_external_apis 表随后废弃(不再被任何接口使用)
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable(
|
||||
'warehouses',
|
||||
{
|
||||
id: { type: Sequelize.BIGINT.UNSIGNED, autoIncrement: true, primaryKey: true },
|
||||
principal_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属主体ID',
|
||||
references: { model: 'principals', key: 'id' },
|
||||
onDelete: 'CASCADE',
|
||||
},
|
||||
code: { type: Sequelize.STRING(50), allowNull: false, comment: '仓库编码' },
|
||||
name: { type: Sequelize.STRING(100), allowNull: false, comment: '仓库名称' },
|
||||
type: { type: Sequelize.STRING(50), comment: '仓库类型:wms/erp/other' },
|
||||
base_url: { type: Sequelize.STRING(255), comment: '接口基础地址' },
|
||||
app_key: { type: Sequelize.STRING(100), comment: '应用Key' },
|
||||
app_secret: { type: Sequelize.STRING(255), comment: '应用密钥' },
|
||||
extra: { type: Sequelize.JSON, comment: '扩展配置' },
|
||||
status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
|
||||
remark: { type: Sequelize.STRING(255), comment: '备注' },
|
||||
deleted_at: { type: Sequelize.DATE, comment: '软删除时间' },
|
||||
created_at: { type: Sequelize.DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
|
||||
updated_at: { type: Sequelize.DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP') },
|
||||
},
|
||||
{ charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '仓库' }
|
||||
);
|
||||
await queryInterface.addIndex('warehouses', { fields: ['principal_id'], name: 'idx_warehouses_principal' });
|
||||
await queryInterface.addIndex('warehouses', {
|
||||
fields: ['principal_id', 'code'],
|
||||
unique: true,
|
||||
name: 'uk_warehouses_principal_code',
|
||||
});
|
||||
|
||||
// 迁移原外部接口中的仓库数据(type 取原系统标识)
|
||||
await queryInterface.sequelize.query(`
|
||||
INSERT INTO warehouses (principal_id, code, name, type, base_url, app_key, app_secret, extra, status, remark, created_at, updated_at)
|
||||
SELECT principal_id, code, name, code, base_url, app_key, app_secret, extra, status, '由外部接口迁移', NOW(), NOW()
|
||||
FROM principal_external_apis
|
||||
`);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable('warehouses');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,58 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 入库单 / 出库单:新增仓库(warehouse_id)、商品总数(item_total)、商品种类数(item_kind)
|
||||
* 并把旧状态值重映射为新状态机:1待入/出库->已创建(1);2已入/出库->完成(4);3已取消->已取消(9)
|
||||
* 同时按现有明细回算商品总数与种类数
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const tables = [
|
||||
{ name: 'inbound_orders', billType: 1 },
|
||||
{ name: 'outbound_orders', billType: 2 },
|
||||
];
|
||||
for (const { name, billType } of tables) {
|
||||
await queryInterface.addColumn(name, 'warehouse_id', {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '仓库ID(关联 warehouses)',
|
||||
references: { model: 'warehouses', key: 'id' },
|
||||
onDelete: 'SET NULL',
|
||||
});
|
||||
await queryInterface.addColumn(name, 'item_total', {
|
||||
type: Sequelize.DECIMAL(12, 3),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '商品总数(明细数量合计)',
|
||||
});
|
||||
await queryInterface.addColumn(name, 'item_kind', {
|
||||
type: Sequelize.INTEGER.UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '商品种类数(不重复商品数)',
|
||||
});
|
||||
await queryInterface.addIndex(name, { fields: ['warehouse_id'], name: `idx_${name}_warehouse` });
|
||||
|
||||
// 旧状态重映射
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE ${name} SET status = CASE WHEN status = 2 THEN 4 WHEN status = 3 THEN 9 ELSE 1 END WHERE status IN (1, 2, 3)`
|
||||
);
|
||||
|
||||
// 按现有明细回算总数/种类数
|
||||
const recalc = `
|
||||
UPDATE ${name} t SET
|
||||
item_total = COALESCE((SELECT SUM(quantity) FROM stock_items si WHERE si.bill_type = ? AND si.bill_id = t.id), 0),
|
||||
item_kind = COALESCE((SELECT COUNT(DISTINCT CASE WHEN si.product_id IS NOT NULL THEN CONCAT('p', si.product_id) ELSE CONCAT('i', si.id) END) FROM stock_items si WHERE si.bill_type = ? AND si.bill_id = t.id), 0)
|
||||
`;
|
||||
await queryInterface.sequelize.query(recalc, { replacements: [billType, billType] });
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
for (const name of ['inbound_orders', 'outbound_orders']) {
|
||||
await queryInterface.removeColumn(name, 'warehouse_id');
|
||||
await queryInterface.removeColumn(name, 'item_total');
|
||||
await queryInterface.removeColumn(name, 'item_kind');
|
||||
}
|
||||
},
|
||||
};
|
||||
32
backend/database/migrations/20260910000300-product-fields.js
Normal file
32
backend/database/migrations/20260910000300-product-fields.js
Normal file
@ -0,0 +1,32 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 商品表:新增 货品编码(sku_code)、条码(barcode)、软删除(deleted_at)
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('products', 'sku_code', {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '货品编码',
|
||||
});
|
||||
await queryInterface.addColumn('products', 'barcode', {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '条码',
|
||||
});
|
||||
await queryInterface.addColumn('products', 'deleted_at', {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
});
|
||||
await queryInterface.addIndex('products', { fields: ['sku_code'], name: 'idx_products_sku_code' });
|
||||
await queryInterface.addIndex('products', { fields: ['barcode'], name: 'idx_products_barcode' });
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.removeColumn('products', 'sku_code');
|
||||
await queryInterface.removeColumn('products', 'barcode');
|
||||
await queryInterface.removeColumn('products', 'deleted_at');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,103 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 组合商品明细表:把「组合商品 ← 系统商品」的组合关系(系统商品ID + 数量)单独落库,
|
||||
* 取代原先 combo_products.items 的 JSON 冗余存储,便于库存展开、销量统计等后续复用。
|
||||
* 约束:同一组合内同一系统商品仅一条记录。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable(
|
||||
'combo_product_items',
|
||||
{
|
||||
id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
autoIncrement: true,
|
||||
primaryKey: true,
|
||||
},
|
||||
principal_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属主体ID',
|
||||
references: { model: 'principals', key: 'id' },
|
||||
},
|
||||
combo_product_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属组合商品ID',
|
||||
references: { model: 'combo_products', key: 'id' },
|
||||
onDelete: 'CASCADE',
|
||||
},
|
||||
product_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '系统商品ID(products.id)',
|
||||
references: { model: 'products', key: 'id' },
|
||||
onDelete: 'CASCADE',
|
||||
},
|
||||
quantity: {
|
||||
type: Sequelize.INTEGER.UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '该商品在组合中的数量',
|
||||
},
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
},
|
||||
},
|
||||
{ charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '组合商品明细表' }
|
||||
);
|
||||
|
||||
await queryInterface.addIndex('combo_product_items', {
|
||||
fields: [ 'combo_product_id', 'product_id' ],
|
||||
unique: true,
|
||||
name: 'uk_combo_product_items_combo_product',
|
||||
});
|
||||
await queryInterface.addIndex('combo_product_items', { fields: [ 'principal_id' ], name: 'idx_combo_product_items_principal' });
|
||||
await queryInterface.addIndex('combo_product_items', { fields: [ 'product_id' ], name: 'idx_combo_product_items_product' });
|
||||
|
||||
// 迁移历史 JSON 明细(combo_products.items)到关系表,确保存量数据不丢
|
||||
const [ rows ] = await queryInterface.sequelize.query(
|
||||
'SELECT id, principal_id, items FROM combo_products WHERE items IS NOT NULL'
|
||||
);
|
||||
for (const row of rows) {
|
||||
let items = row.items;
|
||||
if (typeof items === 'string') {
|
||||
try {
|
||||
items = JSON.parse(items);
|
||||
} catch (e) {
|
||||
items = null;
|
||||
}
|
||||
}
|
||||
if (!Array.isArray(items)) continue;
|
||||
for (const it of items) {
|
||||
const productId = Number(it && it.product_id);
|
||||
if (!productId) continue;
|
||||
const quantity = Number(it.quantity) > 0 ? Math.floor(Number(it.quantity)) : 1;
|
||||
await queryInterface.sequelize.query(
|
||||
'INSERT INTO combo_product_items (principal_id, combo_product_id, product_id, quantity) VALUES (?, ?, ?, ?)',
|
||||
{ replacements: [ row.principal_id, row.id, productId, quantity ] }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await queryInterface.removeColumn('combo_products', 'items');
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('combo_products', 'items', {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '组合明细:[{ "product_id": 1, "quantity": 2 }],关联 products.id',
|
||||
});
|
||||
await queryInterface.dropTable('combo_product_items');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,207 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 商品表对齐外部商品结构:
|
||||
* 1) 重命名:code→item_code、name→item_name、sku_code→goods_code、type→item_type、
|
||||
* category→category_name、spec→sku_property、unit→stock_unit、price→retail_price
|
||||
* 2) 新增外部字段:is_area_sale、length、width、height、volume、gross_weight、net_weight、
|
||||
* category_id、tag_price、is_sn_mgmt、is_shelf_life_mgmt、is_batch_mgmt、brand_name、
|
||||
* create_from、stock_id、warehouse_id、store_id
|
||||
* 3) OMS 专有字段(principal_id / status / deleted_at / image / remark / cost_price / barcode)原样保留;
|
||||
* 外部表的 is_valid、delete_at 与 OMS 的 status、deleted_at 语义重复,不再新增,避免出现两份真值
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
// ---------- 1. 重命名列,保持与外部商品表一致 ----------
|
||||
await queryInterface.renameColumn('products', 'code', 'item_code');
|
||||
await queryInterface.renameColumn('products', 'name', 'item_name');
|
||||
await queryInterface.renameColumn('products', 'sku_code', 'goods_code');
|
||||
await queryInterface.renameColumn('products', 'type', 'item_type');
|
||||
await queryInterface.renameColumn('products', 'category', 'category_name');
|
||||
await queryInterface.renameColumn('products', 'spec', 'sku_property');
|
||||
await queryInterface.renameColumn('products', 'unit', 'stock_unit');
|
||||
await queryInterface.renameColumn('products', 'price', 'retail_price');
|
||||
|
||||
// 按外部结构放宽长度(只放宽不收窄,避免历史数据被截断)
|
||||
await queryInterface.changeColumn('products', 'item_name', {
|
||||
type: Sequelize.STRING(255),
|
||||
allowNull: false,
|
||||
comment: '商品名称',
|
||||
});
|
||||
await queryInterface.changeColumn('products', 'category_name', {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '分类名称',
|
||||
});
|
||||
await queryInterface.changeColumn('products', 'goods_code', {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '货物编码',
|
||||
});
|
||||
await queryInterface.changeColumn('products', 'sku_property', {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: 'SKU规格',
|
||||
});
|
||||
await queryInterface.changeColumn('products', 'stock_unit', {
|
||||
type: Sequelize.STRING(20),
|
||||
allowNull: true,
|
||||
comment: '库存单位',
|
||||
});
|
||||
await queryInterface.changeColumn('products', 'item_type', {
|
||||
type: Sequelize.TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '商品类型',
|
||||
});
|
||||
await queryInterface.changeColumn('products', 'retail_price', {
|
||||
type: Sequelize.DECIMAL(12, 2),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '零售价',
|
||||
});
|
||||
|
||||
// ---------- 2. 索引名与列名对齐(先建新索引,再删旧索引,保证外键列始终有索引) ----------
|
||||
await queryInterface.addIndex('products', {
|
||||
fields: [ 'principal_id', 'item_code' ],
|
||||
unique: true,
|
||||
name: 'uk_products_principal_item_code',
|
||||
});
|
||||
await queryInterface.addIndex('products', { fields: [ 'goods_code' ], name: 'idx_products_goods_code' });
|
||||
await queryInterface.removeIndex('products', 'uk_products_principal_code');
|
||||
await queryInterface.removeIndex('products', 'idx_products_sku_code');
|
||||
|
||||
// ---------- 3. 新增外部字段 ----------
|
||||
await queryInterface.addColumn('products', 'is_area_sale', {
|
||||
type: Sequelize.STRING(1),
|
||||
allowNull: true,
|
||||
defaultValue: 'N',
|
||||
comment: '是否区域销售',
|
||||
});
|
||||
await queryInterface.addColumn('products', 'length', {
|
||||
type: Sequelize.DECIMAL(10, 2),
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '长度',
|
||||
});
|
||||
await queryInterface.addColumn('products', 'width', {
|
||||
type: Sequelize.DECIMAL(10, 2),
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '宽度',
|
||||
});
|
||||
await queryInterface.addColumn('products', 'height', {
|
||||
type: Sequelize.DECIMAL(10, 2),
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '高度',
|
||||
});
|
||||
await queryInterface.addColumn('products', 'volume', {
|
||||
type: Sequelize.DECIMAL(10, 2),
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '体积',
|
||||
});
|
||||
await queryInterface.addColumn('products', 'gross_weight', {
|
||||
type: Sequelize.INTEGER,
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '毛重(g)',
|
||||
});
|
||||
await queryInterface.addColumn('products', 'net_weight', {
|
||||
type: Sequelize.INTEGER,
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '净重(g)',
|
||||
});
|
||||
await queryInterface.addColumn('products', 'category_id', {
|
||||
type: Sequelize.INTEGER,
|
||||
allowNull: true,
|
||||
comment: '分类ID',
|
||||
});
|
||||
await queryInterface.addColumn('products', 'tag_price', {
|
||||
type: Sequelize.DECIMAL(10, 2),
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '标价',
|
||||
});
|
||||
await queryInterface.addColumn('products', 'is_sn_mgmt', {
|
||||
type: Sequelize.STRING(1),
|
||||
allowNull: true,
|
||||
defaultValue: 'N',
|
||||
comment: '是否序列号管理',
|
||||
});
|
||||
await queryInterface.addColumn('products', 'is_shelf_life_mgmt', {
|
||||
type: Sequelize.STRING(1),
|
||||
allowNull: true,
|
||||
defaultValue: 'N',
|
||||
comment: '是否保质期管理',
|
||||
});
|
||||
await queryInterface.addColumn('products', 'is_batch_mgmt', {
|
||||
type: Sequelize.STRING(1),
|
||||
allowNull: true,
|
||||
defaultValue: 'N',
|
||||
comment: '是否批次管理',
|
||||
});
|
||||
await queryInterface.addColumn('products', 'brand_name', {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '品牌名称',
|
||||
});
|
||||
await queryInterface.addColumn('products', 'create_from', {
|
||||
type: Sequelize.ENUM('self', 'qimen', 'api'),
|
||||
allowNull: true,
|
||||
comment: '数据来源',
|
||||
});
|
||||
await queryInterface.addColumn('products', 'stock_id', {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '库存ID',
|
||||
});
|
||||
await queryInterface.addColumn('products', 'warehouse_id', {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '仓库ID',
|
||||
});
|
||||
await queryInterface.addColumn('products', 'store_id', {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '门店ID',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
// 删除新增字段
|
||||
const dropColumns = [
|
||||
'is_area_sale', 'length', 'width', 'height', 'volume', 'gross_weight', 'net_weight',
|
||||
'category_id', 'tag_price', 'is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt',
|
||||
'brand_name', 'create_from', 'stock_id', 'warehouse_id', 'store_id',
|
||||
];
|
||||
for (const column of dropColumns) {
|
||||
await queryInterface.removeColumn('products', column);
|
||||
}
|
||||
|
||||
// 还原索引名
|
||||
await queryInterface.addIndex('products', {
|
||||
fields: [ 'principal_id', 'item_code' ],
|
||||
unique: true,
|
||||
name: 'uk_products_principal_code',
|
||||
});
|
||||
await queryInterface.addIndex('products', { fields: [ 'goods_code' ], name: 'idx_products_sku_code' });
|
||||
await queryInterface.removeIndex('products', 'uk_products_principal_item_code');
|
||||
await queryInterface.removeIndex('products', 'idx_products_goods_code');
|
||||
|
||||
// 还原长度
|
||||
await queryInterface.changeColumn('products', 'item_name', {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: false,
|
||||
comment: '商品名称',
|
||||
});
|
||||
await queryInterface.changeColumn('products', 'category_name', {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: true,
|
||||
comment: '分类',
|
||||
});
|
||||
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,19 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 商品图片组:products.images 存 URL 数组(JSON),首张为主图
|
||||
* 保留原有 products.image 单图字段,作为主图冗余,兼容外部系统与历史数据
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('products', 'images', {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '图片组(URL 数组,首张为主图)',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.removeColumn('products', 'images');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,75 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 外部仓库拆分为两张表:
|
||||
* 1) warehouses 仅保留仓库基础信息(code / name / type / status / remark)
|
||||
* 2) warehouse_apis 存放仓库的接口配置,一个仓库可有多条接口配置
|
||||
* 原 warehouses 上的接口字段数据迁移到 warehouse_apis(每仓库一条「默认配置」),随后删除这些字段
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable(
|
||||
'warehouse_apis',
|
||||
{
|
||||
id: { type: Sequelize.BIGINT.UNSIGNED, autoIncrement: true, primaryKey: true },
|
||||
principal_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属主体ID',
|
||||
references: { model: 'principals', key: 'id' },
|
||||
onDelete: 'CASCADE',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属仓库ID',
|
||||
references: { model: 'warehouses', key: 'id' },
|
||||
onDelete: 'CASCADE',
|
||||
},
|
||||
name: { type: Sequelize.STRING(100), allowNull: false, comment: '接口配置名称' },
|
||||
type: { type: Sequelize.STRING(50), comment: '接口类型:wms/erp/other' },
|
||||
base_url: { type: Sequelize.STRING(255), comment: '接口基础地址' },
|
||||
app_key: { type: Sequelize.STRING(100), comment: '应用Key' },
|
||||
app_secret: { type: Sequelize.STRING(255), comment: '应用密钥' },
|
||||
extra: { type: Sequelize.JSON, comment: '扩展配置' },
|
||||
status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
|
||||
remark: { type: Sequelize.STRING(255), comment: '备注' },
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
},
|
||||
},
|
||||
{ charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '仓库接口配置表' }
|
||||
);
|
||||
await queryInterface.addIndex('warehouse_apis', { fields: [ 'principal_id' ], name: 'idx_warehouse_apis_principal' });
|
||||
await queryInterface.addIndex('warehouse_apis', { fields: [ 'warehouse_id' ], name: 'idx_warehouse_apis_warehouse' });
|
||||
|
||||
// 迁移仓库上已有的接口配置(存在任一接口字段即生成一条配置)
|
||||
await queryInterface.sequelize.query(`
|
||||
INSERT INTO warehouse_apis (principal_id, warehouse_id, name, type, base_url, app_key, app_secret, extra, status, remark, created_at, updated_at)
|
||||
SELECT principal_id, id, '默认配置', type, base_url, app_key, app_secret, extra, status, '由仓库配置迁移', NOW(), NOW()
|
||||
FROM warehouses
|
||||
WHERE base_url IS NOT NULL OR app_key IS NOT NULL OR app_secret IS NOT NULL OR extra IS NOT NULL
|
||||
`);
|
||||
|
||||
// 仓库表不再承载接口配置字段
|
||||
await queryInterface.removeColumn('warehouses', 'base_url');
|
||||
await queryInterface.removeColumn('warehouses', 'app_key');
|
||||
await queryInterface.removeColumn('warehouses', 'app_secret');
|
||||
await queryInterface.removeColumn('warehouses', 'extra');
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('warehouses', 'base_url', { type: Sequelize.STRING(255), comment: '接口基础地址' });
|
||||
await queryInterface.addColumn('warehouses', 'app_key', { type: Sequelize.STRING(100), comment: '应用Key' });
|
||||
await queryInterface.addColumn('warehouses', 'app_secret', { type: Sequelize.STRING(255), comment: '应用密钥' });
|
||||
await queryInterface.addColumn('warehouses', 'extra', { type: Sequelize.JSON, comment: '扩展配置' });
|
||||
await queryInterface.dropTable('warehouse_apis');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,63 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 仓库-商品关联表:只做极简关联,记录某个商品是否已推送到某个仓库
|
||||
* - pushed:是否已推送(1是 0否)
|
||||
* - pushed_at:最近一次推送时间
|
||||
* 删除仓库或删除仓库接口配置时,都会清空该仓库下的关联数据
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable(
|
||||
'warehouse_products',
|
||||
{
|
||||
id: { type: Sequelize.BIGINT.UNSIGNED, autoIncrement: true, primaryKey: true },
|
||||
principal_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属主体ID',
|
||||
references: { model: 'principals', key: 'id' },
|
||||
onDelete: 'CASCADE',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID',
|
||||
references: { model: 'warehouses', key: 'id' },
|
||||
onDelete: 'CASCADE',
|
||||
},
|
||||
product_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '商品ID',
|
||||
references: { model: 'products', key: 'id' },
|
||||
onDelete: 'CASCADE',
|
||||
},
|
||||
pushed: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 0, comment: '是否已推送到仓库:1是 0否' },
|
||||
pushed_at: { type: Sequelize.DATE, comment: '最近一次推送时间' },
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
},
|
||||
},
|
||||
{ charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '仓库-商品关联表(是否推送到仓库)' }
|
||||
);
|
||||
await queryInterface.addIndex('warehouse_products', {
|
||||
fields: [ 'warehouse_id', 'product_id' ],
|
||||
unique: true,
|
||||
name: 'uk_warehouse_products_warehouse_product',
|
||||
});
|
||||
await queryInterface.addIndex('warehouse_products', { fields: [ 'principal_id' ], name: 'idx_warehouse_products_principal' });
|
||||
await queryInterface.addIndex('warehouse_products', { fields: [ 'product_id' ], name: 'idx_warehouse_products_product' });
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable('warehouse_products');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,56 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 对外 API 请求记录表(OMS → 外部 WMS 的调用,如 index.ping / singleitem.synchronize)
|
||||
* 与入站 request_logs 区分,用于排查推送失败、鉴权异常、地址不可达等问题
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable(
|
||||
'api_outbound_logs',
|
||||
{
|
||||
id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
autoIncrement: true,
|
||||
primaryKey: true,
|
||||
},
|
||||
principal_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: '所属主体ID' },
|
||||
warehouse_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: '关联仓库ID' },
|
||||
warehouse_api_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: '使用的接口配置ID' },
|
||||
api_type: { type: Sequelize.STRING(50), defaultValue: 'qimen', comment: '接口类型(类奇门JSON接口等)' },
|
||||
method: { type: Sequelize.STRING(100), allowNull: false, comment: 'WMS 方法名,如 index.ping / singleitem.synchronize' },
|
||||
url: { type: Sequelize.TEXT, allowNull: true, comment: '完整请求地址(含 query,sign 已脱敏)' },
|
||||
request_headers: { type: Sequelize.TEXT, allowNull: true, comment: '请求头 JSON' },
|
||||
request_body: { type: Sequelize.TEXT, allowNull: true, comment: '请求报文 JSON(敏感字段已脱敏)' },
|
||||
response_status: { type: Sequelize.INTEGER, allowNull: true, comment: 'HTTP 状态码' },
|
||||
response_body: { type: Sequelize.TEXT, allowNull: true, comment: '响应报文(超长截断)' },
|
||||
is_success: { type: Sequelize.TINYINT, defaultValue: 0, comment: '传输层是否成功(HTTP 2xx 且可解析)' },
|
||||
business_code: { type: Sequelize.STRING(32), allowNull: true, comment: 'WMS 业务码' },
|
||||
business_message: { type: Sequelize.STRING(255), allowNull: true, comment: 'WMS 业务提示' },
|
||||
error: { type: Sequelize.TEXT, allowNull: true, comment: '异常信息(网络/DNS/超时/非JSON等)' },
|
||||
duration: { type: Sequelize.INTEGER, allowNull: true, comment: '耗时(毫秒)' },
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
},
|
||||
},
|
||||
{ charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '对外API请求记录表' }
|
||||
);
|
||||
|
||||
await queryInterface.addIndex('api_outbound_logs', { fields: [ 'principal_id' ], name: 'idx_oblog_principal' });
|
||||
await queryInterface.addIndex('api_outbound_logs', { fields: [ 'warehouse_id' ], name: 'idx_oblog_warehouse' });
|
||||
await queryInterface.addIndex('api_outbound_logs', { fields: [ 'warehouse_api_id' ], name: 'idx_oblog_api' });
|
||||
await queryInterface.addIndex('api_outbound_logs', { fields: [ 'created_at' ], name: 'idx_oblog_created' });
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable('api_outbound_logs');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,19 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 仓库-商品关联表新增 wms_item_id:记录该商品在 WMS 内部的商品主键ID,
|
||||
* 推送(singleitem.synchronize)成功时由 WMS 返回,用于后续按 itemId 批量查询 WMS 库存(inventory.query)
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('warehouse_products', 'wms_item_id', {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: 'WMS 内部商品ID(singleitem.synchronize 返回),用于按 itemId 查询库存',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.removeColumn('warehouse_products', 'wms_item_id');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,58 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 商品系统库存副表 product_stocks:
|
||||
* 每个系统商品一行,记录总数量 / 锁定数量 / 可用数量(可用 = 总 - 锁定)
|
||||
* - 入库单完成 -> 增加总数量
|
||||
* - 出库单推送 -> 增加锁定数量(占用可用)
|
||||
* - WMS 发货通知(notify.delivery) -> 扣减总数量与锁定数量
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable(
|
||||
'product_stocks',
|
||||
{
|
||||
id: { type: Sequelize.BIGINT.UNSIGNED, autoIncrement: true, primaryKey: true },
|
||||
principal_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属主体ID',
|
||||
references: { model: 'principals', key: 'id' },
|
||||
onDelete: 'CASCADE',
|
||||
},
|
||||
product_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '系统商品ID',
|
||||
references: { model: 'products', key: 'id' },
|
||||
onDelete: 'CASCADE',
|
||||
},
|
||||
quantity: { type: Sequelize.DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '总数量' },
|
||||
lock_quantity: { type: Sequelize.DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '锁定数量' },
|
||||
available: { type: Sequelize.DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '可用数量 = 总数量 - 锁定数量' },
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
},
|
||||
},
|
||||
{ charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '商品系统库存副表' }
|
||||
);
|
||||
await queryInterface.addIndex('product_stocks', { fields: [ 'principal_id' ], name: 'idx_product_stocks_principal' });
|
||||
await queryInterface.addIndex('product_stocks', { fields: [ 'product_id' ], name: 'idx_product_stocks_product' });
|
||||
await queryInterface.addIndex('product_stocks', {
|
||||
fields: [ 'principal_id', 'product_id' ],
|
||||
unique: true,
|
||||
name: 'uk_product_stocks_principal_product',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable('product_stocks');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,36 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* product_stocks 增加「残次品」维度:
|
||||
* - 原 quantity / lock_quantity / available 视为「正品」总/锁定/可用
|
||||
* - 新增 defect_quantity / defect_lock_quantity / defect_available 作为「残次品」
|
||||
* 旧数据 defect_* 默认 0,即全部库存归为正品,向前兼容
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('product_stocks', 'defect_quantity', {
|
||||
type: Sequelize.DECIMAL(12, 3),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '残次品总数量',
|
||||
});
|
||||
await queryInterface.addColumn('product_stocks', 'defect_lock_quantity', {
|
||||
type: Sequelize.DECIMAL(12, 3),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '残次品锁定数量',
|
||||
});
|
||||
await queryInterface.addColumn('product_stocks', 'defect_available', {
|
||||
type: Sequelize.DECIMAL(12, 3),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '残次品可用数量 = 总数量 - 锁定数量',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.removeColumn('product_stocks', 'defect_quantity');
|
||||
await queryInterface.removeColumn('product_stocks', 'defect_lock_quantity');
|
||||
await queryInterface.removeColumn('product_stocks', 'defect_available');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,58 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* product_stocks 存储由「单行 + defect_* 列」改为「按 item_type 分多行」:
|
||||
* - 新增 item_type 列(ZC=正品 / CC=残次品,与 WMS itemType 对齐),非空默认 ZC
|
||||
* - 将既有行的 defect_*(残次品数量)回填为独立的 CC 行,避免数据丢失
|
||||
* - 删除 defect_quantity / defect_lock_quantity / defect_available 三列
|
||||
* - 建立 (product_id, item_type) 唯一索引,保证每个商品每种类型仅一行
|
||||
* 兼容说明:若 defect 列已不存在(全新库),跳过回填与删列,仅建列与索引。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const cols = await queryInterface.describeTable('product_stocks');
|
||||
const hasDefect = !!cols.defect_quantity;
|
||||
|
||||
await queryInterface.addColumn('product_stocks', 'item_type', {
|
||||
type: Sequelize.STRING(4),
|
||||
allowNull: false,
|
||||
defaultValue: 'ZC',
|
||||
comment: '存储类型:ZC=正品 CC=残次品',
|
||||
});
|
||||
|
||||
if (hasDefect) {
|
||||
// 既有残次品数据回填为 CC 行(仅在残次品数量非零时)
|
||||
await queryInterface.sequelize.query(`
|
||||
INSERT INTO product_stocks
|
||||
(principal_id, product_id, item_type, quantity, lock_quantity, available, created_at, updated_at)
|
||||
SELECT
|
||||
principal_id, product_id, 'CC',
|
||||
defect_quantity, defect_lock_quantity, defect_available, NOW(), NOW()
|
||||
FROM product_stocks
|
||||
WHERE defect_quantity <> 0 OR defect_lock_quantity <> 0 OR defect_available <> 0
|
||||
`);
|
||||
await queryInterface.removeColumn('product_stocks', 'defect_quantity');
|
||||
await queryInterface.removeColumn('product_stocks', 'defect_lock_quantity');
|
||||
await queryInterface.removeColumn('product_stocks', 'defect_available');
|
||||
}
|
||||
|
||||
await queryInterface.addIndex('product_stocks', [ 'product_id', 'item_type' ], {
|
||||
unique: true,
|
||||
name: 'uniq_product_stock_type',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.removeIndex('product_stocks', 'uniq_product_stock_type');
|
||||
const cols = await queryInterface.describeTable('product_stocks');
|
||||
if (cols.defect_quantity) {
|
||||
// 已回滚:无需处理 CC 行(降级时残次品数据暂不可恢复,属不可逆迁移)
|
||||
await queryInterface.removeColumn('product_stocks', 'defect_quantity');
|
||||
await queryInterface.removeColumn('product_stocks', 'defect_lock_quantity');
|
||||
await queryInterface.removeColumn('product_stocks', 'defect_available');
|
||||
}
|
||||
if (cols.item_type) {
|
||||
await queryInterface.removeColumn('product_stocks', 'item_type');
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,48 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 修正 products 表列名,使其与外部商品结构及 Product 模型保持一致:
|
||||
* code→item_code、name→item_name、sku_code→goods_code、type→item_type、
|
||||
* category→category_name、spec→sku_property、unit→stock_unit、price→retail_price
|
||||
*
|
||||
* 背景:迁移 20260910000500 曾把上述列改名后又改回旧名,导致 Product 模型/控制器按
|
||||
* item_code / item_name / item_type 等查询时报 "Unknown column 'item_type' in 'field list'"。
|
||||
* 本迁移幂等:仅当旧列存在、新列不存在时才重命名,可重复执行。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const cols = await queryInterface.describeTable('products');
|
||||
const has = (n) => Object.prototype.hasOwnProperty.call(cols, n);
|
||||
const rename = async (from, to) => {
|
||||
if (has(from) && !has(to)) {
|
||||
await queryInterface.renameColumn('products', from, to);
|
||||
}
|
||||
};
|
||||
await rename('code', 'item_code');
|
||||
await rename('name', 'item_name');
|
||||
await rename('sku_code', 'goods_code');
|
||||
await rename('type', 'item_type');
|
||||
await rename('category', 'category_name');
|
||||
await rename('spec', 'sku_property');
|
||||
await rename('unit', 'stock_unit');
|
||||
await rename('price', 'retail_price');
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const cols = await queryInterface.describeTable('products');
|
||||
const has = (n) => Object.prototype.hasOwnProperty.call(cols, n);
|
||||
const rename = async (from, to) => {
|
||||
if (has(from) && !has(to)) {
|
||||
await queryInterface.renameColumn('products', from, to);
|
||||
}
|
||||
};
|
||||
await rename('item_code', 'code');
|
||||
await rename('item_name', 'name');
|
||||
await rename('goods_code', 'sku_code');
|
||||
await rename('item_type', 'type');
|
||||
await rename('category_name', 'category');
|
||||
await rename('sku_property', 'spec');
|
||||
await rename('stock_unit', 'unit');
|
||||
await rename('retail_price', 'price');
|
||||
},
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user