liufumingren ab630e7c01 feat(external-print): 订单拉取与定时同步,组合商品拆分为最小单位
后端能力:
- 接入店管家订单接口(/NewOrder/List),明细归一化后按店铺商品匹配系统商品/组合商品
- 新增 service/externalPrintOrder:手动与定时拉单共用入库逻辑,同时写入待审核状态分表
- 新增 schedule/fetchExternalShopOrders:按店铺配置的间隔自动拉单(最小 3 分钟,起点重叠 10 分钟)
- 新增 lib/orderItemExpand + service/orderItemResolve:平台行与最小单位行互转;
  绑定组合商品时按「数量 = 平台数量 x 组合内数量、单价取子商品零售价」拆成子商品行,解绑可还原
- 明细新增 platform_snapshot,保留平台原样(编码/名称/规格/图片/原行号/原数量/原单价)
- 店铺商品列表支持 has_unbound_order 筛选,订单列表支持 exclude_unbound(均已同步导出定义)
- 店铺商品只读化:移除新增/编辑/删除动作,仅保留查询与绑定;
  同步商品时平台已不存在的商品自动清理(未绑定且未被订单引用直接删除,已绑定或被引用仅下架)
- 新增 scripts/rebuild-order-items 存量明细重建脚本,新增 orderItemExpand 单测(8 项)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-03 03:29:09 +08:00

335 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

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

'use strict';
const { Controller } = require('egg');
const { parsePagination, buildPageResult } = require('../lib/pagination');
/** OMS 内创建的店铺编码前缀:用于区分「OMS 自动生成」与「平台店铺ID」 */
const CODE_PREFIX = 'OMS';
/** 店铺类型:1 平台店铺(手工/平台)2 外部打单平台商家 */
const SHOP_TYPE_PLATFORM = 1;
/** 自动拉取订单的最小间隔(分钟) */
const MIN_AUTO_FETCH_INTERVAL = 3;
/**
* 解析自动拉取订单配置
* @param {Object} body 请求体
* @return {{auto_fetch_order?: number, auto_fetch_interval?: number, error?: string}} 解析结果
*/
function parseAutoFetchConfig(body) {
const result = {};
if (body.auto_fetch_order !== undefined) {
const flag = body.auto_fetch_order;
result.auto_fetch_order = flag === true || Number(flag) === 1 ? 1 : 0;
}
const rawInterval = body.auto_fetch_interval;
if (rawInterval !== undefined && rawInterval !== null && rawInterval !== '') {
const interval = Number(rawInterval);
if (!Number.isInteger(interval) || interval < MIN_AUTO_FETCH_INTERVAL) {
return { error: `自动拉取间隔必须是不小于 ${MIN_AUTO_FETCH_INTERVAL} 的整数(分钟)` };
}
result.auto_fetch_interval = interval;
}
return result;
}
/** 生成店铺编码: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禁用,不传则不过滤
* @request query integer type 店铺类型:1平台店铺 2外部打单平台商家,不传则不过滤
* @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, type } = 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);
if (type !== undefined && type !== '') where.type = Number(type);
const { count, rows } = await ctx.model.Shop.findAndCountAll({
where,
offset,
limit,
order: [[ 'id', 'DESC' ]],
});
// 数据库模式(预留)的密码不回显
const list = rows.map(row => {
const plain = row.get({ plain: true });
plain.has_db_password = !!plain.db_password;
delete plain.db_password;
return plain;
});
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, 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,
}),
]);
const data = shop.get({ plain: true });
data.has_db_password = !!data.db_password;
delete data.db_password;
ctx.body = {
code: 0,
message: 'success',
data: {
...data,
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;
}
const autoFetch = parseAutoFetchConfig(ctx.request.body);
if (autoFetch.error) {
ctx.status = 400;
ctx.body = { code: 400, message: autoFetch.error };
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 body = { ...ctx.request.body };
delete body.type;
delete body.external_print_account_id;
delete body.external_data;
delete body.db_host;
delete body.db_port;
delete body.db_name;
delete body.db_username;
delete body.db_password;
const shop = await ctx.model.Shop.create({
...body,
type: SHOP_TYPE_PLATFORM,
code: shopCode,
auto_fetch_order: autoFetch.auto_fetch_order == null ? 0 : autoFetch.auto_fetch_order,
auto_fetch_interval: autoFetch.auto_fetch_interval == null
? MIN_AUTO_FETCH_INTERVAL
: autoFetch.auto_fetch_interval,
});
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;
// 外部平台导入 / 数据库模式相关字段由对应接入逻辑维护,普通编辑不允许修改
delete ctx.request.body.type;
delete ctx.request.body.external_print_account_id;
delete ctx.request.body.external_data;
delete ctx.request.body.db_host;
delete ctx.request.body.db_port;
delete ctx.request.body.db_name;
delete ctx.request.body.db_username;
delete ctx.request.body.db_password;
// 拉单状态由系统写入(手动/定时拉取),不允许编辑接口修改
delete ctx.request.body.last_order_sync_at;
delete ctx.request.body.last_order_sync_msg;
const autoFetch = parseAutoFetchConfig(ctx.request.body);
if (autoFetch.error) {
ctx.status = 400;
ctx.body = { code: 400, message: autoFetch.error };
return;
}
Object.assign(ctx.request.body, autoFetch);
// 编码留空视为不修改;改动时校验同主体唯一,避免撞唯一索引报 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;