- 新增 shopAreaSync:按账号拉一次商家列表(同账号多店铺共享,PageSize=200 翻页),
把最新商家结构(FxUserId、分区声明 DbAreas)写回 shops.external_data;
商家已不在合作列表时自动把店铺置为禁用,并写明原因
- 手动刷新入口:POST /api/shops/{id}/refresh-area(货主权限)、
POST /api/external-print-accounts/{id}/refresh-shops-area(集团权限)
- 新增定时任务 refreshExternalShopAreas:每小时巡检,按账号 6 小时刷新一次
(DGJ_AREA_REFRESH_HOURS 可调),自动禁用店铺后不再参与自动拉单与一键拉单
- 新增 shopOrderGuard:店铺禁用立即作废该店铺待审核订单
(void_reason 前缀「店铺已禁用,暂停处理」),重新启用时只恢复因此暂停的订单;
禁用店铺再拉单直接拒绝,避免又拉回待审核单
- externalPrintOrder 待审核单核对改用 LogicOrderId 批量回读(50 单/批,最多 300 单)
- orderStatus.restore 支持显式 principalId,供无登录态的系统任务调用
- 前端:店铺列表新增「所在区」列与行内/详情「刷新所在区」按钮,
系统自动禁用的店铺状态带原因提示,启停与刷新后提示作废/恢复了多少订单
- 文档:新增 §4.2.2「所在区」刷新、§4.2.3 店铺禁用/启用与待审核订单
(原 LastWaybillCode 小节顺延为 §4.2.4,WMS 对接文档引用同步)
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
243 lines
9.2 KiB
JavaScript
243 lines
9.2 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
|
||
/** 单页拉取的商家数量(店管家商家列表上限 200) */
|
||
const MERCHANT_PAGE_SIZE = 200;
|
||
|
||
/** 最多翻页次数:防止平台返回异常总数时死循环 */
|
||
const MAX_MERCHANT_PAGES = 50;
|
||
|
||
/** 店铺类型:外部打单平台商家 */
|
||
const SHOP_TYPE_EXTERNAL = 2;
|
||
|
||
/** 平台登录态失效的报错特征(各分区接口统一返回「登录信息过期」/token is invalid) */
|
||
const SESSION_EXPIRED_RE = /登录信息过期|登录已失效|token is invalid|未登录|缺少 token/i;
|
||
|
||
/** 商家已不在合作列表时写入店铺 extra 的原因(前端据此提示) */
|
||
const AUTO_DISABLED_REASON = '店铺已不在打单平台合作列表(可能已解绑或停用),系统已自动禁用';
|
||
|
||
/**
|
||
* 店铺「所在区」同步服务
|
||
*
|
||
* 店管家把每个商家挂在若干个分区(`DbAreas[]`,页面上叫「所在区」)下,拉单要靠这份声明
|
||
* 决定查哪些分区库。商家可能被平台迁移分区或解绑,声明过期会让拉单漏单/报错,因此需要定期刷新:
|
||
* 1. 同一账号下所有店铺共享一份商家列表,一次拉取只请求平台一次(定时任务里按账号去重);
|
||
* 2. 拉到的商家原样写回 shops.external_data(FxUserId、DbAreas 等拉单必需字段);
|
||
* 3. 商家已不在合作列表(解绑/删除/停用)时把店铺自动禁用,之后自动拉单与一键拉单都会跳过
|
||
* (两条链路都只取 status=1 的店铺),需人工把状态改回启用才会恢复。
|
||
*/
|
||
class ShopAreaSyncService extends Service {
|
||
/**
|
||
* 刷新某账号下全部店铺的「所在区」等信息
|
||
* @param {Object} account 账号实例(需 include platform)
|
||
* @param {Object} [options] 选项
|
||
* @param {boolean} [options.disableMissing] 商家已不在合作列表时是否自动禁用店铺(默认 true)
|
||
* @return {Promise<Object>} 刷新结果统计
|
||
*/
|
||
async refreshAccount(account, options = {}) {
|
||
const { ctx } = this;
|
||
const disableMissing = options.disableMissing !== false;
|
||
|
||
const platformService = ctx.service.externalPrintOrder.createPlatformService(account);
|
||
const merchants = await this.fetchMerchants(platformService);
|
||
|
||
const merchantMap = new Map();
|
||
for (const item of merchants) {
|
||
const externalId = String((item && item.external_id) || '').trim();
|
||
if (externalId) merchantMap.set(externalId, item);
|
||
}
|
||
|
||
const shops = await ctx.model.Shop.findAll({
|
||
where: { external_print_account_id: account.id, type: SHOP_TYPE_EXTERNAL },
|
||
order: [[ 'id', 'ASC' ]],
|
||
});
|
||
|
||
const now = new Date();
|
||
const result = {
|
||
account_id: Number(account.id),
|
||
merchants: merchants.length,
|
||
shops: shops.length,
|
||
updated: 0,
|
||
disabled: [],
|
||
missing: [],
|
||
restored: [],
|
||
voided: 0,
|
||
};
|
||
|
||
for (const shop of shops) {
|
||
const externalId = this.resolveExternalId(shop);
|
||
const merchant = externalId ? merchantMap.get(externalId) : null;
|
||
if (merchant) {
|
||
await this.applyMerchant(shop, merchant, now, result);
|
||
} else {
|
||
await this.markMissing(shop, now, { disableMissing, result });
|
||
}
|
||
}
|
||
|
||
if (result.disabled.length) {
|
||
ctx.logger.warn(
|
||
'[shopAreaSync] 账号 %s 有 %d 个店铺已不在平台合作列表,自动禁用:%s',
|
||
account.id,
|
||
result.disabled.length,
|
||
result.disabled.map(item => `${item.id}(${item.name})`).join('、')
|
||
);
|
||
}
|
||
if (result.restored.length) {
|
||
ctx.logger.info(
|
||
'[shopAreaSync] 账号 %s 有 %d 个店铺重新出现在平台合作列表(保持禁用,等待人工启用):%s',
|
||
account.id,
|
||
result.restored.length,
|
||
result.restored.map(item => `${item.id}(${item.name})`).join('、')
|
||
);
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
/**
|
||
* 拉取账号下全部商家(分页汇总)
|
||
* @param {Object} platformService 平台服务实例
|
||
* @return {Promise<Array>} 商家列表(统一结构)
|
||
*/
|
||
async fetchMerchants(platformService) {
|
||
try {
|
||
return await this.pullAllMerchants(platformService);
|
||
} catch (err) {
|
||
// 会话过期时重新登录一次再拉,避免定时任务因为登录态失效整天刷不到分区
|
||
const expired = SESSION_EXPIRED_RE.test(String((err && err.message) || ''));
|
||
if (!expired || typeof platformService.loginByPassword !== 'function') throw err;
|
||
this.ctx.logger.warn('[shopAreaSync] 刷新店铺所在区时登录态失效,重新登录后重试:%s', err.message);
|
||
await platformService.loginByPassword();
|
||
return await this.pullAllMerchants(platformService);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 逐页拉取商家列表
|
||
* @param {Object} platformService 平台服务实例
|
||
* @return {Promise<Array>} 商家列表
|
||
*/
|
||
async pullAllMerchants(platformService) {
|
||
const all = [];
|
||
for (let pageIndex = 1; pageIndex <= MAX_MERCHANT_PAGES; pageIndex++) {
|
||
const page = await platformService.listShops({ pageIndex, pageSize: MERCHANT_PAGE_SIZE });
|
||
const list = Array.isArray(page && page.list) ? page.list : [];
|
||
all.push(...list);
|
||
const total = Number(page && page.total) || all.length;
|
||
if (!list.length || all.length >= total) break;
|
||
}
|
||
return all;
|
||
}
|
||
|
||
/**
|
||
* 店铺在平台的商家ID:优先取 external_data.Id,缺失时按编码(平台-账号-商家ID)兜底解析
|
||
* @param {Object} shop 店铺实例
|
||
* @return {string} 商家ID,取不到返回空串
|
||
*/
|
||
resolveExternalId(shop) {
|
||
const data = shop.external_data || {};
|
||
if (data.Id != null && data.Id !== '') return String(data.Id);
|
||
const code = String(shop.code || '');
|
||
const index = code.lastIndexOf('-');
|
||
return index >= 0 ? code.slice(index + 1) : '';
|
||
}
|
||
|
||
/**
|
||
* 商家仍在合作列表:写回最新商家结构(含分区声明),并清掉「已解绑」标记
|
||
* @param {Object} shop 店铺实例
|
||
* @param {Object} merchant 平台商家(统一结构,raw 为原始结构)
|
||
* @param {Date} now 本次刷新时间
|
||
* @param {Object} result 累计统计
|
||
* @return {Promise<void>} 无返回值
|
||
*/
|
||
async applyMerchant(shop, merchant, now, result) {
|
||
const nextExternalData = merchant.raw || merchant;
|
||
const changed = JSON.stringify(shop.external_data || {}) !== JSON.stringify(nextExternalData);
|
||
const extra = { ...(shop.extra || {}) };
|
||
|
||
if (changed) shop.external_data = nextExternalData;
|
||
extra.area_synced_at = now;
|
||
if (extra.area_missing) delete extra.area_missing;
|
||
|
||
if (extra.auto_disabled) {
|
||
// 商家回到合作列表:只记录提示,是否启用由人工决定(自动启用可能与人工停用的意图冲突)
|
||
delete extra.auto_disabled;
|
||
extra.area_restored_at = now;
|
||
if (Number(shop.status) !== 1) {
|
||
shop.last_order_sync_msg = '店铺已重新出现在打单平台合作列表,可手动启用后继续拉单';
|
||
}
|
||
result.restored.push({ id: Number(shop.id), code: shop.code, name: shop.name });
|
||
}
|
||
|
||
shop.extra = extra;
|
||
await shop.save();
|
||
if (changed) result.updated++;
|
||
}
|
||
|
||
/**
|
||
* 商家已不在合作列表:标记 + (启用中时)自动禁用
|
||
* @param {Object} shop 店铺实例
|
||
* @param {Date} now 本次刷新时间
|
||
* @param {Object} params 参数
|
||
* @param {boolean} params.disableMissing 是否自动禁用
|
||
* @param {Object} params.result 累计统计
|
||
* @return {Promise<void>} 无返回值
|
||
*/
|
||
async markMissing(shop, now, { disableMissing, result }) {
|
||
const { ctx } = this;
|
||
const extra = { ...(shop.extra || {}) };
|
||
const item = { id: Number(shop.id), code: shop.code, name: shop.name };
|
||
|
||
extra.area_synced_at = now;
|
||
extra.area_missing = true;
|
||
result.missing.push(item);
|
||
|
||
const justDisabled = disableMissing && Number(shop.status) === 1;
|
||
if (justDisabled) {
|
||
shop.status = 0;
|
||
extra.auto_disabled = { at: now, reason: AUTO_DISABLED_REASON };
|
||
}
|
||
|
||
shop.extra = extra;
|
||
await shop.save();
|
||
if (!justDisabled) return;
|
||
|
||
// 禁用后无法取号:立即作废该店铺的待审核订单,避免继续审核/取号时报错(启用后自动恢复)
|
||
let voided = 0;
|
||
try {
|
||
const guarded = await ctx.service.shopOrderGuard.voidPendingOrders(shop);
|
||
voided = guarded.count;
|
||
} catch (err) {
|
||
ctx.logger.warn('[shopAreaSync] 店铺 %s 作废待审核订单失败:%s', shop.id, err.message);
|
||
}
|
||
result.voided += voided;
|
||
result.disabled.push(item);
|
||
|
||
await shop.update({
|
||
last_order_sync_msg:
|
||
`${AUTO_DISABLED_REASON};改回启用后会继续拉单` +
|
||
(voided ? `(已作废待审核订单 ${voided} 单,启用后自动恢复)` : ''),
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 账号下店铺最近一次刷新「所在区」的时间(同账号一次拉取会写全部店铺,取最大值)
|
||
* @param {Array} shops 账号下的店铺实例
|
||
* @return {Date|null} 最近刷新时间
|
||
*/
|
||
lastSyncedAt(shops) {
|
||
let latest = null;
|
||
for (const shop of shops) {
|
||
const at = shop.extra && shop.extra.area_synced_at;
|
||
if (!at) return null;
|
||
const time = new Date(at).getTime();
|
||
if (Number.isNaN(time)) return null;
|
||
if (!latest || time > latest.getTime()) latest = new Date(time);
|
||
}
|
||
return latest;
|
||
}
|
||
}
|
||
|
||
module.exports = ShopAreaSyncService;
|