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>
This commit is contained in:
liufumingren 2026-11-03 03:29:06 +08:00
parent 969c68f5f9
commit ab630e7c01
30 changed files with 3748 additions and 194 deletions

View File

@ -52,6 +52,16 @@ const shopItem = {
contact_name: { type: 'string', description: '联系人' },
contact_phone: { type: 'string', description: '联系电话' },
status: { type: 'integer', description: '状态:1启用 0禁用' },
type: { type: 'integer', description: '店铺类型:1平台店铺 2外部打单平台商家 3数据库模式(预留)' },
external_print_account_id: { type: 'integer', description: '来源外部打单账号ID(type=2 时有值)' },
external_data: { type: 'string', description: '外部打单平台返回的商家原始结构 JSON' },
db_host: { type: 'string', description: '数据库地址(type=3 数据库模式店铺使用,预留)' },
db_port: { type: 'integer', description: '数据库端口(type=3 数据库模式店铺使用,预留)' },
db_name: { type: 'string', description: '数据库名(type=3 数据库模式店铺使用,预留)' },
db_username: { type: 'string', description: '数据库账号(type=3 数据库模式店铺使用,预留)' },
has_db_password: { type: 'boolean', description: '是否已配置数据库密码(密码本身不回显)' },
auto_fetch_order: { type: 'integer', description: '是否自动拉取订单:1是 0否' },
auto_fetch_interval: { type: 'integer', description: '自动拉取订单间隔(分钟,最小 3)' },
extra: { type: 'string', description: '扩展配置 JSON' },
remark: { type: 'string', description: '备注' },
created_at: { type: 'string', description: '创建时间' },
@ -922,6 +932,7 @@ module.exports = {
quantity: { type: 'number', description: '数量' },
price: { type: 'number', description: '单价' },
total_amount: { type: 'number', description: '明细金额' },
platform_snapshot: { type: 'string', description: '平台明细快照 JSON(绑定前编码/名称/规格/图片,解绑时还原用)' },
created_at: { type: 'string', description: '创建时间' },
updated_at: { type: 'string', description: '更新时间' },
},
@ -989,6 +1000,8 @@ module.exports = {
contact_name: { type: 'string', description: '联系人' },
contact_phone: { type: 'string', description: '联系电话' },
status: { type: 'integer', description: '状态:1启用 0禁用,默认1' },
auto_fetch_order: { type: 'integer', description: '是否自动拉取订单:1是 0否,默认0' },
auto_fetch_interval: { type: 'integer', description: '自动拉取订单间隔(分钟,最小 3),默认3' },
extra: { type: 'string', description: '扩展配置 JSON' },
remark: { type: 'string', description: '备注' },
},
@ -999,6 +1012,10 @@ module.exports = {
contact_name: { type: 'string', description: '联系人' },
contact_phone: { type: 'string', description: '联系电话' },
status: { type: 'integer', description: '状态:1启用 0禁用' },
auto_fetch_order: { type: 'integer', description: '是否自动拉取订单:1是 0否' },
auto_fetch_interval: { type: 'integer', description: '自动拉取订单间隔(分钟,最小 3)' },
last_order_sync_at: { type: 'string', description: '最近一次拉取订单时间(系统写入)' },
last_order_sync_msg: { type: 'string', description: '最近一次拉取订单结果/失败原因(系统写入)' },
extra: { type: 'string', description: '扩展配置 JSON' },
remark: { type: 'string', description: '备注' },
},
@ -1070,6 +1087,130 @@ module.exports = {
message: { type: 'string', description: '提示信息' },
data: { type: 'externalPrintAccountLoginResult', description: '登录结果' },
},
externalPrintMerchantItem: {
external_id: { type: 'string', description: '平台侧商家ID' },
name: { type: 'string', description: '商家名称' },
contact_name: { type: 'string', description: '联系人' },
contact_phone: { type: 'string', description: '联系电话' },
status: { type: 'integer', description: '状态:1正常 0停用' },
remark: { type: 'string', description: '备注(如商家分组)' },
added: { type: 'boolean', description: '是否已创建到 OMS 店铺' },
raw: { type: 'string', description: '平台返回的商家原始结构 JSON' },
},
externalPrintMerchantPage: buildPage('externalPrintMerchantItem', '外部打单平台商家列表'),
externalPrintMerchantListResponse: buildListResponse('externalPrintMerchantPage'),
createShopsFromMerchantsRequest: {
principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' },
merchants: { type: 'array', itemType: 'externalPrintMerchantItem', required: true, description: '要创建到店铺的商家列表(取自商家列表接口)' },
},
externalPrintShopCreatedItem: {
id: { type: 'integer', description: '店铺主键' },
code: { type: 'string', description: '店铺编码(平台标识-账号ID-商家ID)' },
name: { type: 'string', description: '店铺名称' },
},
externalPrintShopCreateResult: {
created: { type: 'integer', description: '成功创建数量' },
skipped: { type: 'integer', description: '跳过数量(已存在或缺少商家ID)' },
shops: { type: 'array', itemType: 'externalPrintShopCreatedItem', description: '新创建的店铺' },
},
externalPrintShopCreateResponse: {
code: { type: 'integer', description: '业务状态码,0 成功' },
message: { type: 'string', description: '提示信息' },
data: { type: 'externalPrintShopCreateResult', description: '创建结果' },
},
externalPrintShopProductSyncArea: {
dbname: { type: 'string', description: '分区库名,空表示默认区' },
name: { type: 'string', description: '分区名称(如「新系统区」)' },
total: { type: 'integer', description: '平台返回的商品总数' },
unique: { type: 'integer', description: '去重后的商品数' },
pages: { type: 'integer', description: '拉取页数' },
verified: { type: 'boolean', description: '该分区快照是否完整(去重数 = Total)' },
},
externalPrintShopProductSyncHost: {
host: { type: 'string', description: '商品接口域名' },
total: { type: 'integer', description: '该域名各分区商品总数之和' },
unique: { type: 'integer', description: '该域名去重后的商品数' },
pages: { type: 'integer', description: '拉取页数' },
verified: { type: 'boolean', description: '该域名快照是否完整(各分区去重数 = Total)' },
areas: { type: 'array', itemType: 'externalPrintShopProductSyncArea', description: '各分区拉取明细' },
},
externalPrintShopProductSyncResult: {
total: { type: 'integer', description: '各域名商品总数之和' },
unique: { type: 'integer', description: '写入的商品行数(商品 + 规格去重后)' },
created: { type: 'integer', description: '新增商品行数' },
updated: { type: 'integer', description: '更新商品行数' },
removed: { type: 'integer', description: '已删除的商品行数(平台已不存在,且未绑定系统商品、未被订单明细引用)' },
offline: { type: 'integer', description: '保留并标为下架的商品行数(平台已不存在,但已绑定系统商品/组合商品或被订单明细引用)' },
verified: { type: 'boolean', description: '快照是否完整;不完整时不会移除任何商品' },
hosts: { type: 'array', itemType: 'externalPrintShopProductSyncHost', description: '各域名的拉取明细' },
},
externalPrintShopProductSyncResponse: {
code: { type: 'integer', description: '业务状态码,0 成功' },
message: { type: 'string', description: '提示信息' },
data: { type: 'externalPrintShopProductSyncResult', description: '同步结果' },
},
pullShopProductsItem: {
outer_item_id: { type: 'string', required: true, description: '平台商品ID(订单明细的 outer_item_id)' },
outer_sku_id: { type: 'string', description: '平台规格ID(订单明细的 outer_sku_id)' },
},
pullShopProductsRequest: {
principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' },
items: { type: 'array', itemType: 'pullShopProductsItem', required: true, description: '待补拉的商品列表,单次最多 50 个' },
},
externalPrintShopProductPullMissing: {
outer_item_id: { type: 'string', description: '平台商品ID' },
outer_sku_id: { type: 'string', description: '平台规格ID' },
reason: { type: 'string', description: '未命中的原因' },
},
externalPrintShopProductPullItem: {
id: { type: 'integer', description: '店铺商品ID(可用于绑定)' },
shop_id: { type: 'integer', description: '所属店铺ID' },
outer_item_id: { type: 'string', description: '平台商品ID' },
outer_sku_id: { type: 'string', description: '平台规格ID' },
title: { type: 'string', description: '商品标题' },
spec: { type: 'string', description: '规格' },
platform_type: { type: 'string', description: '外部平台类型' },
status: { type: 'integer', description: '状态:1在售 0下架' },
bind_type: { type: 'integer', description: '绑定类型:0未绑定 1系统商品 2组合商品' },
product_id: { type: 'integer', description: '绑定的系统商品ID' },
combo_product_id: { type: 'integer', description: '绑定的组合商品ID' },
},
externalPrintShopProductPullResult: {
requested: { type: 'integer', description: '提交的商品数' },
matched: { type: 'integer', description: '命中的商品行数(商品 + 规格)' },
created: { type: 'integer', description: '新增的店铺商品行数' },
updated: { type: 'integer', description: '更新的店铺商品行数' },
hosts: { type: 'array', itemType: 'string', description: '命中的域名与分区' },
missing: { type: 'array', itemType: 'externalPrintShopProductPullMissing', description: '未命中的商品及原因' },
products: { type: 'array', itemType: 'externalPrintShopProductPullItem', description: '拉取后写入的店铺商品' },
},
externalPrintShopProductPullResponse: {
code: { type: 'integer', description: '业务状态码,0 成功' },
message: { type: 'string', description: '提示信息' },
data: { type: 'externalPrintShopProductPullResult', description: '单品补拉结果' },
},
syncShopOrdersRequest: {
principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' },
start_time: { type: 'string', description: '平台下单时间起(yyyy-MM-dd HH:mm:ss),与 days 二选一' },
end_time: { type: 'string', description: '平台下单时间止,默认当前时间' },
days: { type: 'integer', description: '未传 start_time 时按最近 N 天拉取,默认 1' },
},
externalPrintShopOrderSyncResult: {
start_time: { type: 'string', description: '本次拉取的下单时间起' },
end_time: { type: 'string', description: '本次拉取的下单时间止' },
orders: { type: 'integer', description: '拉取到的订单数' },
created: { type: 'integer', description: '新增订单数' },
updated: { type: 'integer', description: '更新订单数' },
items: { type: 'integer', description: '写入的订单明细数' },
items_bound: { type: 'integer', description: '已匹配到绑定系统商品/组合商品的明细数' },
items_unbound: { type: 'integer', description: '未绑定系统商品的明细数(保留平台原样快照)' },
hosts: { type: 'array', itemType: 'string', description: '拉取命中的域名与分区' },
},
externalPrintShopOrderSyncResponse: {
code: { type: 'integer', description: '业务状态码,0 成功' },
message: { type: 'string', description: '提示信息' },
data: { type: 'externalPrintShopOrderSyncResult', description: '订单拉取结果' },
},
// ---------- 店铺商品 shop_products ----------
shopProductItem: {
@ -1085,6 +1226,9 @@ module.exports = {
price: { type: 'number', description: '店铺售价' },
stock: { type: 'integer', description: '采集到的库存' },
status: { type: 'integer', description: '店铺商品状态:1在售 0下架' },
platform_type: { type: 'string', description: '外部平台类型:TouTiao/Taobao/Pinduoduo 等(外部平台采集时有值)' },
external_shop_id: { type: 'string', description: '外部平台的店铺ID(如店管家 ShopId)' },
unbound_order_count: { type: 'integer', description: '引用该商品但未绑定系统商品的订单数(列表接口回填,0 表示无待处理订单)' },
bind_type: { type: 'integer', description: '绑定类型:0未绑定 1系统商品 2组合商品' },
product_id: { type: 'integer', description: '绑定的系统商品ID' },
combo_product_id: { type: 'integer', description: '绑定的组合商品ID' },
@ -1094,30 +1238,6 @@ module.exports = {
},
shopProductPage: buildPage('shopProductItem', '店铺商品列表'),
shopProductListResponse: buildListResponse('shopProductPage'),
createShopProductRequest: {
principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' },
shop_id: { type: 'integer', required: true, description: '所属店铺ID' },
outer_item_id: { type: 'string', required: true, description: '平台商品ID' },
outer_sku_id: { type: 'string', description: '平台规格ID,无规格时为空' },
title: { type: 'string', description: '商品标题' },
outer_code: { type: 'string', description: '商家编码' },
spec: { type: 'string', description: '规格' },
image: { type: 'string', description: '图片' },
price: { type: 'number', description: '店铺售价' },
stock: { type: 'integer', description: '库存' },
status: { type: 'integer', description: '状态:1在售 0下架,默认1' },
raw: { type: 'string', description: '采集原始数据 JSON' },
},
updateShopProductRequest: {
title: { type: 'string', description: '商品标题' },
outer_code: { type: 'string', description: '商家编码' },
spec: { type: 'string', description: '规格' },
image: { type: 'string', description: '图片' },
price: { type: 'number', description: '店铺售价' },
stock: { type: 'integer', description: '库存' },
status: { type: 'integer', description: '状态:1在售 0下架' },
raw: { type: 'string', description: '采集原始数据 JSON' },
},
/** 店铺商品绑定到系统商品或组合商品 */
bindShopProductRequest: {
bind_type: { type: 'integer', required: true, description: '绑定类型:0解绑 1系统商品 2组合商品' },
@ -1785,7 +1905,9 @@ module.exports = {
/** 店铺下拉项 */
orderStatusShopOption: {
id: { type: 'integer', description: '店铺ID' },
code: { type: 'string', description: '店铺编码(同名店铺用于区分)' },
name: { type: 'string', description: '店铺名称' },
type: { type: 'integer', description: '店铺类型:1平台店铺 2外部打单平台商家 3数据库模式(手工建单排除 2)' },
},
/** 筛选条件下拉数据源(GET /api/order-status/filters) */
orderStatusFilters: {
@ -2152,18 +2274,14 @@ module.exports = {
message: { type: 'string', description: '提示信息' },
data: { type: 'orderStatusPushWmsBatchData', description: '批量推送结果' },
},
/** 批量切换仓库 / 设置所属店铺 */
/** 批量切换仓库(店铺在创建订单时确定,不提供批量改店铺) */
changeOrderStatusWarehouseRequest: {
ids: { type: 'array', itemType: 'integer', required: true, description: '订单ID数组(待审核/异常/待推送)' },
warehouse_id: { type: 'integer', required: true, description: '目标仓库ID(需属于当前主体,同步刷新 warehouse_code 快照)' },
},
changeOrderStatusShopRequest: {
ids: { type: 'array', itemType: 'integer', required: true, description: '订单ID数组(待审核/异常/待推送/委外中)' },
shop_id: { type: 'integer', required: true, description: '目标店铺ID(需属于当前主体,同步刷新 shop_nick 快照)' },
},
orderStatusChangeOwnerData: {
updated: { type: 'integer', description: '更新条数' },
target: { type: 'object', description: '目标仓库 / 店铺(id + 名称,仓库另含 code)' },
target: { type: 'object', description: '目标仓库(id + code + 名称)' },
scope: { type: 'object', description: '本次作用的订单ID集合' },
},
orderStatusChangeOwnerResponse: {

View File

@ -1,5 +1,23 @@
'use strict';
/**
* 把东八区时间对齐到整天:startOfDay/endOfDay
* @param {Date} date 时间
* @param {boolean} end 是否取当天 23:59:59
* @return {Date} 对齐后的时间
*/
function alignDay(date, end) {
const value = new Date(date);
if (end) value.setHours(23, 59, 59, 999);
else value.setHours(0, 0, 0, 0);
return value;
}
/**
* @controller ExternalPrintAccountController 外部打单账号管理
* 账号归属主体,在前端「店铺管理 → 外部打单平台」维护(新增 / 修改 / 删除)
*/
const { Controller } = require('egg');
const { parsePagination, buildPageResult } = require('../lib/pagination');
const { createPrintPlatformService, hasPrintPlatformService } = require('../lib/printPlatform');
@ -20,10 +38,49 @@ function toSafeAccount(row) {
return plain;
}
/** 店铺类型:2 外部打单平台商家 */
const SHOP_TYPE_EXTERNAL = 2;
/** 单品补拉时单次最多提交的商品数(订单明细一般远小于该值) */
const MAX_PULL_PRODUCT_ITEMS = 50;
/**
* @controller ExternalPrintAccountController 外部打单账号管理
* 账号归属主体,在前端「店铺管理 → 外部打单平台」维护(新增 / 修改 / 删除)
* 店铺商品唯一键(与店铺商品表的唯一索引对应)
* @param {string} outerItemId 平台商品ID
* @param {string|null} outerSkuId 平台规格ID
* @return {string} 唯一键
*/
function shopProductKey(outerItemId, outerSkuId) {
return `${outerItemId || ''}|${outerSkuId || ''}`;
}
/** 商品同步时允许更新的字段(新增行仍由 bulkCreate 写入) */
const SHOP_PRODUCT_UPSERT_FIELDS = [
'title',
'outer_code',
'spec',
'image',
'price',
'stock',
'status',
'platform_type',
'external_shop_id',
'raw',
'synced_at',
'updated_at',
];
/**
* 外部平台商家在 OMS 店铺表中的编码:平台标识-账号ID-商家ID(最多 50 字符)
* @param {string} platformCode 平台标识
* @param {number} accountId 账号ID
* @param {string} externalId 商家ID
* @return {string} 店铺编码
*/
function buildExternalShopCode(platformCode, accountId, externalId) {
return `${platformCode}-${accountId}-${externalId}`.slice(0, 50);
}
class ExternalPrintAccountController extends Controller {
/**
* @summary 外部打单账号列表
@ -273,6 +330,523 @@ class ExternalPrintAccountController extends Controller {
}
}
/**
* @summary 拉取账号在外部打单平台的店铺(商家)列表
* @description 实时向平台拉取并标记是否已创建到 OMS 店铺;不落库。前端按账号ID调用,不直连平台
* @router get /api/external-print-accounts/{id}/merchants
* @apikey
* @request path integer *id 账号主键ID
* @request query integer page 页码,默认 1
* @request query integer pageSize 每页条数,默认 20
* @request query string keyword 关键词(商家名称/手机号)
* @response 200 externalPrintMerchantListResponse success
*/
async merchants() {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const account = await this.findAccount(ctx.params.id, { withPlatform: true });
if (!account) {
ctx.status = 404;
ctx.body = { code: 404, message: '打单账号不存在' };
return;
}
const { page, pageSize } = parsePagination(ctx.query);
try {
const service = this.createPlatformService(account);
const result = await service.listShops({
pageIndex: page,
pageSize,
keyword: ctx.query.keyword || '',
});
const platformCode = account.platform.code;
const codes = result.list.map(item => buildExternalShopCode(platformCode, account.id, item.external_id));
const existing = codes.length
? await ctx.model.Shop.findAll({
where: { principal_id: ctx.state.principalId, code: { [Op.in]: codes } },
attributes: [ 'code' ],
raw: true,
})
: [];
const added = new Set(existing.map(row => row.code));
const list = result.list.map(item => ({
...item,
added: added.has(buildExternalShopCode(platformCode, account.id, item.external_id)),
}));
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, result.total, { page, pageSize }) };
} catch (err) {
ctx.status = 400;
ctx.body = { code: 400, message: err.message };
}
}
/**
* @summary 把外部打单平台的店铺(商家)创建到 OMS 店铺
* @description merchants 为商家列表接口返回的项(含 raw),按 external_id 去重;已存在的跳过
* @router post /api/external-print-accounts/{id}/shops
* @apikey
* @request path integer *id 账号主键ID
* @request body createShopsFromMerchantsRequest *body
* @response 200 externalPrintShopCreateResponse success
*/
async createShops() {
const { ctx } = this;
const account = await this.findAccount(ctx.params.id, { withPlatform: true });
if (!account) {
ctx.status = 404;
ctx.body = { code: 404, message: '打单账号不存在' };
return;
}
const merchants = Array.isArray(ctx.request.body.merchants) ? ctx.request.body.merchants : [];
if (!merchants.length) {
ctx.status = 400;
ctx.body = { code: 400, message: 'merchants 不能为空' };
return;
}
if (merchants.length > 200) {
ctx.status = 400;
ctx.body = { code: 400, message: '单次最多添加 200 个店铺' };
return;
}
const platformCode = account.platform.code;
const principalId = ctx.state.principalId;
const created = [];
const transaction = await ctx.model.transaction();
try {
for (const item of merchants) {
const externalId = String((item && item.external_id) || '').trim();
if (!externalId) continue;
const code = buildExternalShopCode(platformCode, account.id, externalId);
const exist = await ctx.model.Shop.findOne({ where: { principal_id: principalId, code }, transaction });
if (exist) continue;
const shop = await ctx.model.Shop.create({
principal_id: principalId,
code,
name: String(item.name || '').trim() || code,
platform: platformCode,
contact_name: item.contact_name ? String(item.contact_name) : null,
contact_phone: item.contact_phone ? String(item.contact_phone) : null,
status: Number(item.status) === 0 ? 0 : 1,
type: SHOP_TYPE_EXTERNAL,
external_print_account_id: account.id,
// 原样保存平台返回的商家完整结构(未带 raw 时退化为保存整条入参),后续按需取字段
external_data: item.raw || item,
remark: item.remark ? String(item.remark).slice(0, 255) : null,
}, { transaction });
created.push({ id: shop.id, code: shop.code, name: shop.name });
}
await transaction.commit();
} catch (err) {
await transaction.rollback();
ctx.status = 400;
ctx.body = { code: 400, message: err.message };
return;
}
ctx.body = {
code: 0,
message: 'success',
data: { created: created.length, skipped: merchants.length - created.length, shops: created },
};
}
/**
* @summary 同步外部打单平台商家的店铺商品
* @description 按商家的分区逐域名拉取全量商品快照,写入店铺商品表(shop_products);
* 快照完整时把本次未出现的已采集商品直接移除(平台已下架/删除的商品无需在本地保留)。
* 前端按账号ID + 店铺ID调用,不直连平台
* @router post /api/external-print-accounts/{id}/shops/{shopId}/sync-products
* @apikey
* @request path integer *id 账号主键ID
* @request path integer *shopId 店铺主键ID
* @response 200 externalPrintShopProductSyncResponse success
*/
async syncShopProducts() {
const { ctx } = this;
const account = await this.findAccount(ctx.params.id, { withPlatform: true });
if (!account) {
ctx.status = 404;
ctx.body = { code: 404, message: '打单账号不存在' };
return;
}
const shop = await ctx.model.Shop.findOne({
where: { id: ctx.params.shopId, principal_id: ctx.state.principalId },
});
if (!shop) {
ctx.status = 404;
ctx.body = { code: 404, message: '店铺不存在' };
return;
}
if (Number(shop.type) !== SHOP_TYPE_EXTERNAL) {
ctx.status = 400;
ctx.body = { code: 400, message: '仅外部打单平台商家支持同步商品' };
return;
}
if (Number(shop.external_print_account_id) !== Number(account.id)) {
ctx.status = 400;
ctx.body = { code: 400, message: '该店铺不属于当前打单账号' };
return;
}
let snapshot;
try {
const service = this.createPlatformService(account);
snapshot = await service.listProducts(shop.get({ plain: true }));
} catch (err) {
ctx.status = 400;
ctx.body = { code: 400, message: err.message };
return;
}
try {
const saved = await this.saveShopProducts(shop, snapshot);
ctx.body = {
code: 0,
message: 'success',
data: {
total: snapshot.total,
unique: saved.unique,
created: saved.created,
updated: saved.updated,
removed: saved.removed,
offline: saved.offline,
verified: snapshot.verified,
hosts: snapshot.hosts,
},
};
} catch (err) {
ctx.status = 500;
ctx.body = { code: 500, message: `保存店铺商品失败:${err.message}` };
}
}
/**
* @summary 按平台商品ID单独拉取店铺商品
* @description 订单明细匹配不到店铺商品时按需补拉:按平台商品ID(可选规格ID)在店铺所属分区及其它分区逐个查询,
* 命中后写入店铺商品表并返回该商品;不会改动其它商品的下架状态
* @router post /api/external-print-accounts/{id}/shops/{shopId}/pull-products
* @apikey
* @request path integer *id 账号主键ID
* @request path integer *shopId 店铺主键ID
* @request body pullShopProductsRequest *body
* @response 200 externalPrintShopProductPullResponse success
*/
async pullShopProducts() {
const { ctx } = this;
const account = await this.findAccount(ctx.params.id, { withPlatform: true });
if (!account) {
ctx.status = 404;
ctx.body = { code: 404, message: '打单账号不存在' };
return;
}
const shop = await ctx.model.Shop.findOne({
where: { id: ctx.params.shopId, principal_id: ctx.state.principalId },
});
if (!shop) {
ctx.status = 404;
ctx.body = { code: 404, message: '店铺不存在' };
return;
}
if (Number(shop.type) !== SHOP_TYPE_EXTERNAL) {
ctx.status = 400;
ctx.body = { code: 400, message: '仅外部打单平台商家支持拉取商品' };
return;
}
if (Number(shop.external_print_account_id) !== Number(account.id)) {
ctx.status = 400;
ctx.body = { code: 400, message: '该店铺不属于当前打单账号' };
return;
}
const body = ctx.request.body || {};
const items = (Array.isArray(body.items) ? body.items : [])
.map(item => ({
outer_item_id: String((item && item.outer_item_id) || '').trim(),
outer_sku_id: String((item && item.outer_sku_id) || '').trim(),
}))
.filter(item => item.outer_item_id);
if (!items.length) {
ctx.status = 400;
ctx.body = { code: 400, message: 'items 不能为空(需传 outer_item_id)' };
return;
}
if (items.length > MAX_PULL_PRODUCT_ITEMS) {
ctx.status = 400;
ctx.body = { code: 400, message: `单次最多补拉 ${MAX_PULL_PRODUCT_ITEMS} 个商品` };
return;
}
let result;
try {
const service = this.createPlatformService(account);
result = await service.listProductsByIds(shop.get({ plain: true }), items);
} catch (err) {
ctx.status = 400;
ctx.body = { code: 400, message: err.message };
return;
}
let saved;
try {
// verified=false:单品补拉只做 upsert,不做移除处理,避免把其它商品误删
saved = await this.saveShopProducts(shop, { list: result.list, verified: false });
} catch (err) {
ctx.status = 500;
ctx.body = { code: 500, message: `保存店铺商品失败:${err.message}` };
return;
}
const savedRows = await this.findSavedShopProducts(shop.id, result.list);
ctx.body = {
code: 0,
message: 'success',
data: {
requested: items.length,
matched: result.list.length,
created: saved.created,
updated: saved.updated,
hosts: result.hosts,
missing: result.missing,
products: savedRows,
},
};
}
/**
* 回查刚写入的店铺商品(供前端直接拿到店铺商品ID去绑定)
* @param {number} shopId 店铺ID
* @param {Array} list 归一化后的商品行
* @return {Promise<Array>} 店铺商品关键字段
*/
async findSavedShopProducts(shopId, list) {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const outerIds = Array.from(new Set(list.map(item => item.outer_item_id).filter(Boolean)));
if (!outerIds.length) return [];
const keys = new Set(list.map(item => shopProductKey(item.outer_item_id, item.outer_sku_id)));
const rows = await ctx.model.ShopProduct.findAll({
where: { shop_id: shopId, outer_item_id: { [Op.in]: outerIds } },
attributes: [ 'id', 'shop_id', 'outer_item_id', 'outer_sku_id', 'title', 'spec', 'platform_type', 'status', 'bind_type', 'product_id', 'combo_product_id' ],
raw: true,
});
return rows.filter(row => keys.has(shopProductKey(row.outer_item_id, row.outer_sku_id)));
}
/**
* @summary 拉取外部打单平台商家的订单
* @description 按时间窗拉取平台订单(含明细)并写入 orders / order_items;
* 明细按店铺商品匹配:店铺商品已绑定系统商品/组合商品的直接写入关联,未绑定的保留平台原样并标记为待处理
* @router post /api/external-print-accounts/{id}/shops/{shopId}/sync-orders
* @apikey
* @request path integer *id 账号主键ID
* @request path integer *shopId 店铺主键ID
* @request body syncShopOrdersRequest *body
* @response 200 externalPrintShopOrderSyncResponse success
*/
async syncShopOrders() {
const { ctx } = this;
const account = await this.findAccount(ctx.params.id, { withPlatform: true });
if (!account) {
ctx.status = 404;
ctx.body = { code: 404, message: '打单账号不存在' };
return;
}
const shop = await ctx.model.Shop.findOne({
where: { id: ctx.params.shopId, principal_id: ctx.state.principalId },
});
if (!shop) {
ctx.status = 404;
ctx.body = { code: 404, message: '店铺不存在' };
return;
}
if (Number(shop.type) !== SHOP_TYPE_EXTERNAL) {
ctx.status = 400;
ctx.body = { code: 400, message: '仅外部打单平台商家支持拉取订单' };
return;
}
if (Number(shop.external_print_account_id) !== Number(account.id)) {
ctx.status = 400;
ctx.body = { code: 400, message: '该店铺不属于当前打单账号' };
return;
}
const body = ctx.request.body || {};
const endTime = body.end_time ? new Date(body.end_time) : new Date();
const startTime = body.start_time
? new Date(body.start_time)
: new Date(alignDay(endTime, false).getTime() - (Math.max(1, Number(body.days) || 1) - 1) * 86400000);
if (Number.isNaN(startTime.getTime()) || Number.isNaN(endTime.getTime())) {
ctx.status = 400;
ctx.body = { code: 400, message: '时间格式不正确' };
return;
}
let saved;
try {
saved = await ctx.service.externalPrintOrder.syncOrders(shop, account, {
startTime,
endTime: alignDay(endTime, true),
});
} catch (err) {
ctx.status = 400;
ctx.body = { code: 400, message: err.message };
return;
}
await ctx.service.externalPrintOrder.markShopSynced(shop, new Date(), `手动拉取成功:${saved.orders} 单`);
ctx.body = {
code: 0,
message: 'success',
data: {
start_time: saved.startTime,
end_time: saved.endTime,
orders: saved.orders,
created: saved.created,
updated: saved.updated,
items: saved.items,
items_bound: saved.itemsBound,
items_unbound: saved.itemsUnbound,
hosts: saved.hosts,
},
};
}
/**
* 把商品快照写入店铺商品表:按唯一键 upsert,快照完整时把本次未出现的商品移除(下架)。
* 未绑定且未被订单引用的直接删除;已绑定或被订单引用的只标为下架,避免丢配置、断溯源。
* 快照不完整(平台分页前后数据不一致)时只更新,不做移除处理,避免误删。
* @param {Object} shop 店铺实例
* @param {Object} snapshot 平台商品快照
* @return {Promise<{unique: number, created: number, updated: number, removed: number, offline: number}>} 写入结果
*/
async saveShopProducts(shop, snapshot) {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const now = new Date();
const existing = await ctx.model.ShopProduct.findAll({
where: { shop_id: shop.id },
attributes: [ 'id', 'outer_item_id', 'outer_sku_id', 'synced_at' ],
raw: true,
});
const existingKeys = new Set(existing.map(row => shopProductKey(row.outer_item_id, row.outer_sku_id)));
const rows = snapshot.list
.filter(item => item.outer_item_id)
.map(item => ({
principal_id: shop.principal_id,
shop_id: shop.id,
outer_item_id: item.outer_item_id,
outer_sku_id: item.outer_sku_id || '',
title: item.title || null,
outer_code: item.outer_code || null,
spec: item.spec || null,
image: item.image || null,
price: item.price,
stock: item.stock,
status: item.status,
platform_type: item.platform_type || null,
external_shop_id: item.external_shop_id || null,
raw: item.raw,
synced_at: now,
created_at: now,
updated_at: now,
}));
let created = 0;
let updated = 0;
for (const row of rows) {
if (existingKeys.has(shopProductKey(row.outer_item_id, row.outer_sku_id))) updated++;
else created++;
}
let removed = 0;
let offline = 0;
const transaction = await ctx.model.transaction();
try {
if (rows.length) {
await ctx.model.ShopProduct.bulkCreate(rows, {
transaction,
updateOnDuplicate: SHOP_PRODUCT_UPSERT_FIELDS,
});
}
if (snapshot.verified) {
const syncedKeys = new Set(rows.map(row => shopProductKey(row.outer_item_id, row.outer_sku_id)));
const staleIds = existing
.filter(row => row.synced_at && !syncedKeys.has(shopProductKey(row.outer_item_id, row.outer_sku_id)))
.map(row => row.id);
if (staleIds.length) {
// 平台已不存在该商品:未被使用的直接移除,避免本地留着无法再匹配订单的僵尸数据;
// 已绑定系统商品/组合商品、或被订单明细引用的保留(删除会丢绑定配置、断掉订单溯源),只标为下架
const keepIds = new Set();
const boundRows = await ctx.model.ShopProduct.findAll({
where: { id: { [Op.in]: staleIds } },
attributes: [ 'id', 'bind_type' ],
raw: true,
transaction,
});
for (const row of boundRows) {
if (Number(row.bind_type) !== 0) keepIds.add(Number(row.id));
}
const referenced = await ctx.model.OrderStatusItem.findAll({
where: { shop_product_id: { [Op.in]: staleIds } },
attributes: [ 'shop_product_id' ],
group: [ 'shop_product_id' ],
raw: true,
transaction,
});
for (const row of referenced) {
if (row.shop_product_id != null) keepIds.add(Number(row.shop_product_id));
}
const deleteIds = staleIds.filter(id => !keepIds.has(Number(id)));
const offlineIds = staleIds.filter(id => keepIds.has(Number(id)));
if (deleteIds.length) {
await ctx.model.ShopProduct.destroy({ where: { id: deleteIds }, transaction });
removed = deleteIds.length;
}
if (offlineIds.length) {
await ctx.model.ShopProduct.update(
{ status: 0, synced_at: now, updated_at: now },
{ where: { id: offlineIds }, transaction }
);
offline = offlineIds.length;
}
}
}
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
return { unique: rows.length, created, updated, removed, offline };
}
/**
* 取当前主体下的账号。
* 资源不存在时 principalCheck 不会写入主体ID(交由控制器返回 404),此时直接返回 null,

View File

@ -69,6 +69,7 @@ class OrderStatusController extends Controller {
* @request query string created_to 创建时间止(YYYY-MM-DD)
* @request query string archived_from 归档时间起(仅 status=history)
* @request query string archived_to 归档时间止(仅 status=history)
* @request query integer exclude_unbound 传 1 时排除含未绑定商品明细的订单(前端「查看未绑定商品订单」开关关闭时使用)
* @response 200 orderStatusListResponse success
*/
async index() {
@ -426,26 +427,6 @@ class OrderStatusController extends Controller {
}
}
/**
* @summary 批量设置所属店铺
* @description 店铺只影响推送时的快递策略匹配(shopNick)与 OMS 记录、不回写 WMS,
* 因此委外中也允许修正(同步刷新 shop_nick 快照)。
* @router post /api/order-status/change-shop
* @apikey
* @request body changeOrderStatusShopRequest
* @response 200 orderStatusChangeOwnerResponse success
*/
async changeShop() {
const { ctx } = this;
const body = ctx.request.body || {};
try {
const data = await ctx.service.orderStatus.changeShop({ ids: this._pickIds(), shop_id: body.shop_id });
ctx.body = { code: 0, message: 'success', data };
} catch (err) {
this._fail(ctx, err, '设置所属店铺失败');
}
}
/**
* @summary 智能识别收件人文本
* @description 把「姓名 电话 地址」等自由文本解析为收件人字段,供新增/编辑表单一键填充。

View File

@ -6,6 +6,37 @@ 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');
@ -32,13 +63,14 @@ class ShopController extends Controller {
* @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 } = ctx.query;
const { keyword, platform, status, type } = ctx.query;
const where = {};
where.principal_id = ctx.state.principalId;
@ -50,6 +82,7 @@ class ShopController extends Controller {
}
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,
@ -58,7 +91,15 @@ class ShopController extends Controller {
order: [[ 'id', 'DESC' ]],
});
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
// 数据库模式(预留)的密码不回显
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 }) };
}
/**
@ -94,11 +135,15 @@ class ShopController extends Controller {
}),
]);
const data = shop.get({ plain: true });
data.has_db_password = !!data.db_password;
delete data.db_password;
ctx.body = {
code: 0,
message: 'success',
data: {
...shop.get({ plain: true }),
...data,
stats: {
shop_product_count: shopProductCount,
shop_product_bound_count: boundCount,
@ -129,6 +174,13 @@ class ShopController extends Controller {
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;
@ -149,7 +201,26 @@ class ShopController extends Controller {
}
}
const shop = await ctx.model.Shop.create({ ...ctx.request.body, code: shopCode });
// 外部平台导入 / 数据库模式相关字段由对应接入逻辑维护,普通新增固定为「平台店铺」
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 } };
}
@ -189,6 +260,26 @@ class ShopController extends Controller {
}
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();

View File

@ -10,7 +10,8 @@ const { parsePagination, buildPageResult } = require('../lib/pagination');
class ShopProductController extends Controller {
/**
* @summary 店铺商品列表
* @description 分页查询店铺商品,支持按店铺、绑定状态、关键词(标题/商家编码/平台商品ID)过滤
* @description 分页查询店铺商品,支持按店铺、绑定状态、关键词(标题/商家编码/平台商品ID)过滤;
* has_unbound_order=1 时只返回「有订单但未绑定系统商品」的店铺商品
* @router get /api/shop-products
* @apikey
* @request query integer page 页码,默认 1
@ -20,16 +21,18 @@ class ShopProductController extends Controller {
* @request query integer bind_type 绑定类型:0未绑定 1系统商品 2组合商品
* @request query integer status 状态:1在售 0下架
* @request query string keyword 关键词,匹配标题、商家编码或平台商品ID
* @request query integer has_unbound_order 传 1 时只返回有订单且未绑定的商品(待处理订单的商品)
* @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 { shop_id: shopId, bind_type: bindType, status, keyword, has_unbound_order: hasUnboundOrder } = ctx.query;
const principalId = Number(ctx.state.principalId);
const where = {};
where.principal_id = ctx.state.principalId;
where.principal_id = 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);
@ -41,6 +44,18 @@ class ShopProductController extends Controller {
];
}
// 有订单未绑定:店铺商品自身未绑定,且被「未绑定系统商品」的订单明细引用
const onlyUnboundOrder = String(hasUnboundOrder) === '1';
if (onlyUnboundOrder) {
where.bind_type = 0;
where.id = {
[Op.in]: ctx.app.Sequelize.literal(
`(SELECT DISTINCT shop_product_id FROM order_status_items WHERE principal_id = ${principalId} ` +
'AND parse_status = 2 AND shop_product_id IS NOT NULL)'
),
};
}
const { count, rows } = await ctx.model.ShopProduct.findAndCountAll({
where,
offset,
@ -53,7 +68,35 @@ class ShopProductController extends Controller {
],
});
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
const list = rows.map(row => row.get({ plain: true }));
await this.attachUnboundOrderCount(list, principalId);
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) };
}
/**
* 回填每个店铺商品的「待处理订单数」(未绑定系统商品的订单明细按订单去重计数),
* 便于列表上直接看出哪些商品还有订单等绑定
* @param {Array} list 店铺商品列表
* @param {number} principalId 主体ID
* @return {Promise<void>} 无返回值
*/
async attachUnboundOrderCount(list, principalId) {
const { ctx } = this;
const ids = list.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0);
if (!ids.length) return;
const Op = this.app.Sequelize.Op;
const rows = await ctx.model.OrderStatusItem.findAll({
where: { principal_id: principalId, parse_status: 2, shop_product_id: { [Op.in]: ids } },
attributes: [
'shop_product_id',
[ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.fn('DISTINCT', ctx.app.Sequelize.col('order_id'))), 'order_count' ],
],
group: [ 'shop_product_id' ],
raw: true,
});
const countByShopProduct = new Map(rows.map(row => [ Number(row.shop_product_id), Number(row.order_count) || 0 ]));
for (const row of list) row.unbound_order_count = countByShopProduct.get(Number(row.id)) || 0;
}
/**
@ -83,72 +126,6 @@ class ShopProductController extends Controller {
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 解绑;
@ -179,6 +156,8 @@ class ShopProductController extends Controller {
}
const data = { bind_type: type, product_id: null, combo_product_id: null };
let boundProduct = null;
let boundCombo = null;
if (type === 1) {
if (!productId) {
@ -193,6 +172,7 @@ class ShopProductController extends Controller {
return;
}
data.product_id = Number(productId);
boundProduct = product;
}
if (type === 2) {
@ -208,32 +188,151 @@ class ShopProductController extends Controller {
return;
}
data.combo_product_id = Number(comboProductId);
boundCombo = combo;
}
await item.update(data);
ctx.body = { code: 0, message: 'success', data: { id: item.id } };
const syncedItems = await this.syncOrderItems(item, boundProduct, boundCombo);
ctx.body = { code: 0, message: 'success', data: { id: item.id, order_items_updated: syncedItems } };
}
/**
* @summary 删除店铺商品
* @description 物理删除采集到的店铺商品
* @router delete /api/shop-products/{id}
* @apikey
* @request path integer *id 主键ID
* @response 200 baseResponse success
* 绑定关系变化后回写订单明细:
* 老明细表(order_items)保持「平台行 1:1」,只同步绑定状态与商品快照;
* 订单页使用的状态明细表(order_status_items)按绑定关系重新展开,
* 绑定组合商品时会拆成组合内子商品行(最小单位)。
* @param {Object} shopProduct 店铺商品实例
* @param {Object|null} product 绑定的系统商品
* @param {Object|null} combo 绑定的组合商品
* @return {Promise<number>} 更新的明细数量(两张表合计)
*/
async destroy() {
async syncOrderItems(shopProduct, product, combo) {
const { ctx } = this;
const item = await ctx.model.ShopProduct.findByPk(ctx.params.id);
const where = { shop_product_id: shopProduct.id };
const affectedItems = await ctx.model.OrderStatusItem.findAll({
where,
attributes: [ 'order_id' ],
raw: true,
});
const orderIds = [ ...new Set(affectedItems.map(row => Number(row.order_id)).filter(id => id > 0)) ];
if (!item) {
ctx.status = 404;
ctx.body = { code: 404, message: '店铺商品不存在' };
return;
// 历史明细可能没有平台快照(功能上线前拉的单),绑定前先按当前未绑定状态补一份,保证以后解绑还能还原
await this.ensurePlatformSnapshot(where);
let updated = 0;
if (product) {
// 老表保留平台原样字段,只同步绑定结果(订单页/推送用的状态明细由 rebuildOrderItems 生成)
const [ affected ] = await ctx.model.OrderItem.update(
{ product_id: product.id, combo_product_id: null, item_type: 1, parse_status: 1, parse_msg: null },
{ where }
);
updated = affected;
} else if (combo) {
const [ affected ] = await ctx.model.OrderItem.update(
{ product_id: null, combo_product_id: combo.id, item_type: 2, parse_status: 1, parse_msg: null },
{ where }
);
updated = affected;
} else {
// 解绑:清空系统商品关联,并把明细字段还原为绑定前的平台快照(platform_snapshot)
const reset = {
product_id: null,
combo_product_id: null,
item_type: 0,
parse_status: 2,
parse_msg: '店铺商品未绑定系统商品,已保留平台原样数据',
};
const orderRows = await ctx.model.OrderItem.findAll({
where,
attributes: [ 'id', 'platform_snapshot' ],
raw: true,
});
for (const row of orderRows) {
const [ affected ] = await ctx.model.OrderItem.update(
{ ...reset, ...this._legacyFieldsFromSnapshot(row.platform_snapshot) },
{ where: { id: row.id } }
);
updated += affected;
}
}
await item.destroy();
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
// 状态明细整体重建:未绑定 / 系统商品 / 组合拆分(行数会变化,不能逐行 update)
updated += await ctx.service.orderItemResolve.rebuildOrderItems(orderIds);
return updated;
}
/**
* 平台快照转老明细表(order_items)字段
* @param {Object|null} snapshot 平台快照
* @return {Object} 需要还原的字段
*/
_legacyFieldsFromSnapshot(snapshot) {
const data = snapshot && typeof snapshot === 'object' ? snapshot : {};
return {
name: data.item_name || null,
sku_code: data.sku_code || null,
spec: data.spec || null,
image: data.image || null,
};
}
/**
* 为缺少平台快照的历史明细补写快照(仅未绑定的明细,此时字段仍是平台原样)
* @param {Object} where 明细筛选条件
* @return {Promise<void>} 无返回值
*/
async ensurePlatformSnapshot(where) {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const scope = {
...where,
platform_snapshot: { [Op.is]: null },
parse_status: { [Op.ne]: 1 },
};
const orderRows = await ctx.model.OrderItem.findAll({
where: scope,
attributes: [ 'id', 'name', 'sku_code', 'spec', 'image' ],
raw: true,
});
for (const row of orderRows) {
await ctx.model.OrderItem.update(
{
platform_snapshot: {
item_code: row.sku_code || null,
item_name: row.name || null,
sku_code: row.sku_code || null,
spec: row.spec || null,
image: row.image || null,
},
},
{ where: { id: row.id } }
);
}
const statusRows = await ctx.model.OrderStatusItem.findAll({
where: scope,
attributes: [ 'id', 'order_line_no', 'item_code', 'item_name', 'sku_code', 'spec', 'image', 'plan_qty', 'actual_price' ],
raw: true,
});
for (const row of statusRows) {
await ctx.model.OrderStatusItem.update(
{
platform_snapshot: {
item_code: row.item_code || null,
item_name: row.item_name || null,
sku_code: row.sku_code || null,
spec: row.spec || null,
image: row.image || null,
// 折叠回平台行需要原行号 / 原数量 / 原单价
line_no: row.order_line_no == null ? '' : String(row.order_line_no),
plan_qty: Number(row.plan_qty) || 0,
actual_price: row.actual_price == null ? null : Number(row.actual_price),
},
},
{ where: { id: row.id } }
);
}
}
}

View File

@ -215,6 +215,7 @@ function itemFields(Sequelize) {
price: { type: DECIMAL(12, 2), comment: '单价(老 order_items.price)' },
total_amount: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '明细金额(老 order_items.total_amount)' },
raw: { type: JsonType, comment: '平台返回的明细原始数据(老 order_items.raw)' },
platform_snapshot: { type: JsonType, comment: '平台明细快照(绑定前的编码/名称/规格/图片,用于解绑还原)' },
created_at: { type: DATE, comment: '创建时间' },
updated_at: { type: DATE, comment: '更新时间' },
};

View File

@ -0,0 +1,265 @@
'use strict';
/**
* 订单明细「平台行 ↔ 最小单位行」互转。
*
* 平台订单一条明细在绑定组合商品后需要拆成组合内的子商品行(数量 = 平台数量 × 组合内数量,
* 单价取子商品自身零售价),这样出库推送、导出、统计都是最小单位;
* 解绑或变更绑定时再按 platform_snapshot 折叠回平台行重新展开。
*
* 可逆的前提:明细行的 platform_snapshot 保留平台原样
* (编码 / 名称 / 规格 / 图片 + 原行号 / 原数量 / 原单价),拆开的子行共用同一份快照。
*/
/**
* 截断字符串,避免超出表字段长度
* @param {*} value 原始值
* @param {number} [max] 最大长度
* @return {string} 处理后的字符串
*/
function text(value, max) {
const str = value == null ? '' : String(value).trim();
return max ? str.slice(0, max) : str;
}
/**
* 数值化(空值按 0)
* @param {*} value 原始值
* @return {number} 数值
*/
function number(value) {
const num = Number(value);
return Number.isFinite(num) ? num : 0;
}
/**
* 数量保留 3 位小数(与 plan_qty DECIMAL(12,3) 一致)
* @param {*} value 原始数量
* @return {number} 数量
*/
function roundQty(value) {
return Number(number(value).toFixed(3));
}
/**
* 金额保留 2 位小数(空值保持 null,表示平台未给价)
* @param {*} value 原始金额
* @return {number|null} 金额
*/
function roundMoney(value) {
if (value == null || value === '') return null;
const num = Number(value);
return Number.isFinite(num) ? Number(num.toFixed(2)) : null;
}
/**
* 由平台明细生成快照(写入 order_status_items.platform_snapshot)
* @param {Object} line 平台明细(统一结构:sku_code/name/spec/image/quantity/price/outer_item_id)
* @param {String|Number} lineNo 原行号
* @return {Object} 快照
*/
function buildSnapshot(line, lineNo) {
const data = line || {};
return {
item_code: text(data.sku_code || data.outer_item_id, 100) || null,
item_name: text(data.name, 255) || null,
sku_code: text(data.sku_code, 100) || null,
spec: text(data.spec, 255) || null,
image: text(data.image, 255) || null,
line_no: text(lineNo == null ? '' : lineNo, 20),
plan_qty: roundQty(data.quantity),
actual_price: roundMoney(data.price),
};
}
/**
* 明细行折叠回平台行:拆开的子行按快照的原行号归并回一行
* @param {Array} rows 订单明细行(order_status_items,任意顺序)
* @return {Array} 平台行(含 template 原行用于复制其它字段)
*/
function foldPlatformLines(rows) {
const groups = new Map();
for (const row of rows || []) {
const snapshot = row.platform_snapshot && typeof row.platform_snapshot === 'object' ? row.platform_snapshot : null;
const snapshotLineNo = snapshot && snapshot.line_no ? String(snapshot.line_no) : '';
// 没有快照行号的历史数据按行自身 id 独立成行,避免把不同平台行误并
const key = snapshotLineNo ? `L${snapshotLineNo}` : `R${row.id}`;
if (groups.has(key)) continue;
groups.set(key, {
line_no: snapshotLineNo || text(row.order_line_no, 20) || '',
item_code: snapshot ? snapshot.item_code : row.item_code,
item_name: snapshot ? snapshot.item_name : row.item_name,
sku_code: snapshot ? snapshot.sku_code : row.sku_code,
spec: snapshot ? snapshot.spec : row.spec,
image: snapshot ? snapshot.image : row.image,
plan_qty: snapshot && snapshot.plan_qty != null ? number(snapshot.plan_qty) : number(row.plan_qty),
actual_price: roundMoney(snapshot && snapshot.actual_price != null ? snapshot.actual_price : row.actual_price),
shop_product_id: row.shop_product_id == null ? null : Number(row.shop_product_id),
outer_item_id: row.outer_item_id || null,
outer_sku_id: row.outer_sku_id || null,
platform_snapshot: snapshot,
template: row,
});
}
return Array.from(groups.values()).sort((a, b) => {
const left = Number(a.line_no);
const right = Number(b.line_no);
if (Number.isFinite(left) && Number.isFinite(right) && left !== right) return left - right;
return String(a.line_no).localeCompare(String(b.line_no));
});
}
/**
* 展开平台行为明细行(最小单位)
* @param {Object} line foldPlatformLines 产出的平台行
* @param {Object} binding 绑定上下文 { shopProduct, product, combo, comboItems }
* @return {Array} 明细行(不含 principal_id / order_id / order_line_no)
*/
function expandPlatformLine(line, binding = {}) {
const template = line.template || {};
const base = {
shop_id: template.shop_id == null ? null : Number(template.shop_id),
shop_product_id: line.shop_product_id || null,
outer_item_id: line.outer_item_id || null,
outer_sku_id: line.outer_sku_id || null,
raw: template.raw || null,
platform_snapshot: line.platform_snapshot || null,
ext_code: template.ext_code == null ? null : template.ext_code,
inventory_type: template.inventory_type || 'ZP',
source_order_code: template.source_order_code == null ? null : template.source_order_code,
extend_props: template.extend_props && typeof template.extend_props === 'object' ? template.extend_props : null,
item_id: null,
stock_id: null,
};
const qty = roundQty(line.plan_qty);
const price = roundMoney(line.actual_price);
const { shopProduct, product, combo, comboItems } = binding;
// 绑定组合:拆成组合内每个子商品一行,数量 = 平台数量 × 组合内数量,单价取子商品零售价
if (combo) {
const children = (comboItems || []).filter(item => item && item.product_id);
if (children.length) {
return children.map((child, idx) => ({
...base,
item_code: text(child.item_code, 100) || null,
item_name: text(child.item_name, 255) || null,
sku_code: text(child.item_code, 100) || null,
spec: text(child.sku_property, 255) || null,
image: text(child.image, 255) || null,
plan_qty: roundQty(qty * (number(child.quantity) || 1)),
quantity: roundQty(qty * (number(child.quantity) || 1)),
actual_price: roundMoney(child.retail_price) == null ? 0 : roundMoney(child.retail_price),
retail_price: roundMoney(child.retail_price) == null ? 0 : roundMoney(child.retail_price),
product_id: Number(child.product_id),
combo_product_id: combo.id,
item_type: 1,
parse_status: 1,
parse_msg: null,
sub_source_order_code: childSubCode(base.source_order_code, idx + 1),
}));
}
// 组合没有配置子商品:保留组合行并提示,避免把组合编码推给仓库
return [{
...base,
item_code: text(combo.code, 100) || null,
item_name: text(combo.name, 255) || null,
sku_code: text(combo.code, 100) || null,
spec: line.spec || null,
image: line.image || null,
plan_qty: qty,
quantity: qty,
actual_price: price,
retail_price: price,
product_id: null,
combo_product_id: combo.id,
item_type: 2,
parse_status: 1,
parse_msg: '组合商品未配置子商品,无法拆分为最小单位',
}];
}
// 绑定系统商品:一行对一行,商品信息取系统商品
if (product) {
return [{
...base,
item_code: text(product.item_code, 100) || null,
item_name: text(product.item_name, 255) || null,
sku_code: text(product.item_code, 100) || null,
spec: text(product.sku_property, 255) || null,
image: text(product.image, 255) || null,
plan_qty: qty,
quantity: qty,
actual_price: price,
retail_price: price,
product_id: Number(product.id),
combo_product_id: null,
item_type: 1,
parse_status: 1,
parse_msg: null,
}];
}
// 未采集到店铺商品 / 店铺商品未绑定系统商品:保留平台原样一行
return [{
...base,
item_code: line.item_code || null,
item_name: line.item_name || null,
sku_code: line.sku_code || null,
spec: line.spec || null,
image: line.image || null,
plan_qty: qty,
quantity: qty,
actual_price: price,
retail_price: price,
product_id: null,
combo_product_id: null,
item_type: 0,
parse_status: 2,
parse_msg: shopProduct
? '店铺商品未绑定系统商品,已保留平台原样数据'
: '未采集到该店铺商品,已保留平台原样数据',
}];
}
/**
* 子行来源编码(保留原来源 + 序号,便于溯源)
* @param {string} [sourceCode] 原行来源编码
* @param {number} seq 子行序号
* @return {string|null} 子行来源编码
*/
function childSubCode(sourceCode, seq) {
const base = text(sourceCode, 40);
if (!base) return null;
return `${base}#${seq}`.slice(0, 50);
}
/**
* 补齐平台快照:保证每行都带完整快照(原行号 / 原数量 / 原单价),便于下次折叠回平台行
* @param {Object} line foldPlatformLines 产出的平台行
* @return {Object} 快照
*/
function normalizeSnapshot(line) {
const source = line.platform_snapshot && typeof line.platform_snapshot === 'object' ? line.platform_snapshot : {};
const snapshot = { ...source };
if (!snapshot.item_code) snapshot.item_code = line.item_code || null;
if (!snapshot.item_name) snapshot.item_name = line.item_name || null;
if (snapshot.sku_code === undefined) snapshot.sku_code = line.sku_code || null;
if (snapshot.spec === undefined) snapshot.spec = line.spec || null;
if (snapshot.image === undefined) snapshot.image = line.image || null;
if (!snapshot.line_no) snapshot.line_no = text(line.line_no, 20);
if (snapshot.plan_qty == null) snapshot.plan_qty = roundQty(line.plan_qty);
if (snapshot.actual_price == null) snapshot.actual_price = roundMoney(line.actual_price);
return snapshot;
}
module.exports = {
buildSnapshot,
normalizeSnapshot,
foldPlatformLines,
expandPlatformLine,
};

View File

@ -142,6 +142,67 @@ class PrintPlatformService {
throw new Error(`外部打单平台 ${this.platformName} 未实现 checkSession()`);
}
/**
* 拉取平台侧的店铺/商家列表,由各平台实现。
* 需返回统一结构,避免上层直接依赖各平台字段:
* { total, list: [{ external_id, name, contact_name, contact_phone, status, remark, raw }] }
* @param {Object} [options] 查询参数:pageIndex / pageSize / keyword
* @return {Promise<{total: number, list: Array}>} 平台店铺列表
*/
async listShops(options) { // eslint-disable-line no-unused-vars
throw new Error(`外部打单平台 ${this.platformName} 未实现 listShops()`);
}
/**
* 拉取平台侧的店铺商品(全量快照),由各平台实现。
* 需返回统一结构,避免上层直接依赖各平台字段:
* {
* total, verified,
* hosts: [{ host, total, verified, pages, areas: [{ dbname, name, total, verified, pages }] }],
* list: [{
* outer_item_id, outer_sku_id, title, outer_code, spec, image,
* price, stock, status, platform_type, external_shop_id, raw,
* }],
* }
* verified 表示快照完整(去重后的商品数 = 平台返回的 Total),上层可据此清理已下架商品。
* @param {Object} shop OMS 店铺记录(type=2,external_data 为平台返回的商家原始结构)
* @return {Promise<{total: number, verified: boolean, hosts: Array, list: Array}>} 商品快照
*/
async listProducts(shop) { // eslint-disable-line no-unused-vars
throw new Error(`外部打单平台 ${this.platformName} 未实现 listProducts()`);
}
/**
* 拉取店铺订单(含明细),由各平台实现。
* 需返回统一结构,避免上层直接依赖各平台字段:
* { total, hosts: [命中来源], list: [{
* external_order_id, external_shop_id, external_shop_name, platform_type, platform_status,
* order_no, total_amount, pay_amount, receiver, remark,
* external_created_at, external_updated_at, raw,
* items: [{ external_item_id, outer_item_id, outer_sku_id, sku_code, name, spec, image,
* quantity, price, total_amount, relation_base_product, base_product, raw }],
* }] }
* 明细只保留平台商品快照,系统商品匹配由上层依据店铺商品绑定关系完成。
* @param {Object} shop OMS 店铺记录(type=2,external_data 为平台返回的商家原始结构)
* @param {Object} [options] 查询参数(startTime / endTime)
* @return {Promise<{total: number, list: Array, hosts: Array}>} 订单列表
*/
async listOrders(shop, options) { // eslint-disable-line no-unused-vars
throw new Error(`外部打单平台 ${this.platformName} 未实现 listOrders()`);
}
/**
* 按平台商品ID(可选规格ID)单独拉取商品,用于订单明细匹配不到店铺商品时按需补拉,由各平台实现。
* 需返回统一结构:
* { list: [与 listProducts().list 同结构], missing: [{ outer_item_id, outer_sku_id, reason }], hosts: [命中来源说明] }
* @param {Object} shop OMS 店铺记录(type=2,external_data 为平台返回的商家原始结构)
* @param {Array<{outer_item_id: string, outer_sku_id?: string}>} items 待补拉的商品
* @return {Promise<{list: Array, missing: Array, hosts: Array}>} 命中与未命中的商品
*/
async listProductsByIds(shop, items) { // eslint-disable-line no-unused-vars
throw new Error(`外部打单平台 ${this.platformName} 未实现 listProductsByIds()`);
}
/**
* 把订单推送到打单平台打印,由各平台实现
* @param {Object} order 订单数据(字段口径由平台协议决定)

View File

@ -17,6 +17,74 @@ const WORKBENCH_HOST = 'fxali.dgjapp.com';
const WORKBENCH_URL = `https://${WORKBENCH_HOST}/GeneralizeIndex/`;
/** 工作台用户信息接口:返回当前登录账号的店铺/昵称等信息(需 token + cookie) */
const USER_INFO_URL = `https://${WORKBENCH_HOST}/api/user/GetUserInfo`;
/** 工作台分区信息接口:商家列表需要其中的 dbname;商品查询需要逐个分区(区)查询 */
const AREAS_INFO_PATH = '/api/user/GetAreasInfo';
/** 商家(即店管家侧的店铺)列表接口 */
const AGENT_LIST_URL = `https://${WORKBENCH_HOST}/Partner/LoadMyAgentList`;
/** 商品列表接口(按分区域名请求,路径固定) */
const PRODUCT_LIST_PATH = '/Product/LoadList';
/** 订单列表接口(按分区域名请求,路径固定) */
const ORDER_LIST_PATH = '/NewOrder/List';
/** 订单列表单页条数(平台允许 500) */
const ORDER_PAGE_SIZE = 500;
/** 订单查询的最大翻页数,防御平台分页异常 */
const ORDER_MAX_PAGES = 200;
/** 商家的分区 DbName -> 商品接口域名(toutiao=抖店、pinduoduo=拼多多、alibaba=精选、jingdong=京东) */
const AREA_PRODUCT_HOSTS = {
toutiao: 'fxdd.dgjapp.com',
pinduoduo: 'fxpdd.dgjapp.com',
alibaba: 'fxali.dgjapp.com',
jingdong: 'fxjd.dgjapp.com',
taobao: 'fxali.dgjapp.com',
kuaishou: 'fxali.dgjapp.com',
};
/** 商家没有可识别的分区时兜底查询的域名:宁可多查,避免漏商品 */
const FALLBACK_PRODUCT_HOSTS = [
'fxali.dgjapp.com',
'fxdd.dgjapp.com',
'fxpdd.dgjapp.com',
'fxjd.dgjapp.com',
'fxtk.dgjapp.com',
];
/** 商品列表单页条数(平台允许 200) */
const PRODUCT_PAGE_SIZE = 200;
/**
* 商品状态是否为在售:平台不同分区返回的状态值不统一(published / 1 / db_del / jdp_delete 等)
* @param {string|number|null} status 平台商品状态
* @return {boolean} 是否在售
*/
function isProductOnSale(status) {
const value = String(status == null ? '' : status).trim().toLowerCase();
return value === '1' || value === 'published' || value === 'online' || value === 'onsale' || value === 'on_sale';
}
/**
* 转数字,非法值按 0 处理
* @param {*} value 原始值
* @return {number} 数字
*/
function toNumber(value) {
const num = Number(value);
return Number.isFinite(num) ? num : 0;
}
/**
* 截断字符串,避免超出表字段长度
* @param {*} value 原始值
* @param {number} max 最大长度
* @return {string} 截断后的字符串
*/
function truncate(value, max) {
return String(value == null ? '' : value).slice(0, max);
}
/** 单次请求超时(毫秒) */
const REQUEST_TIMEOUT_MS = 15000;
@ -127,6 +195,49 @@ function describeFailure(res) {
return `${message}(HTTP ${res ? res.status : '-'})`;
}
/**
* 日期格式化为店管家订单查询使用的时间字符串(yyyy-MM-dd HH:mm:ss)
* @param {Date|string} value 时间
* @return {string} 时间字符串
*/
function formatOrderTime(value) {
const date = value instanceof Date ? value : new Date(value);
if (Number.isNaN(date.getTime())) return '';
const pad = num => String(num).padStart(2, '0');
return (
`${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
`${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
);
}
/**
* 解析平台时间字符串(店管家返回 yyyy-MM-dd HH:mm:ss),非法值返回 null
* @param {*} value 平台时间
* @return {Date|null} 时间
*/
function parseOrderTime(value) {
const text = String(value == null ? '' : value).trim();
if (!text) return null;
const date = new Date(text.replace(' ', 'T'));
return Number.isNaN(date.getTime()) ? null : date;
}
/**
* 订单明细的平台规格ID:不同平台字段口径不一致
* (抖店/淘宝用 SkuId 存规格ID,视频号则用 SkuCode 存规格ID、SkuId 存规格名称)
* @param {Object} data 明细原始结构
* @return {string} 平台规格ID,取不到时返回空字符串
*/
function resolveOrderSkuId(data) {
const looksLikeId = value => /^[0-9A-Za-z_-]{4,64}$/.test(value);
const candidates = [ data.SkuId, data.SkuCode ];
for (const item of candidates) {
const value = String(item == null ? '' : item).trim();
if (value && looksLikeId(value)) return value;
}
return '';
}
/**
* 店管家(dgj)外部打单平台服务。
*
@ -225,6 +336,752 @@ class DgjService extends PrintPlatformService {
};
}
/**
* 拉取工作台分区信息(商家列表接口需要其中的 DbName;商品接口需要按分区逐个查询)
* @param {string} [token] 登录 token,默认取账号已保存的 token
* @param {string} [cookie] 会话 cookie,默认取账号已保存的 cookie
* @param {string} [host] 分区信息所属域名,默认工作台域名
* @return {Promise<{success: boolean, status: number, message: string, data: Object|null}>} 分区信息
*/
async getAreasInfo(token = this.token, cookie = this.cookie, host = WORKBENCH_HOST) {
const tk = String(token || '').trim();
if (!tk) return { success: false, status: 0, message: '账号未保存登录 token', data: null };
const query = new URLSearchParams({ token: tk, dbname: '' });
const headers = { ...WORKBENCH_AJAX_HEADERS, referer: `https://${host}/` };
if (cookie) headers.cookie = cookie;
const res = await this.request(`https://${host}${AREAS_INFO_PATH}?${query.toString()}`, { method: 'GET', headers });
const success = res.status === 200 && !!res.json && res.json.Success === true;
return {
success,
status: res.status,
message: (res.json && res.json.Message) || '',
data: success && res.json.Data ? res.json.Data : null,
};
}
/**
* 拉取当前账号的商家列表(店管家的「商家」即 OMS 的店铺)。
* 返回统一结构,上层(控制器/前端)不直接依赖店管家字段。
* @param {Object} [options] 查询参数
* @param {number} [options.pageIndex] 页码,从 1 开始
* @param {number} [options.pageSize] 每页条数(最大 200)
* @param {string} [options.keyword] 关键词(商家名称/手机号)
* @return {Promise<{total: number, list: Array}>} 统一的店铺列表
*/
async listShops(options = {}) {
if (!this.token || !this.cookie) {
throw new Error('账号未登录:缺少 token 或 cookie,请先登录');
}
const pageIndex = Math.max(1, Number.parseInt(options.pageIndex, 10) || 1);
const pageSize = Math.min(200, Math.max(1, Number.parseInt(options.pageSize, 10) || 20));
const keyword = String(options.keyword || '');
// 商家列表接口需要 traceId 与 dbname,取不到时按空值请求
let traceId = '';
let dbName = '';
try {
const info = await this.getUserInfo();
traceId = (info.data && info.data.TraceId) || '';
const areas = await this.getAreasInfo();
dbName = (areas.data && areas.data.DbName) || '';
} catch {
// 忽略:上下文参数缺失不阻断列表查询
}
const query = new URLSearchParams({
token: this.token,
traceId,
dbname: dbName,
dataFlag: '',
key: keyword,
status: '0s',
pageIndex: String(pageIndex),
pageSize: String(pageSize),
IsCustomerOrder: 'false',
FxPageType: '1',
});
const headers = { ...WORKBENCH_AJAX_HEADERS };
if (this.cookie) headers.cookie = this.cookie;
const res = await this.request(`${AGENT_LIST_URL}?${query.toString()}`, { method: 'GET', headers });
if (res.status === 401) {
throw new Error(`店管家登录已失效:${(res.json && res.json.Message) || 'token is invalid'}`);
}
if (!res.json || res.json.Success !== true) {
const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`;
throw new Error(`拉取店管家商家列表失败:${reason}`);
}
const data = res.json.Data || {};
const list = Array.isArray(data.List) ? data.List.map(item => this.normalizeShop(item)) : [];
return { total: Number(data.Total) || list.length, list };
}
/**
* 把店管家商家结构转换为统一的店铺结构(其他平台按同样结构返回即可)
* @param {Object} item 店管家商家原始结构
* @return {Object} 统一店铺结构
*/
normalizeShop(item) {
const data = item || {};
return {
external_id: String(data.Id == null ? '' : data.Id),
name: data.Remark || data.UserName || data.NickName || data.RemarkName || '',
contact_name: data.SenderName || data.Remark || '',
contact_phone: data.SenderMobile || data.Mobile || '',
status: Number(data.Status) === 0 ? 0 : 1,
remark: data.RemarkName || '',
raw: data,
};
}
/**
* 根据商家的分区信息确定要查询的商品域名。
* 商家在店管家的 DbAreas 里记录了所在分区(抖店/拼多多/精选/京东),
* 商品接口按分区域名部署;识别不出分区时兜底查询全部域名,避免漏商品。
* @param {Object} externalData 商家原始结构(shops.external_data)
* @return {string[]} 商品接口域名列表
*/
resolveProductHosts(externalData) {
const areas = Array.isArray(externalData && externalData.DbAreas) ? externalData.DbAreas : [];
const hosts = [];
for (const area of areas) {
const host = AREA_PRODUCT_HOSTS[String((area && area.DbName) || '').toLowerCase()];
if (host && !hosts.includes(host)) hosts.push(host);
}
return hosts.length ? hosts : FALLBACK_PRODUCT_HOSTS.slice();
}
/**
* 组装商品列表查询表单(字段口径与店管家工作台一致)
* @param {string} agentId 商家 FxUserId(注意不是商家 Id);为空表示不限商家
* @param {number} pageIndex 页码,从 1 开始
* @param {number} pageSize 每页条数
* @param {Object} [filters] 单品查询条件
* @param {string} [filters.productId] 平台商品ID
* @param {string} [filters.skuId] 平台规格ID
* @return {URLSearchParams} 表单
*/
buildProductForm(agentId, pageIndex, pageSize, filters = {}) {
return new URLSearchParams({
PageIndex: String(pageIndex),
PageSize: String(pageSize),
SelectShopId: '',
SelectSupplierId: '',
SelectAgentId: agentId ? String(agentId) : '',
SelectPlatformType: '',
InputProductName: '',
ProductType: 'all',
ProductStatus: '0',
ProductCargoNumber: '',
ProductSkuName: '',
ProductShortTitle: '',
ProductSkuShortTitle: '',
IsSetShortTitle: '',
IsSetSkuShortTitle: '',
IsSetWeight: '',
IsSkuSetWeight: '',
ProductId: filters.productId || '',
SkuId: filters.skuId || '',
SkuCargoNumber: '',
IsDeleted: 'false',
IsRelationBaseProduct: '',
ActiveTimeDay: '-1',
StockCode: '',
IsExistStockCode: '',
IsCustomerOrder: 'false',
FxPageType: '1',
});
}
/**
* 列出某个域名下账号可访问的分区(区)。
* 同一域名可能存在多个物理库(如「精选平台四区」「新系统区」),dbname 为空表示默认区;
* 商品必须逐区查询,否则会漏掉其它区的商品。
* @param {string} host 商品接口域名
* @return {Promise<Array<{dbname: string, name: string}>>} 分区列表(含默认区)
*/
async listProductAreas(host) {
const areas = await this.getAreasInfo(this.token, this.cookie, host);
const data = areas.data || {};
const list = [];
const push = (dbname, name) => {
const value = String(dbname || '');
if (!value || list.some(item => item.dbname === value)) return;
list.push({ dbname: value, name: name || '' });
};
// 当前分区 + 其它分区;dbname 为空等价于当前分区,这里统一用显式库名查询
const names = new Map();
for (const area of data.DbArea || []) {
if (area && area.DbName) names.set(String(area.DbName), area.NickName || '');
}
push(data.DbName, names.get(String(data.DbName || '')) || '当前分区');
for (const area of data.DbArea || []) push(area && area.DbName, area && area.NickName);
return list.length ? list : [{ dbname: '', name: '默认区' }];
}
/**
* 拉取一页商品
* @param {string} host 商品接口域名
* @param {Object} options 查询参数
* @param {string} [options.agentId] 商家 FxUserId,为空表示不限商家
* @param {string} options.traceId 登录上下文 traceId
* @param {string} [options.dbname] 分区库名,为空表示默认区
* @param {string} [options.productId] 平台商品ID(单品查询)
* @param {string} [options.skuId] 平台规格ID(单品查询)
* @param {number} options.pageIndex 页码
* @param {number} options.pageSize 每页条数
* @return {Promise<{rows: Array, total: number}>} 当页商品与总数
*/
async fetchProductPage(host, { agentId, traceId, dbname, productId, skuId, pageIndex, pageSize }) {
const query = new URLSearchParams({
token: this.token,
traceId: traceId || '',
dbname: dbname || '',
dataFlag: '',
});
const headers = {
accept: 'application/json, text/javascript, */*; q=0.01',
'accept-language': 'zh-CN,zh;q=0.9',
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
referer: `https://${host}/`,
'user-agent': BROWSER_HEADERS['user-agent'],
'x-requested-with': 'XMLHttpRequest',
};
if (this.cookie) headers.cookie = this.cookie;
const res = await this.request(`https://${host}${PRODUCT_LIST_PATH}?${query.toString()}`, {
method: 'POST',
headers,
body: this.buildProductForm(agentId, pageIndex, pageSize, { productId, skuId }).toString(),
});
if (res.status === 401) {
throw new Error(`店管家登录已失效:${(res.json && res.json.Message) || 'token is invalid'}`);
}
if (!res.json || res.json.Success !== true) {
const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`;
throw new Error(`拉取店管家商品列表失败(${host}):${reason}`);
}
const data = res.json.Data || {};
return {
rows: Array.isArray(data.Rows) ? data.Rows : [],
total: Number(data.Total) || 0,
};
}
/**
* 拉取某个域名下单个分区的全量商品快照。
* 逐页拉取并校验「去重后的商品数 = Total」,不一致时重试一次,
* 避免平台在分页过程中新增/删除商品导致漏拉或重复。
* @param {string} host 商品接口域名
* @param {Object} options 查询参数
* @param {string} options.agentId 商家 FxUserId
* @param {string} options.traceId 登录上下文 traceId
* @param {string} [options.dbname] 分区库名,为空表示默认区
* @param {string} [options.name] 分区名称
* @return {Promise<Object>} 分区商品快照
*/
async fetchAreaSnapshot(host, { agentId, traceId, dbname, name }) {
const maxAttempts = 2;
let snapshot = null;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const rows = [];
let total = 0;
let pages = 0;
// 上限 1000 页:防御平台分页异常(Total 与实际不符)时死循环
for (let pageIndex = 1; pageIndex <= 1000; pageIndex++) {
const page = await this.fetchProductPage(host, {
agentId,
traceId,
dbname,
pageIndex,
pageSize: PRODUCT_PAGE_SIZE,
});
pages++;
if (pages === 1) total = page.total;
rows.push(...page.rows);
if (!page.rows.length || rows.length >= total) break;
}
const unique = new Map();
for (const item of rows) {
const key = String((item && (item.Id != null ? item.Id : item.PlatformId)) || '');
if (key && !unique.has(key)) unique.set(key, item);
}
const candidate = {
host,
dbname: dbname || '',
name: name || '',
total,
uniqueCount: unique.size,
pages,
rows: Array.from(unique.values()),
verified: unique.size === total,
};
// 重试结果更差(例如瞬时返回空列表)时保留上一次快照,避免把商品误判为下架
if (!snapshot || candidate.verified || candidate.uniqueCount > snapshot.uniqueCount) {
snapshot = candidate;
}
if (snapshot.verified) break;
}
return snapshot;
}
/**
* 拉取某个域名下所有分区的商品快照并合并。
* 同一域名下可能有多个物理库(默认区 / 新系统区等),只查默认区会漏掉其它区的商品。
* @param {string} host 商品接口域名
* @param {Object} options 查询参数
* @param {string} options.agentId 商家 FxUserId
* @param {string} options.traceId 登录上下文 traceId
* @return {Promise<Object>} 域名商品快照(含各分区明细)
*/
async fetchProductSnapshot(host, { agentId, traceId }) {
const areas = await this.listProductAreas(host);
const snapshots = [];
for (const area of areas) {
snapshots.push(await this.fetchAreaSnapshot(host, {
agentId,
traceId,
dbname: area.dbname,
name: area.name,
}));
}
// 不同分区是独立库,正常不会重复;仍按商品ID去重,避免同一商品被写入两次
const rows = new Map();
for (const snapshot of snapshots) {
for (const item of snapshot.rows) {
const key = String((item && (item.Id != null ? item.Id : item.PlatformId)) || '');
if (key && !rows.has(key)) rows.set(key, item);
}
}
return {
host,
total: snapshots.reduce((sum, snapshot) => sum + snapshot.total, 0),
uniqueCount: rows.size,
pages: snapshots.reduce((sum, snapshot) => sum + snapshot.pages, 0),
rows: Array.from(rows.values()),
verified: snapshots.every(snapshot => snapshot.verified),
areas: snapshots.map(snapshot => ({
dbname: snapshot.dbname,
name: snapshot.name,
total: snapshot.total,
unique: snapshot.uniqueCount,
pages: snapshot.pages,
verified: snapshot.verified,
})),
};
}
/**
* 拉取店铺商品全量快照:商家可能同时经营多个平台,
* 按其分区逐个域名拉取后合并,按「平台类型 + 平台商品ID + 平台规格ID」去重。
* @param {Object} shop OMS 店铺记录(type=2,external_data 为商家原始结构)
* @return {Promise<{total: number, verified: boolean, hosts: Array, list: Array}>} 商品快照
*/
async listProducts(shop) {
if (!this.token || !this.cookie) {
throw new Error('账号未登录:缺少 token 或 cookie,请先登录');
}
const data = (shop && shop.external_data) || {};
const agentId = String(data.FxUserId || '').trim();
if (!agentId) throw new Error('店铺缺少商家 FxUserId,无法拉取平台商品');
const hosts = this.resolveProductHosts(data);
let traceId = '';
try {
const info = await this.getUserInfo();
traceId = (info.data && info.data.TraceId) || '';
} catch {
// 忽略:traceId 缺失不阻断商品查询
}
const snapshots = [];
for (const host of hosts) {
snapshots.push(await this.fetchProductSnapshot(host, { agentId, traceId }));
}
const merged = new Map();
for (const snapshot of snapshots) {
for (const item of snapshot.rows) {
for (const row of this.normalizeProduct(item)) {
merged.set(`${row.platform_type}|${row.outer_item_id}|${row.outer_sku_id}`, row);
}
}
}
return {
total: snapshots.reduce((sum, snapshot) => sum + snapshot.total, 0),
verified: snapshots.every(snapshot => snapshot.verified),
hosts: snapshots.map(snapshot => ({
host: snapshot.host,
total: snapshot.total,
unique: snapshot.uniqueCount,
pages: snapshot.pages,
verified: snapshot.verified,
areas: snapshot.areas,
})),
list: Array.from(merged.values()),
};
}
/**
* 按平台商品ID(可选规格ID)单独拉取商品,用于订单明细匹配不到店铺商品时按需补拉。
* 单品查询不传 SelectAgentId:商品可能属于同一账号下的其它商家,按商品ID更容易命中;
* 域名与分区按「店铺所属分区优先、其余域名兜底」的顺序逐个尝试,命中即停止。
* @param {Object} shop OMS 店铺记录(type=2,external_data 为商家原始结构)
* @param {Array<{outer_item_id: string, outer_sku_id?: string}>} items 待补拉的商品
* @return {Promise<{list: Array, missing: Array, hosts: Array}>} 命中的店铺商品行与未命中的商品
*/
async listProductsByIds(shop, items = []) {
if (!this.token || !this.cookie) {
throw new Error('账号未登录:缺少 token 或 cookie,请先登录');
}
const data = (shop && shop.external_data) || {};
const hosts = [];
for (const host of [ ...this.resolveProductHosts(data), ...FALLBACK_PRODUCT_HOSTS ]) {
if (!hosts.includes(host)) hosts.push(host);
}
let traceId = '';
try {
const info = await this.getUserInfo();
traceId = (info.data && info.data.TraceId) || '';
} catch {
// 忽略:traceId 缺失不阻断单品查询
}
const areaCache = new Map();
const list = [];
const missing = [];
const hitHosts = new Set();
for (const item of items) {
const productId = String((item && item.outer_item_id) || '').trim();
const skuId = String((item && item.outer_sku_id) || '').trim();
if (!productId) {
missing.push({ outer_item_id: productId, outer_sku_id: skuId, reason: '缺少平台商品ID' });
continue;
}
let matched = [];
for (const host of hosts) {
if (!areaCache.has(host)) areaCache.set(host, await this.listProductAreas(host));
for (const area of areaCache.get(host)) {
const page = await this.fetchProductPage(host, {
traceId,
dbname: area.dbname,
productId,
skuId,
pageIndex: 1,
pageSize: 20,
});
if (!page.rows.length) continue;
for (const product of page.rows) {
const rows = this.normalizeProduct(product);
// 带规格ID时只保留该规格(平台可能返回整个商品的全部规格)
const picked = skuId ? rows.filter(row => row.outer_sku_id === skuId) : rows;
matched = matched.concat(picked);
}
if (matched.length) {
hitHosts.add(`${host}(${area.name || area.dbname})`);
break;
}
}
if (matched.length) break;
}
if (matched.length) list.push(...matched);
else missing.push({ outer_item_id: productId, outer_sku_id: skuId, reason: '平台未查询到该商品' });
}
return { list, missing, hosts: Array.from(hitHosts) };
}
/**
* 把店管家商品(含 SKU 列表)转换为店铺商品行的统一结构。
* 平台商品ID取商品级 PlatformId;平台规格ID取 SKU 的 SpecId/SkuId
* (注意 SKU.PlatformId 是商品级平台ID,不能当作规格ID),缺失时退化为店管家内部ID。
* 原样保留商品与 SKU 结构供后续使用。
* @param {Object} product 店管家商品原始结构
* @return {Array<Object>} 店铺商品行(一个 SKU 一行)
*/
normalizeProduct(product) {
const data = product || {};
const skus = Array.isArray(data.Skus) && data.Skus.length ? data.Skus : [ null ];
const productRaw = { ...data };
delete productRaw.Skus;
const platformType = truncate(data.PlatformType, 32);
const externalShopId = data.ShopId == null ? '' : truncate(data.ShopId, 64);
const status = isProductOnSale(data.Status) ? 1 : 0;
return skus.map(sku => {
const item = sku || {};
const ptInfo = item.PtProductInfo || {};
const attrs = [ item.AttributeValue1, item.AttributeValue2 ].filter(Boolean).join(' ');
return {
outer_item_id: String(data.PlatformId || ptInfo.PrductId || data.Id || ''),
outer_sku_id: String(item.SpecId || item.SkuId || item.Id || ''),
title: truncate(data.Subject, 255),
outer_code: String(item.CargoNumber || item.SkuSelfCode || data.CargoNumber || data.ProductSelfCode || ''),
spec: truncate(item.Name || attrs, 255),
image: truncate(data.ImageUrl || item.ImgUrl, 255),
price: toNumber(item.SalePrice),
stock: Math.max(0, Math.trunc(toNumber(item.AvailableCount))),
status,
platform_type: platformType,
external_shop_id: externalShopId,
raw: { product: productRaw, sku: sku || null },
};
});
}
/**
* 拉取店铺订单(按商家 FxUserId 过滤)。
* 店管家订单列表不提供商家维度的过滤参数(UpFxUserId 过滤会返回服务器繁忙),
* 因此按时间窗 + 分区域名拉取全量后,在本地按订单的 UpFxUserId 归属到店铺。
* @param {Object} shop OMS 店铺记录(type=2,external_data 为商家原始结构)
* @param {Object} [options] 查询参数
* @param {Date|string} [options.startTime] 平台下单时间起(含)
* @param {Date|string} [options.endTime] 平台下单时间止(含)
* @return {Promise<{total: number, list: Array, hosts: Array}>} 订单列表
*/
async listOrders(shop, options = {}) {
if (!this.token || !this.cookie) {
throw new Error('账号未登录:缺少 token 或 cookie,请先登录');
}
const data = (shop && shop.external_data) || {};
const merchantFxUserId = String(data.FxUserId || '').trim();
if (!merchantFxUserId) throw new Error('店铺缺少商家 FxUserId,无法拉取平台订单');
const end = options.endTime ? new Date(options.endTime) : new Date();
const start = options.startTime
? new Date(options.startTime)
: new Date(end.getTime() - 7 * 24 * 3600 * 1000);
const hosts = this.resolveProductHosts(data);
let traceId = '';
try {
const info = await this.getUserInfo();
traceId = (info.data && info.data.TraceId) || '';
} catch {
// 忽略:traceId 缺失不阻断订单查询
}
const orders = new Map();
const hitHosts = [];
for (const host of hosts) {
const areas = await this.listProductAreas(host);
for (const area of areas) {
const fetched = await this.fetchOrderPages(host, {
traceId,
dbname: area.dbname,
startTime: start,
endTime: end,
});
if (fetched.length) hitHosts.push(`${host}(${area.name || area.dbname})`);
for (const row of fetched) {
// 订单列表按账号维度返回,这里只保留当前商家的订单
if (String(row.UpFxUserId || '') !== merchantFxUserId) continue;
const order = this.normalizeOrder(row);
if (order.external_order_id) orders.set(order.external_order_id, order);
}
}
}
return { total: orders.size, list: Array.from(orders.values()), hosts: hitHosts };
}
/**
* 按分页拉取订单列表(不归属过滤,交由调用方按商家过滤)
* @param {string} host 接口域名
* @param {Object} options 查询参数
* @param {string} options.traceId 登录上下文 traceId
* @param {string} options.dbname 分区库名
* @param {Date} options.startTime 下单时间起
* @param {Date} options.endTime 下单时间止
* @return {Promise<Array>} 订单原始结构列表
*/
async fetchOrderPages(host, { traceId, dbname, startTime, endTime }) {
const rows = [];
let pageCount = 1;
for (let pageIndex = 1; pageIndex <= ORDER_MAX_PAGES; pageIndex++) {
const page = await this.fetchOrderPage(host, {
traceId,
dbname,
startTime,
endTime,
pageIndex,
});
rows.push(...page.rows);
pageCount = page.pageCount || pageCount;
if (page.rows.length < ORDER_PAGE_SIZE || pageIndex >= pageCount) break;
}
return rows;
}
/**
* 拉取一页订单
* @param {string} host 接口域名
* @param {Object} options 查询参数
* @param {string} options.traceId 登录上下文 traceId
* @param {string} options.dbname 分区库名
* @param {Date} options.startTime 下单时间起
* @param {Date} options.endTime 下单时间止
* @param {number} options.pageIndex 页码
* @return {Promise<{rows: Array, total: number, pageCount: number}>} 当页订单
*/
async fetchOrderPage(host, { traceId, dbname, startTime, endTime, pageIndex }) {
const query = new URLSearchParams({
token: this.token,
traceId: traceId || '',
dbname: dbname || '',
dataFlag: '',
});
const form = new URLSearchParams();
const filter = (index, fields) => {
for (const [ key, value ] of Object.entries(fields)) form.append(`Filters[${index}][${key}]`, value);
};
filter(0, {
TableAlias: 'o',
FieldType: 'DateTime',
TableName: 'LogicOrder',
Name: 'CreateTime',
Value: formatOrderTime(startTime),
ExtValue: formatOrderTime(endTime),
Contract: 'between',
});
form.set('IsOrderDesc', 'true');
form.set('OrderByField', 'o.CreateTime');
form.set('IsPdd', 'false');
form.set('PageSize', String(ORDER_PAGE_SIZE));
form.set('PageIndex', String(pageIndex));
form.set('isFilterDangerChar', 'false');
form.set('TarType', '');
form.set('requestUrl', `https://${host}/NewOrder/WaitOrder`);
form.set('IsCustomerOrder', 'false');
form.set('FxPageType', '2');
const headers = {
accept: 'application/json, text/javascript, */*; q=0.01',
'accept-language': 'zh-CN,zh;q=0.9',
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
referer: `https://${host}/NewOrder/WaitOrder`,
'user-agent': BROWSER_HEADERS['user-agent'],
'x-requested-with': 'XMLHttpRequest',
};
if (this.cookie) headers.cookie = this.cookie;
const res = await this.request(`https://${host}${ORDER_LIST_PATH}?${query.toString()}`, {
method: 'POST',
headers,
body: form.toString(),
});
if (res.status === 401) {
throw new Error(`店管家登录已失效:${(res.json && res.json.Message) || 'token is invalid'}`);
}
if (!res.json || res.json.Success !== true) {
const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`;
throw new Error(`拉取店管家订单失败(${host}):${reason}`);
}
const data = res.json.Data || {};
return {
rows: Array.isArray(data.Rows) ? data.Rows : [],
total: Number(data.Total) || 0,
pageCount: Number(data.PageCount) || 1,
};
}
/**
* 把店管家订单结构转换为统一结构(明细保留平台商品快照,不在此处做系统商品匹配)
* @param {Object} row 店管家订单原始结构
* @return {Object} 统一订单结构
*/
normalizeOrder(row) {
const data = row || {};
const subOrders = Array.isArray(data.SubOrders) ? data.SubOrders : [];
return {
external_order_id: String(data.PlatformOrderId || data.LogicOrderId || ''),
external_shop_id: data.ShopId == null ? '' : String(data.ShopId),
external_shop_name: truncate(data.ShopName || data.AgentShopName || data.SelfShopName, 128),
platform_type: truncate(data.PlatformType, 32),
platform_status: truncate(data.ErpState || data.Status, 32),
order_no: String(data.PlatformOrderId || data.LogicOrderId || ''),
total_amount: toNumber(data.TotalAmount),
pay_amount: toNumber(data.SumTotalAmount || data.TotalAmount),
// 店管家对收件人脱敏(明文仅打印组件可取):这里保留可用的省市区与脱敏明细地址
receiver: {
name: data.ToName || '',
phone: data.ToPhone || '',
address: data.ToAddress || '',
full_address: data.ToFullAddress || '',
province: data.ToProvince || '',
city: data.ToCity || '',
area: data.ToCounty || '',
town: data.ToTown || '',
masked: !!(data.ToName && /\*/.test(String(data.ToName))) || !!(data.ToAddress && /\*/.test(String(data.ToAddress))),
},
remark: truncate(data.BuyerRemark || data.SellerRemark, 255),
external_created_at: parseOrderTime(data.CreateTime),
external_updated_at: parseOrderTime(data.UpdateTime),
raw: data,
items: subOrders.map(item => this.normalizeOrderItem(item)),
};
}
/**
* 把店管家订单明细转换为统一结构:平台商品快照原样保留,
* 系统商品关联由上层按店铺商品绑定关系决定(未绑定时保持原样)
* @param {Object} item 店管家明细原始结构
* @return {Object} 统一明细结构
*/
normalizeOrderItem(item) {
const data = item || {};
const ptInfo = data.PtProductInfo || {};
const spec = data.Color || data.Size || ptInfo.PrductSpecs || '';
return {
external_item_id: data.OrderItemId == null ? '' : truncate(data.OrderItemId, 64),
outer_item_id: String(data.ProductID || ptInfo.PrductId || ''),
outer_sku_id: resolveOrderSkuId(data),
sku_code: truncate(data.CargoNumber || data.productCargoNumber || ptInfo.CargoNumber, 100),
name: truncate(data.ProductSubject || ptInfo.ProductSubject, 255),
spec: truncate(spec, 255),
image: truncate(data.ProductImgUrl || ptInfo.ProductImgUrl, 255),
quantity: toNumber(data.Count),
price: toNumber(data.Price),
total_amount: toNumber(data.ItemAmount),
// 店管家基准商品的关联状态(IsRelationBaseProduct=true 表示该明细已关联平台基础商品)
relation_base_product: !!data.IsRelationBaseProduct,
base_product: data.BaseProductInfo || null,
raw: data,
};
}
/**
* 登录:token + cookie 有效时直接复用;否则用账号密码登录,
* 成功后把 token 与 cookie 写回账号表,避免上下文丢失

View File

@ -14,6 +14,16 @@ module.exports = app => {
order_no: { type: STRING(50), allowNull: false, comment: '业务订单号' },
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
shop_id: { type: BIGINT.UNSIGNED, comment: '所属店铺ID,为空表示未关联店铺' },
external_print_account_id: { type: BIGINT.UNSIGNED, comment: '来源外部打单账号ID' },
external_order_id: { type: STRING(64), comment: '平台订单号(店管家 PlatformOrderId)' },
platform_type: { type: STRING(32), comment: '平台类型:TouTiao/Taobao/Pinduoduo 等' },
platform_status: { type: STRING(32), comment: '平台侧订单状态' },
external_shop_id: { type: STRING(64), comment: '平台侧店铺ID(店管家 ShopId)' },
external_shop_name: { type: STRING(128), comment: '平台侧店铺名称' },
external_created_at: { type: DATE, comment: '平台侧订单创建时间' },
external_updated_at: { type: DATE, comment: '平台侧订单更新时间' },
synced_at: { type: DATE, comment: '最近一次从平台同步的时间' },
external_data: { type: JSON, comment: '平台返回的订单原始结构' },
order_type: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '订单类型' },
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '主状态:1待处理 2处理中 3已完成 4已取消' },
wms_status: { type: STRING(50), comment: '外部WMS状态' },

View File

@ -18,6 +18,7 @@ module.exports = app => {
product_id: { type: BIGINT.UNSIGNED, comment: '系统商品ID,为空表示未解析出商品' },
combo_product_id: { type: BIGINT.UNSIGNED, comment: '组合商品ID,为空表示非组合商品' },
shop_product_id: { type: BIGINT.UNSIGNED, comment: '命中的店铺商品ID' },
external_item_id: { type: STRING(64), comment: '平台明细ID(店管家 OrderItemId)' },
item_type: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '明细类型:0未识别 1普通商品 2组合商品' },
parse_status: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '解析状态:0未解析 1已解析 2解析失败' },
parse_msg: { type: STRING(255), comment: '解析失败原因' },
@ -31,6 +32,7 @@ module.exports = app => {
price: { type: DECIMAL(12, 2), comment: '单价' },
total_amount: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '明细金额' },
raw: { type: JSON, comment: '平台返回的明细原始数据' },
platform_snapshot: { type: JSON, comment: '平台明细快照(绑定前的编码/名称/规格/图片,用于解绑还原)' },
created_at: { type: DATE, comment: '创建时间' },
updated_at: { type: DATE, comment: '更新时间' },
});

View File

@ -6,7 +6,7 @@
* @return {object} shop model
*/
module.exports = app => {
const { BIGINT, STRING, TINYINT, JSON, DATE } = app.Sequelize;
const { BIGINT, STRING, TINYINT, INTEGER, JSON, DATE } = app.Sequelize;
const Shop = app.model.define('shop', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
@ -17,6 +17,18 @@ module.exports = app => {
contact_name: { type: STRING(50), comment: '联系人' },
contact_phone: { type: STRING(20), comment: '联系电话' },
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
type: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '店铺类型:1平台店铺 2外部打单平台商家 3数据库模式(预留)' },
external_print_account_id: { type: BIGINT.UNSIGNED, comment: '来源外部打单账号ID(type=2 时有值)' },
external_data: { type: JSON, comment: '外部打单平台返回的商家原始结构' },
db_host: { type: STRING(255), comment: '数据库地址(type=3 数据库模式店铺使用,预留)' },
db_port: { type: INTEGER, comment: '数据库端口(type=3 数据库模式店铺使用,预留)' },
db_name: { type: STRING(100), comment: '数据库名(type=3 数据库模式店铺使用,预留)' },
db_username: { type: STRING(100), comment: '数据库账号(type=3 数据库模式店铺使用,预留)' },
db_password: { type: STRING(255), comment: '数据库密码(type=3 数据库模式店铺使用,预留,接口不回显)' },
auto_fetch_order: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '是否自动拉取订单:1是 0否' },
auto_fetch_interval: { type: INTEGER, allowNull: false, defaultValue: 3, comment: '自动拉取订单间隔(分钟,最小 3)' },
last_order_sync_at: { type: DATE, comment: '最近一次拉取订单时间' },
last_order_sync_msg: { type: STRING(255), comment: '最近一次拉取订单结果/失败原因' },
extra: { type: JSON, comment: '扩展配置 JSON:授权信息、接口参数等' },
remark: { type: STRING(255), comment: '备注' },
created_at: { type: DATE, comment: '创建时间' },
@ -25,6 +37,7 @@ module.exports = app => {
Shop.associate = () => {
app.model.Shop.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
app.model.Shop.belongsTo(app.model.ExternalPrintAccount, { foreignKey: 'external_print_account_id', as: 'externalPrintAccount' });
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' });

View File

@ -23,6 +23,8 @@ module.exports = app => {
price: { type: DECIMAL(12, 2), comment: '店铺售价' },
stock: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '采集到的库存' },
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '店铺商品状态:1在售 0下架' },
platform_type: { type: STRING(32), comment: '外部平台类型:TouTiao/Taobao/Pinduoduo 等' },
external_shop_id: { type: STRING(64), comment: '外部平台的店铺ID(如店管家 ShopId)' },
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,未绑定为空' },

View File

@ -82,7 +82,6 @@ module.exports = app => {
router.post('/api/order-status/push-wms', jwtAuth, principalCheck(), controller.orderStatus.pushWmsBatch);
// 批量切换仓库 / 设置所属店铺(同步刷新快照)
router.post('/api/order-status/change-warehouse', jwtAuth, principalCheck(), controller.orderStatus.changeWarehouse);
router.post('/api/order-status/change-shop', jwtAuth, principalCheck(), controller.orderStatus.changeShop);
// 订单详情 / 编辑 / 删除(删除仅限待审核、异常、已取消)/ 推送仓库(单条)
router.get('/api/order-status/:id', jwtAuth, principalCheck(), controller.orderStatus.show);
router.put('/api/order-status/:id', jwtAuth, principalCheck(), controller.orderStatus.update);
@ -122,13 +121,25 @@ module.exports = app => {
router.resources('orderItems', '/api/order-items', jwtAuth, principalCheck({ model: 'OrderItem' }), controller.orderItem);
// 店铺与店铺商品(采集的商品可绑定到系统商品或组合商品)
router.resources('shops', '/api/shops', jwtAuth, principalCheck({ model: 'Shop' }), controller.shop);
router.resources('shopProducts', '/api/shop-products', jwtAuth, principalCheck({ model: 'ShopProduct' }), controller.shopProduct);
// 店铺商品完全来自平台采集:不提供手工新增 / 编辑 / 删除,只保留查询与绑定;
// 同步商品时平台已不存在的商品会自动移除
router.get('/api/shop-products', jwtAuth, principalCheck({ model: 'ShopProduct' }), controller.shopProduct.index);
router.get('/api/shop-products/:id', jwtAuth, principalCheck({ model: 'ShopProduct' }), controller.shopProduct.show);
router.post('/api/shop-products/:id/bind', jwtAuth, principalCheck({ model: 'ShopProduct' }), controller.shopProduct.bind);
// 外部打单平台:平台基础资料由开发者维护(只读查询);打单账号归属主体,在「店铺管理」下维护
router.get('/api/external-print-platforms', jwtAuth, controller.externalPrintPlatform.index);
// 账号登录态检查 / 登录(需在 resources 之前注册,避免被 /:id 误匹配)
router.post('/api/external-print-accounts/:id/check', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.check);
router.post('/api/external-print-accounts/:id/login', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.login);
// 平台侧店铺(商家)列表与创建到 OMS 店铺(前端按账号ID调用,后端按平台服务分发)
router.get('/api/external-print-accounts/:id/merchants', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.merchants);
router.post('/api/external-print-accounts/:id/shops', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.createShops);
// 同步商家店铺商品(按商家分区逐域名拉取全量快照后写入店铺商品表)
router.post('/api/external-print-accounts/:id/shops/:shopId/sync-products', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.syncShopProducts);
// 按平台商品ID单独补拉(订单明细匹配不到店铺商品时使用,不做下架处理)
router.post('/api/external-print-accounts/:id/shops/:shopId/pull-products', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.pullShopProducts);
// 拉取商家订单(含明细),明细按店铺商品绑定关系写入系统商品关联
router.post('/api/external-print-accounts/:id/shops/:shopId/sync-orders', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.syncShopOrders);
router.resources('externalPrintAccounts', '/api/external-print-accounts', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount);
// 出入库单与明细(明细共用 stock_items 表,以 bill_type 区分:1入库 2出库)
// 单据状态由业务事务推动(审核/推送/完成/驳回/作废/取消/恢复),不提供直接修改状态的接口

View File

@ -0,0 +1,109 @@
'use strict';
/**
* 定时拉取外部打单平台订单。
*
* 每分钟扫描开启「自动拉取订单」的外部打单平台店铺(type=2),
* 按各店铺配置的间隔(auto_fetch_interval,最小 3 分钟)判断是否到期:
* - 上次拉取时间 + 间隔 > 现在 → 跳过
* - 否则以「上次拉取时间向前重叠 10 分钟」为起点拉取,避免边界订单漏单;
* 从未拉取过时按最近一个间隔拉取
*
* 拉取逻辑与手动拉取共用 service(externalPrintOrder),保证入库口径一致;
* 每次执行后记录 last_order_sync_at / last_order_sync_msg,失败不影响其它店铺。
*/
const OVERLAP_MS = 10 * 60 * 1000;
const MIN_INTERVAL_MINUTES = 3;
const DEFAULT_INTERVAL_MINUTES = 3;
/** 防止上一轮未结束时重复触发(单进程内串行) */
let running = false;
module.exports = {
schedule: {
cron: '0 * * * * *',
type: 'worker',
disable: false,
},
async task(ctx) {
if (running) {
ctx.logger.info('[external-order-fetch] 上一轮仍在执行,跳过本次');
return { skipped: true };
}
running = true;
try {
const Op = ctx.app.Sequelize.Op;
const shops = await ctx.model.Shop.findAll({
where: {
type: 2,
status: 1,
auto_fetch_order: 1,
external_print_account_id: { [Op.ne]: null },
},
order: [[ 'id', 'ASC' ]],
});
if (!shops.length) return { shops: 0 };
const accountIds = Array.from(new Set(shops.map(shop => Number(shop.external_print_account_id))));
const accounts = await ctx.model.ExternalPrintAccount.findAll({
where: { id: { [Op.in]: accountIds } },
include: [
{
model: ctx.model.ExternalPrintPlatform,
as: 'platform',
attributes: [ 'id', 'code', 'name', 'url', 'fetch_waybill_no' ],
},
],
});
const accountMap = new Map(accounts.map(account => [ Number(account.id), account ]));
const now = new Date();
let fetched = 0;
let failed = 0;
for (const shop of shops) {
const interval = Math.max(
MIN_INTERVAL_MINUTES,
Number(shop.auto_fetch_interval) || DEFAULT_INTERVAL_MINUTES
) * 60 * 1000;
const last = shop.last_order_sync_at ? new Date(shop.last_order_sync_at) : null;
if (last && now.getTime() - last.getTime() < interval) continue;
const account = accountMap.get(Number(shop.external_print_account_id));
if (!account) {
await ctx.service.externalPrintOrder.markShopSynced(shop, now, '拉单失败:店铺关联的打单账号不存在');
failed++;
continue;
}
const startTime = last ? new Date(last.getTime() - OVERLAP_MS) : new Date(now.getTime() - interval);
try {
const result = await ctx.service.externalPrintOrder.syncOrders(shop, account, {
startTime,
endTime: now,
});
await ctx.service.externalPrintOrder.markShopSynced(
shop,
now,
`自动拉取成功:${result.orders} 单(新增 ${result.created},更新 ${result.updated}),明细 ${result.items} 条`
);
fetched++;
ctx.logger.info(
`[external-order-fetch] 店铺 ${shop.id} 拉单成功:订单 ${result.orders},明细 ${result.items}`
);
} catch (err) {
await ctx.service.externalPrintOrder.markShopSynced(shop, now, `自动拉取失败:${err.message}`);
failed++;
ctx.logger.warn(`[external-order-fetch] 店铺 ${shop.id} 拉单失败:${err.message}`);
}
}
return { shops: shops.length, fetched, failed };
} finally {
running = false;
}
},
};

View File

@ -0,0 +1,423 @@
'use strict';
const Service = require('egg').Service;
const { createPrintPlatformService, hasPrintPlatformService } = require('../lib/printPlatform');
const { ORDER_STATUS } = require('../lib/orderStatus');
const { buildSnapshot } = require('../lib/orderItemExpand');
/**
* 截断字符串,避免超出表字段长度
* @param {*} value 原始值
* @param {number} max 最大长度
* @return {string} 截断后的字符串
*/
function truncateText(value, max) {
return String(value == null ? '' : value).slice(0, max);
}
/**
* 明细行转列表摘要快照(与订单页 product_info 口径一致)
* @param {Array} lines 明细
* @return {Array|null} 快照
*/
function buildProductInfo(lines) {
const list = Array.isArray(lines) ? lines : [];
if (!list.length) return null;
return list.map(line => ({
item_code: line.sku_code || line.outer_item_id || null,
item_name: line.name || null,
quantity: line.quantity,
price: line.price,
}));
}
/**
* 明细行转平台原样快照:绑定系统商品/组合商品时明细字段会被覆盖或拆分,解绑时按此还原
* @param {Object} line 平台明细
* @param {String} lineNo 原行号
* @return {Object} 快照
*/
function buildPlatformSnapshot(line, lineNo) {
return buildSnapshot(line, lineNo);
}
/**
* 外部打单平台订单拉取服务
*
* 同时服务手动拉取(控制器)与定时拉取(app/schedule/fetchExternalShopOrders.js),
* 保证两条链路的取数与入库规则完全一致:
* 1. 明细先按(店铺 + 平台商品ID + 平台规格ID)命中店铺商品,记录 shop_product_id;
* 2. 店铺商品已绑定系统商品/组合商品时写入 product_id / combo_product_id 并标记已解析;
* 3. 未采集或未绑定时保留平台原样快照,标记为待处理(parse_status=2)。
*/
class ExternalPrintOrderService extends Service {
/**
* 按账号所属平台创建服务实例;cookie/token 变更时写回账号表
* @param {Object} account 账号实例(需 include platform)
* @return {Object} 平台服务实例
*/
createPlatformService(account) {
const platform = account.platform;
if (!platform) throw new Error('打单账号未关联外部打单平台');
if (!hasPrintPlatformService(platform.code)) {
throw new Error(`外部打单平台 ${platform.name}(${platform.code})暂未接入`);
}
return createPrintPlatformService(platform.code, {
platform: platform.get({ plain: true }),
account: account.get({ plain: true }),
saveCookie: async cookie => {
await account.update({ cookie });
},
saveToken: async token => {
await account.update({ token });
},
saveLoginStatus: async status => {
if (Number(account.login_status) !== Number(status)) {
await account.update({ login_status: status });
}
},
});
}
/**
* 拉取并写入某个店铺的订单(含明细)
* @param {Object} shop 店铺实例(type=2 外部打单平台商家)
* @param {Object} account 账号实例(需 include platform)
* @param {Object} options 时间窗
* @param {Date} options.startTime 平台下单时间起
* @param {Date} options.endTime 平台下单时间止
* @return {Promise<Object>} 拉取与写入统计
*/
async syncOrders(shop, account, { startTime, endTime }) {
const platformService = this.createPlatformService(account);
const result = await platformService.listOrders(shop.get ? shop.get({ plain: true }) : shop, {
startTime,
endTime,
});
const saved = await this.saveOrders(shop, account, result.list);
return {
startTime,
endTime,
orders: result.total,
created: saved.created,
updated: saved.updated,
items: saved.items,
itemsBound: saved.itemsBound,
itemsUnbound: saved.itemsUnbound,
hosts: result.hosts,
};
}
/**
* 写入平台订单与明细(按 order_no 去重,明细按 external_item_id 去重)
* @param {Object} shop 店铺实例
* @param {Object} account 账号实例
* @param {Array} list 平台订单列表
* @return {Promise<Object>} 写入统计
*/
async saveOrders(shop, account, list) {
const { ctx } = this;
const now = new Date();
let created = 0;
let updated = 0;
let items = 0;
let itemsBound = 0;
let itemsUnbound = 0;
const transaction = await ctx.model.transaction();
try {
for (const item of list) {
const externalOrderId = String(item.external_order_id || '').trim();
if (!externalOrderId) continue;
const orderNo = truncateText(`${account.platform.code}-${externalOrderId}`, 50);
const fields = {
principal_id: shop.principal_id,
shop_id: shop.id,
order_no: orderNo,
order_type: 1,
total_amount: item.total_amount,
pay_amount: item.pay_amount,
receiver: item.receiver,
remark: item.remark || null,
external_print_account_id: account.id,
external_order_id: externalOrderId,
platform_type: item.platform_type || null,
platform_status: item.platform_status || null,
external_shop_id: item.external_shop_id || null,
external_shop_name: item.external_shop_name || null,
external_created_at: item.external_created_at,
external_updated_at: item.external_updated_at,
synced_at: now,
external_data: item.raw,
};
let order = await ctx.model.Order.findOne({
where: { principal_id: shop.principal_id, order_no: orderNo },
transaction,
});
if (order) {
await order.update(fields, { transaction });
updated++;
} else {
order = await ctx.model.Order.create(fields, { transaction });
created++;
}
const existingItems = await ctx.model.OrderItem.findAll({
where: { order_id: order.id },
attributes: [ 'id', 'external_item_id' ],
raw: true,
transaction,
});
const itemIdMap = new Map(existingItems.map(row => [ String(row.external_item_id || ''), row.id ]));
const resolvedLines = [];
for (const [ lineIndex, line ] of (item.items || []).entries()) {
const externalItemId = String(line.external_item_id || '').trim();
const matched = await this.matchShopProduct(shop, line);
const bound = this.resolveBoundProduct(matched);
resolvedLines.push({ line, externalItemId, matched, bound });
const lineFields = {
principal_id: shop.principal_id,
order_id: order.id,
shop_id: shop.id,
shop_product_id: matched ? matched.id : null,
product_id: bound.product_id,
combo_product_id: bound.combo_product_id,
item_type: bound.item_type,
parse_status: bound.parse_status,
parse_msg: bound.parse_msg,
outer_item_id: line.outer_item_id || null,
outer_sku_id: line.outer_sku_id || null,
sku_code: line.sku_code || null,
// 未绑定系统商品时保留平台原样快照
name: line.name || null,
spec: line.spec || null,
image: line.image || null,
quantity: line.quantity,
price: line.price,
total_amount: line.total_amount,
external_item_id: externalItemId || null,
raw: line.raw,
platform_snapshot: buildPlatformSnapshot(line, lineIndex + 1),
};
const existId = externalItemId ? itemIdMap.get(externalItemId) : null;
if (existId) {
await ctx.model.OrderItem.update(lineFields, { where: { id: existId }, transaction });
} else {
await ctx.model.OrderItem.create(lineFields, { transaction });
}
items++;
if (bound.parse_status === 1) itemsBound++;
else itemsUnbound++;
}
// 同步写入「待审核」状态表:订单页(待审核/待推送…)读取的是状态分表,不写这里列表看不到
await this.saveOrderToPending(shop, account, item, resolvedLines, transaction);
}
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
return { created, updated, items, itemsBound, itemsUnbound };
}
/**
* 写入「待审核」状态表(order_index + order_status_pending + order_status_items)。
* 订单页的待审核/待推送等视图都基于状态分表,平台订单必须落到这里才可见。
* 已流转到其它状态(待推送/异常/委外中…)的订单不覆盖,避免打乱仓内流程。
* @param {Object} shop 店铺实例
* @param {Object} account 账号实例
* @param {Object} item 平台订单
* @param {Array} resolvedLines 已解析的明细(line / externalItemId / matched / bound)
* @param {Object} transaction 事务
* @return {Promise<void>} 无返回值
*/
async saveOrderToPending(shop, account, item, resolvedLines, transaction) {
const { ctx } = this;
const externalOrderId = String(item.external_order_id || '').trim();
const lines = resolvedLines || [];
const receiver = item.receiver || {};
const phone = String(receiver.phone || '').trim();
const itemTotal = lines.reduce((sum, row) => sum + (Number(row.line.quantity) || 0), 0);
const itemAmount = lines.reduce((sum, row) => sum + (Number(row.line.total_amount) || 0), 0);
const fields = {
shop_id: shop.id,
// 订单页「店铺」列展示 OMS 店铺名(平台店铺名带手机号,写入 extend_props 备用)
shop_nick: truncateText(shop.name, 200),
product_info: buildProductInfo(lines.map(row => row.line)),
receiver: truncateText(receiver.name, 50),
mobile: truncateText(phone, 50),
tel: truncateText(phone, 50),
province: truncateText(receiver.province, 100),
city: truncateText(receiver.city, 100),
area: truncateText(receiver.area, 100),
town: truncateText(receiver.town, 100),
detail_address: truncateText(receiver.address, 500),
address: truncateText(receiver.full_address || receiver.address, 255),
total_amount: item.total_amount,
pay_amount: item.pay_amount,
item_amount: Number(itemAmount.toFixed(2)),
item_total: Number(itemTotal.toFixed(3)),
item_kind: lines.length,
source_platform_code: truncateText(item.platform_type, 50),
source_platform_name: truncateText(item.platform_type, 200),
buyer_message: truncateText(item.remark, 500),
place_order_time: item.external_created_at,
pay_time: item.external_updated_at,
remark: truncateText(item.remark, 255),
order_type: 'JYCK',
extend_props: {
source: 'external_print',
platform: account.platform.code,
platform_shop_id: item.external_shop_id || null,
platform_shop_name: item.external_shop_name || null,
receiver_masked: !!receiver.masked,
},
};
let index = await ctx.model.OrderIndex.findOne({
where: { principal_id: shop.principal_id, parent_order_no: externalOrderId },
transaction,
});
let orderId;
if (index) {
const pending = await ctx.model.OrderStatusPending.findByPk(index.id, { transaction });
// 已流转出待审核(待推送/异常/委外中/配送…)时保持现状
if (!pending) return;
orderId = index.id;
await pending.update(fields, { transaction });
} else {
const orderNo = truncateText(`${account.platform.code}-${externalOrderId}`, 50);
index = await ctx.model.OrderIndex.create({
order_no: orderNo,
parent_order_no: externalOrderId,
principal_id: shop.principal_id,
current_table: ORDER_STATUS.PENDING,
current_status: ORDER_STATUS.PENDING,
}, { transaction });
orderId = index.id;
await ctx.model.OrderStatusPending.create({
...fields,
id: orderId,
order_no: orderNo,
parent_order_no: externalOrderId,
principal_id: shop.principal_id,
status: ORDER_STATUS.PENDING,
}, { transaction });
}
// 明细整体替换:平台侧可能调整规格/数量
// 先按平台原样落库(保留原行号/原数量/原单价),再由统一解析器按店铺商品绑定关系展开为最小单位
await ctx.model.OrderStatusItem.destroy({ where: { order_id: orderId }, transaction });
const rows = lines.map(({ line, externalItemId, matched, bound }, idx) => ({
principal_id: shop.principal_id,
order_id: orderId,
shop_id: shop.id,
order_line_no: String(idx + 1),
item_code: truncateText(line.sku_code || line.outer_item_id, 100),
item_name: truncateText(line.name, 255),
plan_qty: line.quantity,
actual_price: line.price,
retail_price: line.price,
ext_code: truncateText(line.outer_item_id, 100),
inventory_type: 'ZP',
source_order_code: truncateText(externalOrderId, 50),
sub_source_order_code: truncateText(externalItemId, 50),
shop_product_id: matched ? matched.id : null,
product_id: bound.product_id,
combo_product_id: bound.combo_product_id,
item_type: bound.item_type,
parse_status: bound.parse_status,
parse_msg: bound.parse_msg,
outer_item_id: line.outer_item_id || null,
outer_sku_id: line.outer_sku_id || null,
sku_code: truncateText(line.sku_code, 100),
spec: truncateText(line.spec, 255),
image: truncateText(line.image, 255),
quantity: line.quantity,
price: line.price,
total_amount: line.total_amount,
raw: line.raw,
platform_snapshot: buildPlatformSnapshot(line, idx + 1),
}));
if (rows.length) await ctx.model.OrderStatusItem.bulkCreate(rows, { transaction });
// 按绑定关系重新展开(组合商品拆成子商品行),并刷新订单头摘要与明细统计
await ctx.service.orderItemResolve.rebuildOrderItems([ orderId ], { transaction });
}
/**
* 按平台商品ID/规格ID命中店铺商品(规格ID为空时按商品ID匹配任意规格)
* @param {Object} shop 店铺实例
* @param {Object} line 平台明细
* @return {Promise<Object|null>} 店铺商品
*/
async matchShopProduct(shop, line) {
const { ctx } = this;
const outerItemId = String(line.outer_item_id || '').trim();
if (!outerItemId) return null;
const where = { shop_id: shop.id, outer_item_id: outerItemId };
const outerSkuId = String(line.outer_sku_id || '').trim();
if (outerSkuId) where.outer_sku_id = outerSkuId;
return ctx.model.ShopProduct.findOne({ where });
}
/**
* 由店铺商品绑定关系推导订单明细的关联结果;未绑定时保持未解析(保留平台快照)
* @param {Object|null} shopProduct 店铺商品
* @return {{product_id: number|null, combo_product_id: number|null, item_type: number, parse_status: number, parse_msg: string|null}} 关联结果
*/
resolveBoundProduct(shopProduct) {
if (!shopProduct) {
return {
product_id: null,
combo_product_id: null,
item_type: 0,
parse_status: 2,
parse_msg: '未采集到该店铺商品,已保留平台原样数据',
};
}
if (Number(shopProduct.bind_type) === 1 && shopProduct.product_id) {
return { product_id: shopProduct.product_id, combo_product_id: null, item_type: 1, parse_status: 1, parse_msg: null };
}
if (Number(shopProduct.bind_type) === 2 && shopProduct.combo_product_id) {
return { product_id: null, combo_product_id: shopProduct.combo_product_id, item_type: 2, parse_status: 1, parse_msg: null };
}
return {
product_id: null,
combo_product_id: null,
item_type: 0,
parse_status: 2,
parse_msg: '店铺商品未绑定系统商品,已保留平台原样数据',
};
}
/**
* 记录店铺最近一次拉单结果(定时任务据此判断是否到期)
* @param {Object} shop 店铺实例
* @param {Date} syncedAt 本次拉单时间
* @param {string} message 结果说明
* @return {Promise<void>} 无返回值
*/
async markShopSynced(shop, syncedAt, message) {
await shop.update({
last_order_sync_at: syncedAt,
last_order_sync_msg: truncateText(message, 255),
});
}
}
module.exports = ExternalPrintOrderService;

View File

@ -0,0 +1,194 @@
'use strict';
const Service = require('egg').Service;
const { foldPlatformLines, normalizeSnapshot, expandPlatformLine } = require('../lib/orderItemExpand');
const { ORDER_STATUS } = require('../lib/orderStatus');
/**
* 订单明细解析服务
*
* 平台订单明细按「店铺商品 → 系统商品 / 组合商品」的绑定关系解析为最小单位:
* - 未采集到店铺商品 / 店铺商品未绑定系统商品:保留平台原样一行(parse_status=2)
* - 绑定系统商品:一行对一行
* - 绑定组合商品:拆成组合内每个子商品一行(数量 = 平台数量 × 组合内数量,单价取子商品零售价)
*
* 明细行始终在 platform_snapshot 里保留平台原样,因此绑定关系变化时可以折叠回平台行再重新展开,
* 行数变化(1 行 ↔ N 行)不会丢失原始数量与单价。
*/
class OrderItemResolveService extends Service {
/**
* 批量载入组合商品的子商品明细
* @param {Array<number>} comboIds 组合商品ID
* @return {Promise<Map<number, Array>>} comboId → 子商品数组
*/
async loadComboItems(comboIds) {
const { ctx } = this;
const map = new Map();
const ids = [ ...new Set((comboIds || []).map(Number).filter(id => id > 0)) ];
if (!ids.length) return map;
const Op = this.app.Sequelize.Op;
const rows = await ctx.model.ComboProductItem.findAll({
where: { combo_product_id: { [Op.in]: ids } },
include: [{
model: ctx.model.Product,
as: 'product',
attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'image', 'retail_price' ],
required: false,
}],
order: [[ 'id', 'ASC' ]],
});
for (const row of rows) {
const plain = row.get({ plain: true });
const product = plain.product || {};
const comboId = Number(plain.combo_product_id);
if (!map.has(comboId)) map.set(comboId, []);
map.get(comboId).push({
product_id: Number(plain.product_id),
quantity: Number(plain.quantity) || 1,
item_code: product.item_code || null,
item_name: product.item_name || null,
sku_property: product.sku_property || null,
image: product.image || null,
retail_price: product.retail_price,
});
}
return map;
}
/**
* 批量载入店铺商品的绑定上下文
* @param {Array<number>} shopProductIds 店铺商品ID
* @return {Promise<Map<number, Object>>} shopProductId → { shopProduct, product, combo, comboItems }
*/
async loadBindings(shopProductIds) {
const { ctx } = this;
const map = new Map();
const ids = [ ...new Set((shopProductIds || []).map(Number).filter(id => id > 0)) ];
if (!ids.length) return map;
const Op = this.app.Sequelize.Op;
const shopProducts = await ctx.model.ShopProduct.findAll({
where: { id: { [Op.in]: ids } },
raw: true,
});
if (!shopProducts.length) return map;
const productIds = shopProducts
.filter(row => Number(row.bind_type) === 1 && row.product_id)
.map(row => Number(row.product_id));
const comboIds = shopProducts
.filter(row => Number(row.bind_type) === 2 && row.combo_product_id)
.map(row => Number(row.combo_product_id));
const products = productIds.length
? await ctx.model.Product.findAll({ where: { id: { [Op.in]: productIds } }, raw: true })
: [];
const combos = comboIds.length
? await ctx.model.ComboProduct.findAll({ where: { id: { [Op.in]: comboIds } }, raw: true })
: [];
const comboItems = await this.loadComboItems(comboIds);
const productMap = new Map(products.map(row => [ Number(row.id), row ]));
const comboMap = new Map(combos.map(row => [ Number(row.id), row ]));
for (const shopProduct of shopProducts) {
const bindType = Number(shopProduct.bind_type);
const product = bindType === 1 ? productMap.get(Number(shopProduct.product_id)) : null;
const combo = bindType === 2 ? comboMap.get(Number(shopProduct.combo_product_id)) : null;
map.set(Number(shopProduct.id), {
shopProduct,
product: product || null,
combo: combo || null,
comboItems: combo ? comboItems.get(Number(combo.id)) || [] : [],
});
}
return map;
}
/**
* 按当前绑定关系重建若干订单的明细(折叠为平台行 → 重新展开为最小单位)
*
* 默认只处理「待审核 / 异常」:这两类允许维护明细;
* 待推送及之后的订单明细已随审核锁定库存、甚至已下发仓库,改动会与仓内流程不一致。
* 不含平台溯源信息(手工录入)的订单整单跳过。
* @param {Array<number>} orderIds 订单ID
* @param {Object} [options] { transaction, statuses }
* @return {Promise<number>} 重建后的明细行数合计
*/
async rebuildOrderItems(orderIds, options = {}) {
const { ctx } = this;
const ids = [ ...new Set((orderIds || []).map(Number).filter(id => id > 0)) ];
if (!ids.length) return 0;
const Op = this.app.Sequelize.Op;
const statuses = options.statuses || [ ORDER_STATUS.PENDING, ORDER_STATUS.EXCEPTION ];
const indexRows = await ctx.model.OrderIndex.findAll({
where: { id: { [Op.in]: ids }, current_status: { [Op.in]: statuses } },
attributes: [ 'id' ],
raw: true,
});
const targetIds = indexRows.map(row => Number(row.id));
if (!targetIds.length) return 0;
const transaction = options.transaction || await ctx.model.transaction();
const ownedTransaction = !options.transaction;
let affected = 0;
try {
for (const orderId of targetIds) {
const rows = await ctx.model.OrderStatusItem.findAll({
where: { order_id: orderId },
order: [[ 'order_line_no', 'ASC' ], [ 'id', 'ASC' ]],
raw: true,
transaction,
});
if (!rows.length) continue;
// 只重建「平台行」:手工录入的明细没有平台溯源信息(快照 / 平台商品ID / 店铺商品),
// 一旦按平台口径重排会被抹成未解析并丢掉已选商品,因此整单跳过,保持原样
const isPlatformOrder = rows.every(row => row.platform_snapshot
|| row.shop_product_id != null
|| String(row.outer_item_id || '').trim());
if (!isPlatformOrder) continue;
const lines = foldPlatformLines(rows);
const bindings = await this.loadBindings(lines.map(line => line.shop_product_id));
const payload = [];
for (const line of lines) {
const snapshot = normalizeSnapshot(line);
const binding = line.shop_product_id ? bindings.get(Number(line.shop_product_id)) : null;
const parts = expandPlatformLine({ ...line, platform_snapshot: snapshot }, binding || {});
for (const part of parts) payload.push(part);
}
await ctx.model.OrderStatusItem.destroy({ where: { order_id: orderId }, transaction });
if (payload.length) {
await ctx.model.OrderStatusItem.bulkCreate(
payload.map((row, idx) => ({
...row,
principal_id: rows[0].principal_id,
order_id: orderId,
order_line_no: String(idx + 1),
})),
{ transaction }
);
}
await ctx.service.orderStatus.refreshItemSummary(orderId, rows[0].principal_id, transaction);
affected += payload.length;
}
if (ownedTransaction) await transaction.commit();
} catch (err) {
if (ownedTransaction) await transaction.rollback();
throw err;
}
return affected;
}
}
module.exports = OrderItemResolveService;

View File

@ -27,6 +27,9 @@ const ARCHIVE_BATCH_LIMIT = 200;
/** 手工创建订单在扩展字段(extend_props)中写入的标记(与老发货单一致) */
const HANDMADE_ORDER_LABEL = '手工单';
/** 店铺类型:2 外部打单平台商家(其订单只能由平台拉取,手工建单不可选) */
const SHOP_TYPE_EXTERNAL = 2;
/** 可编辑单据头/明细的状态(仅未审核的订单允许改) */
const EDITABLE_STATUSES = [ ORDER_STATUS.PENDING, ORDER_STATUS.EXCEPTION ];
@ -347,6 +350,17 @@ class OrderStatusService extends Service {
}
}
// exclude_unbound=1:排除「有未绑定系统商品的明细」的订单(订单页默认只看已解析订单)
// 用 EXISTS 子查询而非 IN 列表,避免未绑定订单很多时拼接超长参数
if (String(p.exclude_unbound) === '1') {
where[Op.and] = [
ctx.app.Sequelize.literal(
'NOT EXISTS (SELECT 1 FROM order_status_items oi WHERE oi.order_id = `' + Model.tableName + '`.id ' +
`AND oi.principal_id = ${principalId} AND oi.parse_status = 2)`
),
];
}
const { count, rows } = await Model.findAndCountAll({
where,
offset: p.offset,
@ -376,6 +390,8 @@ class OrderStatusService extends Service {
row.current_table = status;
row.product_summary = this._productSummary(row.product_info);
row.product_kind = Array.isArray(row.product_info) ? row.product_info.length : 0;
// 平台拉取的订单店铺由平台决定,前端据此禁用「设置店铺」
row.is_external = this._isExternalPrintOrder(row);
}
// 无 product_info 快照(新建发货单走 items 明细、老数据搬迁)时,按明细表现算摘要,
@ -413,6 +429,24 @@ class OrderStatusService extends Service {
const nameById = new Map(shops.map(shop => [ Number(shop.id), shop.name ]));
for (const row of list) row.shop_name = nameById.get(Number(row.shop_id)) || null;
}
// 仓库名称(状态表只存 warehouse_id + warehouse_code 快照,列表按 id 批量补名称,列表展示名称而非编码)
const warehouseIds = [
...new Set(list.map(row => Number(row.warehouse_id)).filter(id => Number.isInteger(id) && id > 0)),
];
if (warehouseIds.length) {
const warehouses = await ctx.model.Warehouse.findAll({
where: { id: { [Op.in]: warehouseIds }, principal_id: principalId },
attributes: [ 'id', 'code', 'name' ],
});
const warehouseById = new Map(warehouses.map(item => [ Number(item.id), item ]));
for (const row of list) {
const warehouse = warehouseById.get(Number(row.warehouse_id));
if (!warehouse) continue;
row.warehouse_name = warehouse.name;
row.warehouse_code = row.warehouse_code || warehouse.code;
}
}
}
/**
@ -549,13 +583,23 @@ class OrderStatusService extends Service {
shopId = Number(payload.shop_id);
const shop = await ctx.model.Shop.findOne({
where: { id: shopId, principal_id: principalId },
attributes: [ 'id', 'name' ],
attributes: [ 'id', 'name', 'type' ],
});
if (!shop) {
const err = new Error('店铺不存在或不属于当前主体');
err.status = 404;
throw err;
}
// 外部打单平台店铺的订单只能由平台拉取,手工建单不允许选择
if (Number(shop.type) === SHOP_TYPE_EXTERNAL) {
const err = new Error('外部打单平台店铺的订单由平台拉取,手工建单请选择其它店铺');
err.status = 400;
throw err;
}
} else {
const err = new Error('请选择店铺(手工订单必须指定店铺,平台拉取的店铺不可选)');
err.status = 400;
throw err;
}
// 仓库:可空(审核前补齐即可),但填了必须是当前主体的仓库,并快照 warehouse_code
@ -710,8 +754,32 @@ class OrderStatusService extends Service {
*/
async _replaceItems(orderId, principalId, items, transaction) {
const { ctx } = this;
// 平台订单(外部打单平台拉取)的明细带平台溯源信息(快照 / 店铺商品 / 平台商品 ID),
// 手工覆盖时前端不会回传这些字段,按行号沿用,否则再次绑定/解绑就还原不回平台原样数据
const existings = await ctx.model.OrderStatusItem.findAll({
where: { order_id: orderId, principal_id: principalId },
attributes: [
'order_line_no', 'platform_snapshot', 'shop_product_id', 'outer_item_id', 'outer_sku_id',
'product_id', 'combo_product_id', 'item_type', 'parse_status', 'parse_msg',
],
raw: true,
transaction,
});
const existingByLine = new Map(existings.map(row => [ String(row.order_line_no), row ]));
await ctx.model.OrderStatusItem.destroy({ where: { order_id: orderId, principal_id: principalId }, transaction });
const rows = items.map((item, idx) => this._buildItemRow(item, { principalId, orderId, lineIndex: idx }));
const rows = items.map((item, idx) => {
const row = this._buildItemRow(item, { principalId, orderId, lineIndex: idx });
const source = existingByLine.get(String(row.order_line_no));
if (!source) return row;
if (!row.platform_snapshot && source.platform_snapshot) row.platform_snapshot = source.platform_snapshot;
for (const field of [ 'shop_product_id', 'outer_item_id', 'outer_sku_id', 'product_id', 'combo_product_id', 'parse_msg' ]) {
if (row[field] == null && source[field] != null) row[field] = source[field];
}
if (!Number(row.item_type)) row.item_type = Number(source.item_type) || 0;
if (!Number(row.parse_status)) row.parse_status = Number(source.parse_status) || 0;
return row;
});
return ctx.model.OrderStatusItem.bulkCreate(rows, { transaction });
}
@ -757,6 +825,7 @@ class OrderStatusService extends Service {
price: num(body.price == null ? body.actual_price : body.price),
total_amount: Number(body.total_amount == null ? 0 : body.total_amount),
raw: body.raw && typeof body.raw === 'object' ? body.raw : null,
platform_snapshot: body.platform_snapshot && typeof body.platform_snapshot === 'object' ? body.platform_snapshot : null,
};
}
@ -1223,6 +1292,8 @@ class OrderStatusService extends Service {
plain.status_label = orderStatusLabel(plain.status);
plain.current_table = row.current_status;
plain.product_summary = this._productSummary(plain.product_info);
// 平台拉取的订单不允许改店铺(前端据此禁用店铺下拉)
plain.is_external = this._isExternalPrintOrder(plain);
if (plain.shop_id) {
const shop = await ctx.model.Shop.findByPk(plain.shop_id, { attributes: [ 'id', 'name' ] });
if (shop) plain.shop_name = shop.name;
@ -1379,6 +1450,17 @@ class OrderStatusService extends Service {
}
const current = await this._model(row.current_status).findByPk(row.id);
// 店铺由平台决定:平台拉取的订单不允许通过编辑改店铺
if (body.shop_id !== undefined && this._isExternalPrintOrder(current)) {
const nextShopId = body.shop_id === null || body.shop_id === '' ? null : Number(body.shop_id);
if (nextShopId !== Number(current.shop_id)) {
const err = new Error('该订单由外部打单平台拉取,店铺不可修改');
err.status = 400;
throw err;
}
}
const merged = { ...current.get({ plain: true }), ...patch };
const receiverError = validateReceiver(merged);
if (receiverError) {
@ -1455,7 +1537,6 @@ class OrderStatusService extends Service {
async changeWarehouse(p = {}) {
return this._changeOwnerField({
ids: p.ids,
field: 'warehouse',
value: p.warehouse_id,
actionLabel: '切换仓库',
allowedFrom: [ ORDER_STATUS.PENDING, ORDER_STATUS.EXCEPTION, ORDER_STATUS.QUEUED ],
@ -1463,37 +1544,31 @@ class OrderStatusService extends Service {
}
/**
* 批量设置所属店铺(只影响推送时的快递策略与 OMS 记录,不回写 WMS,委外中也允许修正)
* @param {Object} p { ids, shop_id }
* @return {Promise<Object>} { updated, target_shop }
* 判断订单是否由外部打单平台拉取(其店铺由平台决定,不允许人工改店铺)
* @param {Object} row 状态表记录(含 extend_props)
* @return {boolean} 是否平台拉取订单
*/
async changeShop(p = {}) {
return this._changeOwnerField({
ids: p.ids,
field: 'shop',
value: p.shop_id,
actionLabel: '设置所属店铺',
allowedFrom: [ ORDER_STATUS.PENDING, ORDER_STATUS.EXCEPTION, ORDER_STATUS.QUEUED, ORDER_STATUS.OUTSOURCING ],
});
_isExternalPrintOrder(row) {
const props = row && row.extend_props;
return !!(props && typeof props === 'object' && props.source === 'external_print');
}
/**
* 批量变更仓库 / 店铺(按状态分组更新,同步刷新编码 / 名称快照)
* 批量切换发货仓库(按状态分组更新,同步刷新仓库编码快照)
* @param {Object} p 参数
* @param {Array} p.ids 订单 id
* @param {String} p.field warehouse 或 shop
* @param {Number} p.value 目标仓库 / 店铺 id
* @param {Number} p.value 目标仓库 id
* @param {String} p.actionLabel 动作名(用于报错文案)
* @param {Array} p.allowedFrom 允许的来源状态
* @return {Promise<Object>} { updated, target, scope }
*/
async _changeOwnerField({ ids, field, value, actionLabel, allowedFrom }) {
async _changeOwnerField({ ids, value, actionLabel, allowedFrom }) {
const { ctx } = this;
const Op = ctx.app.Sequelize.Op;
const principalId = ctx.state.principalId;
const targetId = value === null || value === undefined || value === '' ? null : Number(value);
if (!targetId) {
const err = new Error(`${field}_id 为必填项`);
const err = new Error('warehouse_id 为必填项');
err.status = 400;
throw err;
}
@ -1510,43 +1585,84 @@ class OrderStatusService extends Service {
throw err;
}
let patch;
let target;
if (field === 'warehouse') {
const warehouse = await ctx.model.Warehouse.findOne({
where: { id: targetId, principal_id: principalId },
attributes: [ 'id', 'code', 'name' ],
});
if (!warehouse) {
const err = new Error('仓库不存在或不属于当前主体');
err.status = 404;
throw err;
}
patch = { warehouse_id: targetId, warehouse_code: warehouse.code };
target = { id: Number(warehouse.id), code: warehouse.code, name: warehouse.name };
} else {
const shop = await ctx.model.Shop.findOne({
where: { id: targetId, principal_id: principalId },
attributes: [ 'id', 'name' ],
});
if (!shop) {
const err = new Error('店铺不存在或不属于当前主体');
err.status = 404;
throw err;
}
patch = { shop_id: targetId, shop_nick: shop.name };
target = { id: Number(shop.id), name: shop.name };
const targets = indexRows;
const warehouse = await ctx.model.Warehouse.findOne({
where: { id: targetId, principal_id: principalId },
attributes: [ 'id', 'code', 'name' ],
});
if (!warehouse) {
const err = new Error('仓库不存在或不属于当前主体');
err.status = 404;
throw err;
}
const patch = { warehouse_id: targetId, warehouse_code: warehouse.code };
const target = { id: Number(warehouse.id), code: warehouse.code, name: warehouse.name };
let updated = 0;
for (const status of new Set(indexRows.map(row => row.current_status))) {
const groupIds = indexRows.filter(row => row.current_status === status).map(row => Number(row.id));
for (const status of new Set(targets.map(row => row.current_status))) {
const groupIds = targets.filter(row => row.current_status === status).map(row => Number(row.id));
const [ count ] = await this._model(status).update(patch, {
where: { principal_id: principalId, id: { [Op.in]: groupIds } },
});
updated += Number(count) || 0;
}
return { updated, target, scope: { ids: indexRows.map(row => Number(row.id)) } };
return { updated, target, scope: { ids: targets.map(row => Number(row.id)) } };
}
/**
* 按当前明细重算订单头的商品摘要(product_info)与明细统计(item_total / item_kind / item_amount)
*
* 明细被重新解析(绑定/解绑、组合商品拆分为最小单位)后调用,保证列表展示与明细口径一致。
* @param {number} orderId 订单ID
* @param {number} [principalId] 主体ID(默认取上下文;定时任务里需显式传入)
* @param {Object} [transaction] 事务
* @return {Promise<void>} 无返回值
*/
async refreshItemSummary(orderId, principalId, transaction) {
const { ctx } = this;
const pid = Number(principalId || ctx.state.principalId);
if (!Number.isInteger(pid) || pid <= 0) return;
const [ index ] = await ctx.model.OrderIndex.findAll({
where: { id: orderId, principal_id: pid },
attributes: [ 'current_status' ],
raw: true,
transaction,
});
if (!index) return;
const items = await ctx.model.OrderStatusItem.findAll({
where: { order_id: orderId, principal_id: pid },
attributes: [ 'item_code', 'item_name', 'plan_qty', 'actual_price', 'order_line_no', 'id' ],
order: [[ 'order_line_no', 'ASC' ], [ 'id', 'ASC' ]],
raw: true,
transaction,
});
let itemTotal = 0;
let itemAmount = 0;
const productInfo = items.map(line => {
const qty = Number(line.plan_qty) || 0;
const price = line.actual_price == null ? 0 : Number(line.actual_price);
itemTotal += qty;
itemAmount += qty * price;
return {
item_code: line.item_code,
item_name: line.item_name,
quantity: qty,
price: line.actual_price == null ? null : price,
};
});
await this._model(index.current_status).update(
{
product_info: productInfo.length ? productInfo : null,
item_total: Number(itemTotal.toFixed(3)),
item_kind: items.length,
item_amount: Number(itemAmount.toFixed(2)),
},
{ where: { id: orderId, principal_id: pid }, transaction }
);
}
/**
@ -1634,7 +1750,7 @@ class OrderStatusService extends Service {
const { ctx } = this;
const shops = await ctx.model.Shop.findAll({
where: { principal_id: ctx.state.principalId },
attributes: [ 'id', 'name' ],
attributes: [ 'id', 'code', 'name', 'type' ],
order: [[ 'id', 'ASC' ]],
limit: 500,
});
@ -1652,7 +1768,12 @@ class OrderStatusService extends Service {
archive_months: ORDER_ARCHIVE_MONTHS,
index_table: ORDER_INDEX_TABLE,
item_table: ORDER_ITEM_TABLE,
shops: shops.map(shop => ({ id: Number(shop.id), name: shop.name })),
shops: shops.map(shop => ({
id: Number(shop.id),
code: shop.code,
name: shop.name,
type: Number(shop.type) || 1,
})),
warehouses: warehouses.map(warehouse => ({
id: Number(warehouse.id),
code: warehouse.code,

View File

@ -619,6 +619,7 @@ const EXPORT_TYPES = {
{ key: 'created_to', label: '创建时间止', type: 'date' },
{ key: 'archived_from', label: '归档时间起', type: 'date' },
{ key: 'archived_to', label: '归档时间止', type: 'date' },
{ key: 'exclude_unbound', label: '排除含未绑定商品的订单', type: 'select', options: [{ value: '1', label: '是' }] },
],
build: (f, ctx) => {
// 订单按状态分表存储:指定状态时只查对应表,未指定时 UNION ALL 各状态表
@ -642,6 +643,12 @@ const EXPORT_TYPES = {
.to('created_at', f.created_to)
.from('archived_at', f.archived_from)
.to('archived_at', f.archived_to);
if (String(f.exclude_unbound) === '1') {
wh.raw(
'NOT EXISTS (SELECT 1 FROM order_status_items oi WHERE oi.order_id = t.id ' +
`AND oi.principal_id = ${Number(ctx.principalId)} AND oi.parse_status = 2)`
);
}
return buildResult({
columns: ORDER_COLUMNS,
from: `(${inner}) AS t`,
@ -805,6 +812,7 @@ const EXPORT_TYPES = {
{ key: 'shop_id', label: '店铺', type: 'shop' },
{ key: 'bind_type', label: '绑定类型', type: 'select', options: BIND_TYPE_OPTIONS },
{ key: 'status', label: '状态', type: 'select', options: ENABLE_OPTIONS },
{ key: 'has_unbound_order', label: '只看有订单未绑定', type: 'select', options: [{ value: '1', label: '是' }] },
{ key: 'keyword', label: '关键词', type: 'text', placeholder: '标题 / 平台商品ID / 规格ID / 商家编码' },
],
build: (f, ctx) => {
@ -814,6 +822,14 @@ const EXPORT_TYPES = {
.eq('t.bind_type', f.bind_type)
.eq('t.status', f.status)
.kw([ 't.title', 't.outer_item_id', 't.outer_sku_id', 't.outer_code' ], f.keyword);
// 有订单未绑定:与列表接口同口径(未绑定 + 被未解析的订单明细引用)
if (String(f.has_unbound_order) === '1') {
wh.raw('t.bind_type = 0');
wh.raw(
`t.id IN (SELECT DISTINCT shop_product_id FROM order_status_items WHERE principal_id = ${Number(ctx.principalId)} ` +
'AND parse_status = 2 AND shop_product_id IS NOT NULL)'
);
}
return buildResult({ columns: SHOP_PRODUCT_COLUMNS, from: 'shop_products t', wh });
},
},

View File

@ -0,0 +1,47 @@
'use strict';
/**
* 店铺表扩展:支持从外部打单平台(如店管家的商家)创建店铺。
*
* - type:店铺类型(1 平台店铺 / 2 外部打单平台商家),用于区分手工/平台店铺与外部导入店铺
* - external_print_account_id:来源外部打单账号(type=2 时有值),便于按账号查看/追溯
* - external_data:外部打单平台返回的商家原始结构(原样保存,后续按需取字段)
* - db_mode:数据库模式(预留字段,供后续分区/多库逻辑使用)
*/
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('shops', 'type', {
type: Sequelize.TINYINT,
allowNull: false,
defaultValue: 1,
comment: '店铺类型:1平台店铺 2外部打单平台商家',
});
await queryInterface.addColumn('shops', 'external_print_account_id', {
type: Sequelize.BIGINT.UNSIGNED,
allowNull: true,
comment: '来源外部打单账号ID(type=2 时有值)',
});
await queryInterface.addColumn('shops', 'external_data', {
type: Sequelize.JSON,
allowNull: true,
comment: '外部打单平台返回的商家原始结构',
});
await queryInterface.addColumn('shops', 'db_mode', {
type: Sequelize.STRING(50),
allowNull: true,
comment: '数据库模式(预留,后续分区/多库逻辑使用)',
});
await queryInterface.addIndex('shops', { fields: [ 'external_print_account_id' ], name: 'idx_shops_external_account' });
await queryInterface.addIndex('shops', { fields: [ 'type' ], name: 'idx_shops_type' });
},
async down(queryInterface) {
await queryInterface.removeIndex('shops', 'idx_shops_external_account');
await queryInterface.removeIndex('shops', 'idx_shops_type');
await queryInterface.removeColumn('shops', 'db_mode');
await queryInterface.removeColumn('shops', 'external_data');
await queryInterface.removeColumn('shops', 'external_print_account_id');
await queryInterface.removeColumn('shops', 'type');
},
};

View File

@ -0,0 +1,69 @@
'use strict';
/**
* 修正「数据库模式」语义:它是店铺的一种类型(预约),
* 用于店铺配置自己的数据库账号密码以自动取单,与外部打单平台无关。
*
* - 删除此前误加的 db_mode(曾用于存平台分区标识;平台原始结构仍保留在 external_data 中)
* - 新增数据库连接配置字段(type=3 数据库模式店铺使用,具体逻辑后续实现)
* - type 注释补充 3=数据库模式(预留)
*/
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.removeColumn('shops', 'db_mode');
await queryInterface.addColumn('shops', 'db_host', {
type: Sequelize.STRING(255),
allowNull: true,
comment: '数据库地址(type=3 数据库模式店铺使用,预留)',
});
await queryInterface.addColumn('shops', 'db_port', {
type: Sequelize.INTEGER,
allowNull: true,
comment: '数据库端口(type=3 数据库模式店铺使用,预留)',
});
await queryInterface.addColumn('shops', 'db_name', {
type: Sequelize.STRING(100),
allowNull: true,
comment: '数据库名(type=3 数据库模式店铺使用,预留)',
});
await queryInterface.addColumn('shops', 'db_username', {
type: Sequelize.STRING(100),
allowNull: true,
comment: '数据库账号(type=3 数据库模式店铺使用,预留)',
});
await queryInterface.addColumn('shops', 'db_password', {
type: Sequelize.STRING(255),
allowNull: true,
comment: '数据库密码(type=3 数据库模式店铺使用,预留,接口不回显)',
});
await queryInterface.changeColumn('shops', 'type', {
type: Sequelize.TINYINT,
allowNull: false,
defaultValue: 1,
comment: '店铺类型:1平台店铺 2外部打单平台商家 3数据库模式(预留)',
});
},
async down(queryInterface, Sequelize) {
await queryInterface.removeColumn('shops', 'db_password');
await queryInterface.removeColumn('shops', 'db_username');
await queryInterface.removeColumn('shops', 'db_name');
await queryInterface.removeColumn('shops', 'db_port');
await queryInterface.removeColumn('shops', 'db_host');
await queryInterface.addColumn('shops', 'db_mode', {
type: Sequelize.STRING(50),
allowNull: true,
comment: '数据库模式(预留,后续分区/多库逻辑使用)',
});
await queryInterface.changeColumn('shops', 'type', {
type: Sequelize.TINYINT,
allowNull: false,
defaultValue: 1,
comment: '店铺类型:1平台店铺 2外部打单平台商家',
});
},
};

View File

@ -0,0 +1,31 @@
'use strict';
/**
* 店铺增加「自动拉取订单」配置。
*
* - auto_fetch_order:是否自动拉取订单(1 是 / 0 否),默认关闭
* - auto_fetch_interval:拉取间隔(分钟),默认 3,最小 3(业务层校验)
*
* 具体拉单调度逻辑后续实现,本次先提供配置项。
*/
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('shops', 'auto_fetch_order', {
type: Sequelize.TINYINT,
allowNull: false,
defaultValue: 0,
comment: '是否自动拉取订单:1是 0否',
});
await queryInterface.addColumn('shops', 'auto_fetch_interval', {
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: 3,
comment: '自动拉取订单间隔(分钟,最小 3)',
});
},
async down(queryInterface) {
await queryInterface.removeColumn('shops', 'auto_fetch_interval');
await queryInterface.removeColumn('shops', 'auto_fetch_order');
},
};

View File

@ -0,0 +1,34 @@
'use strict';
/**
* 店铺商品增加外部平台标识。
*
* - platform_type:平台商品结构里的平台类型(如 TouTiao / Taobao / Pinduoduo),
* 同一商家的商品可能来自多个平台,需与商品ID一起区分来源
* - external_shop_id:外部平台的店铺ID(如店管家商品结构里的 ShopId),
* 用于区分同一商家在不同平台店铺下的商品
*/
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('shop_products', 'platform_type', {
type: Sequelize.STRING(32),
allowNull: true,
comment: '外部平台类型:TouTiao/Taobao/Pinduoduo 等',
});
await queryInterface.addColumn('shop_products', 'external_shop_id', {
type: Sequelize.STRING(64),
allowNull: true,
comment: '外部平台的店铺ID(如店管家 ShopId)',
});
await queryInterface.addIndex('shop_products', {
fields: [ 'shop_id', 'platform_type' ],
name: 'idx_shop_products_shop_platform',
});
},
async down(queryInterface) {
await queryInterface.removeIndex('shop_products', 'idx_shop_products_shop_platform');
await queryInterface.removeColumn('shop_products', 'external_shop_id');
await queryInterface.removeColumn('shop_products', 'platform_type');
},
};

View File

@ -0,0 +1,99 @@
'use strict';
/**
* 订单与订单明细增加外部打单平台(如店管家)来源字段。
*
* orders:
* - external_print_account_id / external_order_id:来源打单账号与平台订单号(PlatformOrderId),用于去重与回查
* - platform_type / platform_status:平台类型(TouTiao/Taobao…)与平台侧状态(ErpState)
* - external_shop_id / external_shop_name:平台侧店铺(一个商家可有多个平台店铺)
* - external_created_at / external_updated_at / synced_at:平台上创建、更新时间与最近同步时间
* - external_data:平台返回的订单原始结构
*
* order_items:
* - external_item_id:平台明细ID(OrderItemId),与订单ID一起唯一标识一条明细
*/
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('orders', 'external_print_account_id', {
type: Sequelize.BIGINT.UNSIGNED,
allowNull: true,
comment: '来源外部打单账号ID',
});
await queryInterface.addColumn('orders', 'external_order_id', {
type: Sequelize.STRING(64),
allowNull: true,
comment: '平台订单号(店管家 PlatformOrderId)',
});
await queryInterface.addColumn('orders', 'platform_type', {
type: Sequelize.STRING(32),
allowNull: true,
comment: '平台类型:TouTiao/Taobao/Pinduoduo 等',
});
await queryInterface.addColumn('orders', 'platform_status', {
type: Sequelize.STRING(32),
allowNull: true,
comment: '平台侧订单状态(如 waitsellersend)',
});
await queryInterface.addColumn('orders', 'external_shop_id', {
type: Sequelize.STRING(64),
allowNull: true,
comment: '平台侧店铺ID(店管家 ShopId)',
});
await queryInterface.addColumn('orders', 'external_shop_name', {
type: Sequelize.STRING(128),
allowNull: true,
comment: '平台侧店铺名称',
});
await queryInterface.addColumn('orders', 'external_created_at', {
type: Sequelize.DATE,
allowNull: true,
comment: '平台侧订单创建时间',
});
await queryInterface.addColumn('orders', 'external_updated_at', {
type: Sequelize.DATE,
allowNull: true,
comment: '平台侧订单更新时间',
});
await queryInterface.addColumn('orders', 'synced_at', {
type: Sequelize.DATE,
allowNull: true,
comment: '最近一次从平台同步的时间',
});
await queryInterface.addColumn('orders', 'external_data', {
type: Sequelize.JSON,
allowNull: true,
comment: '平台返回的订单原始结构',
});
await queryInterface.addIndex('orders', { fields: [ 'principal_id', 'external_order_id' ], name: 'idx_orders_principal_external' });
await queryInterface.addIndex('orders', { fields: [ 'shop_id', 'external_order_id' ], name: 'idx_orders_shop_external' });
await queryInterface.addColumn('order_items', 'external_item_id', {
type: Sequelize.STRING(64),
allowNull: true,
comment: '平台明细ID(店管家 OrderItemId)',
});
await queryInterface.addIndex('order_items', {
fields: [ 'order_id', 'external_item_id' ],
unique: true,
name: 'uk_order_items_order_external',
});
},
async down(queryInterface) {
await queryInterface.removeIndex('order_items', 'uk_order_items_order_external');
await queryInterface.removeColumn('order_items', 'external_item_id');
await queryInterface.removeIndex('orders', 'idx_orders_shop_external');
await queryInterface.removeIndex('orders', 'idx_orders_principal_external');
await queryInterface.removeColumn('orders', 'external_data');
await queryInterface.removeColumn('orders', 'synced_at');
await queryInterface.removeColumn('orders', 'external_updated_at');
await queryInterface.removeColumn('orders', 'external_created_at');
await queryInterface.removeColumn('orders', 'external_shop_name');
await queryInterface.removeColumn('orders', 'external_shop_id');
await queryInterface.removeColumn('orders', 'platform_status');
await queryInterface.removeColumn('orders', 'platform_type');
await queryInterface.removeColumn('orders', 'external_order_id');
await queryInterface.removeColumn('orders', 'external_print_account_id');
},
};

View File

@ -0,0 +1,29 @@
'use strict';
/**
* 店铺增加「最近拉取订单」状态,用于定时拉单判断间隔与前端展示。
*
* - last_order_sync_at:最近一次成功发起拉单的时间(含手动与定时)
* - last_order_sync_msg:最近一次拉单结果/失败原因
*/
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('shops', 'last_order_sync_at', {
type: Sequelize.DATE,
allowNull: true,
comment: '最近一次拉取订单时间',
});
await queryInterface.addColumn('shops', 'last_order_sync_msg', {
type: Sequelize.STRING(255),
allowNull: true,
comment: '最近一次拉取订单结果/失败原因',
});
await queryInterface.addIndex('shops', [ 'type', 'auto_fetch_order' ], { name: 'idx_shops_type_auto_fetch' });
},
async down(queryInterface) {
await queryInterface.removeIndex('shops', 'idx_shops_type_auto_fetch');
await queryInterface.removeColumn('shops', 'last_order_sync_msg');
await queryInterface.removeColumn('shops', 'last_order_sync_at');
},
};

View File

@ -0,0 +1,19 @@
'use strict';
/**
* 订单明细增加「主体 + 店铺商品 + 解析状态」索引。
*
* 用途:店铺商品页按「有订单未绑定」快速筛选(order_status_items.shop_product_id + parse_status),
* 以及列表回填每个店铺商品的待处理订单数,避免全表扫描。
*/
module.exports = {
async up(queryInterface) {
await queryInterface.addIndex('order_status_items', [ 'principal_id', 'shop_product_id', 'parse_status' ], {
name: 'idx_order_status_items_principal_shop_product',
});
},
async down(queryInterface) {
await queryInterface.removeIndex('order_status_items', 'idx_order_status_items_principal_shop_product');
},
};

View File

@ -0,0 +1,35 @@
'use strict';
/**
* 订单明细增加「平台原样快照」列。
*
* 背景:绑定系统商品/组合商品时,明细的编码/名称/规格/图片会被系统商品信息覆盖;
* 解绑后需要还原为平台原始快照,而 raw 列是平台各异的原始报文,无法通用还原,
* 因此在拉单时把统一结构下的平台快照单独留存在 platform_snapshot。
*/
const SNAPSHOT_COLUMN = {
type: 'JSON',
allowNull: true,
comment: '平台明细快照(绑定前的编码/名称/规格/图片,用于解绑还原)',
};
module.exports = {
async up(queryInterface, Sequelize) {
// 幂等:上一次执行可能因数据库异常中断,列已加上但迁移未记录
for (const table of [ 'order_items', 'order_status_items' ]) {
const columns = await queryInterface.describeTable(table);
if (!columns.platform_snapshot) {
await queryInterface.addColumn(table, 'platform_snapshot', { ...SNAPSHOT_COLUMN, type: Sequelize.JSON });
}
}
},
async down(queryInterface) {
for (const table of [ 'order_items', 'order_status_items' ]) {
const columns = await queryInterface.describeTable(table);
if (columns.platform_snapshot) {
await queryInterface.removeColumn(table, 'platform_snapshot');
}
}
},
};

View File

@ -17,6 +17,7 @@
"migration:down:all": "sequelize-cli db:migrate:undo:all",
"migration:create": "sequelize-cli migration:generate --name",
"swagger:export": "node scripts/export-swagger.js",
"order-items:rebuild": "node scripts/rebuild-order-items.js",
"deploy": "npm run deploy:prod",
"deploy:prod": "npm --prefix ../tools run deploy --",
"deploy:backend": "npm --prefix ../tools run deploy:backend --",

View File

@ -0,0 +1,98 @@
'use strict';
/**
* 重建订单明细(平台订单解析口径变更后的存量修复工具)。
*
* 背景:平台订单明细需要按店铺商品绑定关系展开为最小单位(组合商品拆成子商品行),
* 旧代码只把绑定结果写回明细、不做拆分,存量订单会残留组合行。
*
* 用法:
* node scripts/rebuild-order-items.js # 重建全部外部打单平台订单
* node scripts/rebuild-order-items.js --order 226 # 只重建指定订单(可逗号分隔)
* node scripts/rebuild-order-items.js --dry-run # 只统计不写库
*/
const mm = require('egg-mock');
/**
* 解析命令行参数
* @param {Array<string>} argv 进程参数(process.argv.slice(2))
* @return {{orderIds: Array<number>, dryRun: boolean}} 解析结果
*/
function parseArgs(argv) {
const args = { orderIds: [], dryRun: false };
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--dry-run') args.dryRun = true;
else if (arg === '--order' || arg === '--orders') {
const value = argv[i + 1] || '';
args.orderIds.push(...value.split(',').map(v => Number(v.trim())).filter(v => v > 0));
i++;
}
}
return args;
}
(async () => {
const args = parseArgs(process.argv.slice(2));
const app = mm.app();
await app.ready();
const ctx = app.mockContext();
let orderIds = args.orderIds;
const Op = app.Sequelize.Op;
if (!orderIds.length) {
// 只处理平台拉取的订单:老表 orders.external_order_id 有值 → 按 order_no 映射到订单索引表
const legacy = await ctx.model.Order.findAll({
where: { external_order_id: { [Op.ne]: null } },
attributes: [ 'order_no' ],
raw: true,
});
const orderNos = [ ...new Set(legacy.map(row => row.order_no).filter(Boolean)) ];
if (orderNos.length) {
const indexes = await ctx.model.OrderIndex.findAll({
where: { order_no: { [Op.in]: orderNos } },
attributes: [ 'id' ],
raw: true,
});
orderIds = indexes.map(row => Number(row.id));
}
}
if (!orderIds.length) {
console.log('没有需要重建的订单');
await app.close();
process.exit(0);
}
// 只重建允许维护明细的订单(待审核 / 异常):已推送仓库的订单明细保持历史原样
const candidates = await ctx.model.OrderIndex.findAll({
where: { id: { [Op.in]: orderIds }, current_status: { [Op.in]: [ 'pending', 'exception' ] } },
attributes: [ 'id', 'current_status' ],
raw: true,
});
orderIds = candidates.map(row => Number(row.id));
if (!orderIds.length) {
console.log('没有需要重建的订单(仅待审核 / 异常需要重建)');
await app.close();
process.exit(0);
}
if (args.dryRun) {
console.log(`[dry-run] 待重建订单 ${orderIds.length} 个:${orderIds.slice(0, 20).join(', ')}${orderIds.length > 20 ? ' …' : ''}`);
await app.close();
process.exit(0);
}
let affected = 0;
for (const orderId of orderIds) {
affected += await ctx.service.orderItemResolve.rebuildOrderItems([ orderId ]);
}
console.log(`重建完成:订单 ${orderIds.length} 个,明细行 ${affected} 行`);
await app.close();
process.exit(0);
})().catch(err => {
console.error('重建失败:', err);
process.exit(1);
});

View File

@ -0,0 +1,144 @@
'use strict';
const { assert } = require('egg-mock/bootstrap');
const {
buildSnapshot,
normalizeSnapshot,
foldPlatformLines,
expandPlatformLine,
} = require('../../../app/lib/orderItemExpand');
/**
* 订单明细「平台行 ↔ 最小单位行」互转的单测。
*
* 覆盖三类绑定口径:未绑定(保留平台原样)、系统商品(一行对一行)、组合商品(拆成子商品行),
* 以及子行折叠回平台行时不丢原始数量/单价。
*/
describe('app/lib/orderItemExpand', () => {
const comboLine = {
line_no: '1',
item_code: 'PK1',
item_name: '平台组合',
plan_qty: 2,
actual_price: 29.9,
shop_product_id: 9,
platform_snapshot: { item_code: 'PK1', item_name: '平台组合', line_no: '1', plan_qty: 2, actual_price: 29.9 },
template: { shop_id: 18 },
};
it('buildSnapshot 记录原行号、原数量与原单价', () => {
const snapshot = buildSnapshot(
{ sku_code: 'SKU1', name: '平台商品', spec: '红色', image: 'a.png', quantity: 2, price: 12.345 },
3
);
assert.deepStrictEqual(snapshot, {
item_code: 'SKU1',
item_name: '平台商品',
sku_code: 'SKU1',
spec: '红色',
image: 'a.png',
line_no: '3',
plan_qty: 2,
actual_price: 12.35,
});
});
it('绑定组合商品时拆成子商品行:数量相乘、单价取子商品零售价', () => {
const parts = expandPlatformLine(comboLine, {
shopProduct: { id: 9 },
combo: { id: 7, code: 'C1', name: '组合' },
comboItems: [{ product_id: 3, quantity: 20, item_code: 'P3', item_name: '测试商品', retail_price: '1.00' }],
});
assert.strictEqual(parts.length, 1);
assert.strictEqual(parts[0].item_code, 'P3');
assert.strictEqual(parts[0].plan_qty, 40);
assert.strictEqual(parts[0].actual_price, 1);
assert.strictEqual(parts[0].product_id, 3);
assert.strictEqual(parts[0].combo_product_id, 7);
assert.strictEqual(parts[0].parse_status, 1);
});
it('组合未配置子商品时保留组合行并提示', () => {
const parts = expandPlatformLine(comboLine, {
shopProduct: { id: 9 },
combo: { id: 7, code: 'C1', name: '组合' },
comboItems: [],
});
assert.strictEqual(parts.length, 1);
assert.strictEqual(parts[0].item_code, 'C1');
assert.strictEqual(parts[0].item_type, 2);
assert(parts[0].parse_msg.includes('未配置子商品'));
});
it('绑定系统商品时一行对一行', () => {
const parts = expandPlatformLine(comboLine, {
shopProduct: { id: 9 },
product: { id: 5, item_code: 'S5', item_name: '系统商品' },
});
assert.strictEqual(parts.length, 1);
assert.strictEqual(parts[0].item_code, 'S5');
assert.strictEqual(parts[0].plan_qty, 2);
assert.strictEqual(parts[0].item_type, 1);
});
it('未采集到店铺商品时保留平台原样并标记待处理', () => {
const parts = expandPlatformLine({ ...comboLine, platform_snapshot: null }, {});
assert.strictEqual(parts[0].item_code, 'PK1');
assert.strictEqual(parts[0].parse_status, 2);
assert(parts[0].parse_msg.includes('未采集到该店铺商品'));
});
it('子行按快照原行号折叠回平台行并恢复原数量', () => {
const rows = [
{
id: 1,
order_line_no: '1',
item_code: 'P3',
plan_qty: 40,
actual_price: 1,
platform_snapshot: { line_no: '1', item_code: 'PK1', item_name: '平台组合', plan_qty: 2, actual_price: 29.9 },
},
{
id: 2,
order_line_no: '2',
item_code: 'PK1',
plan_qty: 1,
actual_price: 29.9,
platform_snapshot: { line_no: '2', item_code: 'PK2', item_name: '平台第二行', plan_qty: 1, actual_price: 29.9 },
},
];
const lines = foldPlatformLines(rows);
assert.strictEqual(lines.length, 2);
assert.strictEqual(lines[0].item_code, 'PK1');
assert.strictEqual(lines[0].plan_qty, 2);
assert.strictEqual(lines[1].item_code, 'PK2');
});
it('同一平台行拆出的多子行只折叠为一行', () => {
const snapshot = { line_no: '1', item_code: 'PK1', plan_qty: 3, actual_price: 10 };
const lines = foldPlatformLines([
{ id: 1, order_line_no: '1', platform_snapshot: snapshot },
{ id: 2, order_line_no: '2', platform_snapshot: snapshot },
]);
assert.strictEqual(lines.length, 1);
assert.strictEqual(lines[0].plan_qty, 3);
});
it('无快照的历史行按自身独立折叠并补齐字段', () => {
const lines = foldPlatformLines([
{ id: 77, order_line_no: '4', item_code: 'X', item_name: 'Y', plan_qty: 5, actual_price: 3 },
]);
const snapshot = normalizeSnapshot(lines[0]);
assert.strictEqual(lines.length, 1);
assert.strictEqual(snapshot.line_no, '4');
assert.strictEqual(snapshot.plan_qty, 5);
assert.strictEqual(snapshot.actual_price, 3);
});
});