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

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

928 lines
32 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

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

'use strict';
/**
* 把东八区时间对齐到整天: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');
/**
* 列表/详情不回显密码与 cookie,仅返回是否已设置
* @param {object} row 账号记录(Sequelize 实例或普通对象)
* @return {object} 去掉凭据后的账号数据
*/
function toSafeAccount(row) {
const plain = typeof row.get === 'function' ? row.get({ plain: true }) : { ...row };
plain.has_password = !!plain.password;
plain.has_cookie = !!plain.cookie;
plain.has_token = !!plain.token;
delete plain.password;
delete plain.cookie;
delete plain.token;
return plain;
}
/** 店铺类型:2 外部打单平台商家 */
const SHOP_TYPE_EXTERNAL = 2;
/** 单品补拉时单次最多提交的商品数(订单明细一般远小于该值) */
const MAX_PULL_PRODUCT_ITEMS = 50;
/**
* 店铺商品唯一键(与店铺商品表的唯一索引对应)
* @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 外部打单账号列表
* @description 分页查询当前主体下的打单账号,支持按平台过滤与账号模糊搜索;响应不含密码
* @router get /api/external-print-accounts
* @apikey
* @request query integer page 页码,默认 1
* @request query integer pageSize 每页条数,默认 20
* @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体)
* @request query integer platform_id 外部打单平台ID,不传则返回全部平台
* @request query string keyword 关键词,匹配账号
* @response 200 externalPrintAccountListResponse success
*/
async index() {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
const { platform_id: platformId, keyword } = ctx.query;
const where = { principal_id: ctx.state.principalId };
if (platformId) where.platform_id = Number(platformId);
if (keyword) where.account = { [Op.like]: `%${String(keyword).trim()}%` };
const { count, rows } = await ctx.model.ExternalPrintAccount.findAndCountAll({
where,
offset,
limit,
order: [[ 'id', 'DESC' ]],
include: [
{
model: ctx.model.ExternalPrintPlatform,
as: 'platform',
attributes: [ 'id', 'code', 'name', 'url', 'fetch_waybill_no' ],
},
],
});
const list = rows.map(toSafeAccount);
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) };
}
/**
* @summary 外部打单账号详情
* @description 按主键查询账号信息(不含密码)
* @router get /api/external-print-accounts/{id}
* @apikey
* @request path integer *id 账号主键ID
* @response 200 baseResponse success
*/
async show() {
const { ctx } = this;
const item = await this.findAccount(ctx.params.id, { withPlatform: true });
if (!item) {
ctx.status = 404;
ctx.body = { code: 404, message: '打单账号不存在' };
return;
}
ctx.body = { code: 0, message: 'success', data: toSafeAccount(item) };
}
/**
* @summary 新增外部打单账号
* @description platform_id、account、password 必填;同一主体在同一平台下账号不能重复
* @router post /api/external-print-accounts
* @apikey
* @request body createExternalPrintAccountRequest *body
* @response 200 baseResponse success
*/
async create() {
const { ctx } = this;
const principalId = ctx.state.principalId;
const body = ctx.request.body || {};
const platformId = Number(body.platform_id);
const account = String(body.account || '').trim();
const password = String(body.password || '');
if (!platformId || !account || !password) {
ctx.status = 400;
ctx.body = { code: 400, message: 'platform_id(外部打单平台)、account(账号)、password(密码)为必填项' };
return;
}
const platform = await ctx.model.ExternalPrintPlatform.findByPk(platformId);
if (!platform) {
ctx.status = 400;
ctx.body = { code: 400, message: '外部打单平台不存在' };
return;
}
const exist = await ctx.model.ExternalPrintAccount.findOne({
where: { principal_id: principalId, platform_id: platformId, account },
});
if (exist) {
ctx.status = 400;
ctx.body = { code: 400, message: `该平台下账号 ${account} 已存在` };
return;
}
const item = await ctx.model.ExternalPrintAccount.create({
principal_id: principalId,
platform_id: platformId,
account,
password,
});
ctx.body = { code: 0, message: 'success', data: { id: item.id } };
}
/**
* @summary 更新外部打单账号
* @description 未传入的字段保持原值;password 留空表示不修改密码(接口不回显密码)
* @router put /api/external-print-accounts/{id}
* @apikey
* @request path integer *id 账号主键ID
* @request body updateExternalPrintAccountRequest *body
* @response 200 baseResponse success
*/
async update() {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const item = await this.findAccount(ctx.params.id);
if (!item) {
ctx.status = 404;
ctx.body = { code: 404, message: '打单账号不存在' };
return;
}
const body = ctx.request.body || {};
const patch = {};
if (body.platform_id !== undefined && body.platform_id !== '' && body.platform_id !== null) {
const platformId = Number(body.platform_id);
const platform = await ctx.model.ExternalPrintPlatform.findByPk(platformId);
if (!platform) {
ctx.status = 400;
ctx.body = { code: 400, message: '外部打单平台不存在' };
return;
}
patch.platform_id = platformId;
}
if (body.account !== undefined) {
const account = String(body.account).trim();
if (!account) {
ctx.status = 400;
ctx.body = { code: 400, message: 'account(账号)不能为空' };
return;
}
patch.account = account;
}
if (body.password !== undefined && body.password !== null && String(body.password) !== '') {
patch.password = String(body.password);
}
const platformId = patch.platform_id === undefined ? item.platform_id : patch.platform_id;
const account = patch.account === undefined ? item.account : patch.account;
if (patch.platform_id !== undefined || patch.account !== undefined) {
const exist = await ctx.model.ExternalPrintAccount.findOne({
where: {
principal_id: item.principal_id,
platform_id: platformId,
account,
id: { [Op.ne]: item.id },
},
});
if (exist) {
ctx.status = 400;
ctx.body = { code: 400, message: `该平台下账号 ${account} 已存在` };
return;
}
}
await item.update(patch);
ctx.body = { code: 0, message: 'success', data: { id: item.id } };
}
/**
* @summary 检查外部打单账号登录状态
* @description 用账号已保存的 cookie 访问平台门户,返回是否仍处于登录态;不会触发重新登录
* @router post /api/external-print-accounts/{id}/check
* @apikey
* @request path integer *id 账号主键ID
* @response 200 externalPrintAccountCheckResponse success
*/
async check() {
const { ctx } = this;
const account = await this.findAccount(ctx.params.id, { withPlatform: true });
if (!account) {
ctx.status = 404;
ctx.body = { code: 404, message: '打单账号不存在' };
return;
}
try {
const service = this.createPlatformService(account);
const result = await service.checkSession();
ctx.body = {
code: 0,
message: 'success',
data: {
logged_in: !!result.loggedIn,
message: result.message || '',
url: result.url || '',
nickname: result.nickname || '',
shop_name: result.shopName || '',
},
};
} catch (err) {
ctx.status = 400;
ctx.body = { code: 400, message: err.message };
}
}
/**
* @summary 登录外部打单账号
* @description cookie 有效时直接复用;否则用账号密码登录,成功后把会话 cookie 写回账号表
* @router post /api/external-print-accounts/{id}/login
* @apikey
* @request path integer *id 账号主键ID
* @response 200 externalPrintAccountLoginResponse success
*/
async login() {
const { ctx } = this;
const account = await this.findAccount(ctx.params.id, { withPlatform: true });
if (!account) {
ctx.status = 404;
ctx.body = { code: 404, message: '打单账号不存在' };
return;
}
try {
const service = this.createPlatformService(account);
const result = await service.login();
ctx.body = {
code: 0,
message: 'success',
data: { logged_in: true, reused: !!result.reused, shop_name: result.shopName || '' },
};
} catch (err) {
ctx.status = 400;
ctx.body = { code: 400, message: err.message };
}
}
/**
* @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,
* 避免把 undefined 传给 Sequelize 导致 500。
* @param {number|string} id 账号ID
* @param {Object} [options] withPlatform 为 true 时一并带出平台配置
* @return {Promise<Object|null>} 账号实例
*/
async findAccount(id, options = {}) {
const { ctx } = this;
const principalId = ctx.state.principalId;
if (principalId == null) return null;
const query = { where: { id, principal_id: principalId } };
if (options.withPlatform) {
query.include = [
{
model: ctx.model.ExternalPrintPlatform,
as: 'platform',
attributes: [ 'id', 'code', 'name', 'url', 'fetch_waybill_no' ],
},
];
}
return ctx.model.ExternalPrintAccount.findOne(query);
}
/**
* 按账号所属平台创建服务实例;cookie 变更时写回账号表
* @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 });
}
},
});
}
/**
* @summary 删除外部打单账号
* @description 物理删除账号
* @router delete /api/external-print-accounts/{id}
* @apikey
* @request path integer *id 账号主键ID
* @response 200 baseResponse success
*/
async destroy() {
const { ctx } = this;
const item = await this.findAccount(ctx.params.id);
if (!item) {
ctx.status = 404;
ctx.body = { code: 404, message: '打单账号不存在' };
return;
}
await item.destroy();
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
}
}
module.exports = ExternalPrintAccountController;