This commit is contained in:
liufumingren 2026-05-25 17:08:56 +08:00
parent 150e2977d4
commit dc4894cb6d
74 changed files with 12644 additions and 732 deletions

View File

@ -5,6 +5,110 @@ const {
const { toSuccess, toFailure } = require('../lib/api_response');
class HomeController extends Controller {
/**
* 规范化平台编码。
* @param {*} platformCode 平台编码原始值。
* @return {string} 标准化后的平台编码。
*/
normalizePlatformCode(platformCode) {
return String(platformCode || '').trim().toUpperCase();
}
/**
* 判断店铺记录的平台编码是否与目标平台一致。
* @param {object|null|undefined} shop 店铺记录。
* @param {string} platformCode 目标平台编码。
* @return {boolean} 是否一致。
*/
isMatchedShopPlatform(shop, platformCode) {
return this.normalizePlatformCode(shop && shop.platform_code) === this.normalizePlatformCode(platformCode);
}
/**
* 解析绑定授权回调 state 并提取业务编码。
*
* 仅支持以 bind_ 开头的 state,去掉前缀后的剩余整段即业务 code。
*
* @param {string} state 授权回调中的 state 原始值。
* @return {string} 解析得到的业务 code,无法解析时返回空字符串。
*/
parsePlatformOauthBindBusinessCode(state) {
const bindStatePrefix = 'bind_';
if (typeof state !== 'string') {
return '';
}
const normalizedState = state.trim();
if (!normalizedState.startsWith(bindStatePrefix)) {
return '';
}
return normalizedState.slice(bindStatePrefix.length).trim();
}
/**
* 渲染平台绑定授权的简易结果页。
*
* 成功场景仅展示简洁成功文案;失败场景仅展示简洁失败文案并提示重新授权。
*
* @param {boolean} isSuccess 是否成功。
* @return {Promise<void>} 无返回值。
*/
async renderPlatformOauthBindResultPage(isSuccess) {
const title = isSuccess ? '绑定成功' : '绑定失败';
const message = isSuccess ? '绑定成功' : '绑定失败,请重新授权';
const color = isSuccess ? '#2f7d32' : '#c62828';
const html = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${title}</title>
<style>
body {
margin: 0;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: #f7f8fa;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}
.card {
width: min(90vw, 360px);
padding: 28px 20px;
border-radius: 12px;
background: #fff;
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.08);
text-align: center;
}
.title {
margin: 0;
font-size: 22px;
color: ${color};
}
.message {
margin: 12px 0 0;
font-size: 15px;
color: #4b5563;
}
</style>
</head>
<body>
<main class="card">
<h1 class="title">${title}</h1>
<p class="message">${message}</p>
</main>
</body>
</html>`;
this.ctx.status = isSuccess ? 200 : 400;
this.ctx.type = 'text/html; charset=utf-8';
this.ctx.body = html;
}
/**
* 解析平台授权回调 state,提取平台编码与授权随机码。
* @param {string} state 回调原始 state。
@ -52,7 +156,7 @@ class HomeController extends Controller {
const hasShop = Boolean(shop);
const isProcessed = hasShop ? Number(shop.status) === 1 : null;
const isPlatformMatched = hasShop && parsedState
? String(shop.platform_code || '') === platformCode
? this.isMatchedShopPlatform(shop, platformCode)
: null;
let resultLevel = 'error';
let resultText = errorMessage || '授权回调校验失败';
@ -92,6 +196,62 @@ class HomeController extends Controller {
};
}
/**
* 将淘宝授权接口返回的奇门响应归一化为可读取的对象。
* @param {object|Array|null|undefined} xmlArray 奇门返回中的 xmlArray 字段。
* @return {object|null} 归一化后的响应对象,无法识别时返回 null。
*/
normalizeTbOauthQimenResponse(xmlArray) {
if (!xmlArray || typeof xmlArray !== 'object' || Array.isArray(xmlArray)) {
return null;
}
const response = xmlArray.response && typeof xmlArray.response === 'object'
? xmlArray.response
: xmlArray;
if (response.top_auth_token_create_response && typeof response.top_auth_token_create_response === 'object') {
return response.top_auth_token_create_response;
}
return response;
}
/**
* 从淘宝授权接口的奇门返回中提取 access_token。
* @param {object|Array|null|undefined} xmlArray 奇门返回中的 xmlArray 字段。
* @return {string} 提取出的 access_token,失败时返回空字符串。
*/
extractTbOauthAccessToken(xmlArray) {
if (Array.isArray(xmlArray)) {
const tokenCreateResponse = xmlArray.find(item => item && typeof item === 'object' && item.name === 'top_auth_token_create_response');
const tokenCreateChildren = Array.isArray(tokenCreateResponse && tokenCreateResponse.children)
? tokenCreateResponse.children
: [];
const tokenCreateResult = tokenCreateChildren.find(item => item && typeof item === 'object' && item.name === 'result');
const resultChildren = Array.isArray(tokenCreateResult && tokenCreateResult.children)
? tokenCreateResult.children
: [];
const accessTokenItem = resultChildren.find(item => item && typeof item === 'object' && item.name === 'access_token');
return accessTokenItem && accessTokenItem.value !== undefined && accessTokenItem.value !== null
? String(accessTokenItem.value).trim()
: '';
}
const response = this.normalizeTbOauthQimenResponse(xmlArray);
const result = response && response.result && typeof response.result === 'object'
? response.result
: null;
const accessTokenValue = result && result.access_token !== undefined && result.access_token !== null
? result.access_token
: response && response.access_token !== undefined && response.access_token !== null
? response.access_token
: '';
return accessTokenValue ? String(accessTokenValue).trim() : '';
}
async testSendData() {
await this.ctx.service.systems.print.index.test();
this.ctx.body = 'ok';
@ -154,6 +314,67 @@ class HomeController extends Controller {
}
}
/**
* 使用授权码请求菜鸟授权结果,并按淘宝 OAuth 协议解析返回值。
* @param {string} code 平台回调返回的授权码。
* @return {Promise<{success: boolean, message?: string, result: object|null}>} 请求处理结果。
*/
async cainiao(code) {
const qimenConfig = this.app.config.qimen || {};
const redirectUri = 'http://39.100.57.68/';
const requestPayload = {
code,
grant_type: 'authorization_code',
client_id: qimenConfig.appKey || '',
client_secret: qimenConfig.security || '',
redirect_uri: redirectUri,
};
const formBody = new URLSearchParams(requestPayload).toString();
try {
const result = await this.ctx.curl('https://oauth.taobao.com/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
dataType: 'json',
content: formBody,
});
console.log(result);
const responseData = result && result.data ? result.data : null;
const hasTaobaoStandardError = !!(
responseData
&& (responseData.error !== undefined || responseData.error_description !== undefined)
);
if (responseData && (responseData.error_response || hasTaobaoStandardError)) {
const errorMessage = responseData.error_response && responseData.error_response.error_msg
? responseData.error_response.error_msg
: responseData.error_description || responseData.error || '未知错误';
return {
success: false,
message: `菜鸟授权失败:${errorMessage}`,
result,
};
}
return {
success: true,
result,
};
} catch (error) {
this.ctx.logger.error('[platform-oauth][CAINIAO] oauth/token 请求异常: %s', error);
return {
success: false,
message: `菜鸟授权请求异常:${error.message}`,
result: null,
};
}
}
/**
* 构建拼多多授权店铺回写字段。
* @param {object|null|undefined} oauthData 拼多多授权返回数据。
@ -187,29 +408,81 @@ class HomeController extends Controller {
return updatePayload;
}
/**
* 安全解码淘宝店铺昵称,解码失败时保留原值。
* @param {string|null|undefined} taobaoUserNick 淘宝返回的店铺昵称。
* @return {string|null|undefined} 解码后的店铺昵称,失败时返回原值。
*/
decodeTbShopName(taobaoUserNick) {
if (typeof taobaoUserNick !== 'string') {
return taobaoUserNick;
}
try {
return decodeURIComponent(taobaoUserNick);
} catch (error) {
return taobaoUserNick;
}
}
/**
* 构建菜鸟授权店铺回写字段。
* @param {object|null|undefined} oauthData 菜鸟授权返回数据,字段仍遵循淘宝 OAuth 协议。
* @return {object} 可直接用于店铺模型回写的字段对象。
*/
buildCainiaoOauthShopUpdatePayload(oauthData) {
const toDateFromUnixMilliseconds = value => {
const milliseconds = Number(value);
if (!Number.isFinite(milliseconds) || milliseconds <= 0) {
return null;
}
return new Date(milliseconds);
};
const updatePayload = {
owner_id: oauthData && oauthData.taobao_user_id !== undefined ? oauthData.taobao_user_id : null,
access_token: oauthData && oauthData.access_token !== undefined ? oauthData.access_token : null,
refresh_token: oauthData && oauthData.refresh_token !== undefined ? oauthData.refresh_token : null,
token_expires_at: toDateFromUnixMilliseconds(oauthData && oauthData.expire_time),
refresh_token_expires_at: toDateFromUnixMilliseconds(oauthData && oauthData.refresh_token_valid_time),
auth_expire_at: toDateFromUnixMilliseconds(oauthData && oauthData.expire_time),
scope: oauthData && oauthData.scope !== undefined ? oauthData.scope : null,
status: 1,
};
if (oauthData && oauthData.taobao_user_nick !== undefined) {
updatePayload.shop_name = this.decodeTbShopName(oauthData.taobao_user_nick);
}
return updatePayload;
}
/**
* 按仓库、平台与授权标识查找已授权的旧店铺记录。
* @param {import('sequelize').Model} shop 当前预申请店铺记录。
* @param {object|null|undefined} oauthData 拼多多授权返回数据。
* @param {string|number|null|undefined} ownerId 平台主体标识。
* @param {string|null|undefined} shopName 店铺名称。
* @param {import('sequelize').Transaction} transaction 当前事务对象。
* @return {Promise<import('sequelize').Model|null>} 命中的已授权店铺记录。
*/
async findAuthorizedPddOauthShop(shop, oauthData, transaction) {
async findAuthorizedOauthShop(shop, ownerId, shopName, transaction) {
const { Op } = this.app.Sequelize;
const ownerId = oauthData && oauthData.owner_id !== undefined && oauthData.owner_id !== null
? String(oauthData.owner_id).trim()
const normalizedOwnerId = ownerId !== undefined && ownerId !== null
? String(ownerId).trim()
: '';
const ownerName = oauthData && oauthData.owner_name !== undefined && oauthData.owner_name !== null
? String(oauthData.owner_name).trim()
const normalizedShopName = shopName !== undefined && shopName !== null
? String(shopName).trim()
: '';
const matchConditions = [];
if (ownerId) {
matchConditions.push({ owner_id: oauthData.owner_id });
if (normalizedOwnerId) {
matchConditions.push({ owner_id: ownerId });
}
if (ownerName) {
matchConditions.push({ shop_name: ownerName });
if (normalizedShopName) {
matchConditions.push({ shop_name: shopName });
}
if (!matchConditions.length) {
@ -230,6 +503,24 @@ class HomeController extends Controller {
});
}
/**
* 按仓库、平台与授权标识查找已授权的旧店铺记录。
* @param {import('sequelize').Model} shop 当前预申请店铺记录。
* @param {object|null|undefined} oauthData 拼多多授权返回数据。
* @param {import('sequelize').Transaction} transaction 当前事务对象。
* @return {Promise<import('sequelize').Model|null>} 命中的已授权店铺记录。
*/
async findAuthorizedPddOauthShop(shop, oauthData, transaction) {
const ownerId = oauthData && oauthData.owner_id !== undefined && oauthData.owner_id !== null
? String(oauthData.owner_id).trim()
: '';
const ownerName = oauthData && oauthData.owner_name !== undefined && oauthData.owner_name !== null
? String(oauthData.owner_name).trim()
: '';
return await this.findAuthorizedOauthShop(shop, ownerId ? oauthData.owner_id : null, ownerName, transaction);
}
/**
* 将拼多多授权成功后的关键字段回写到店铺记录。
* @param {import('sequelize').Model} shop 店铺模型实例。
@ -274,6 +565,55 @@ class HomeController extends Controller {
});
}
/**
* 将菜鸟授权成功后的关键字段回写到店铺记录。
* @param {import('sequelize').Model} shop 店铺模型实例。
* @param {object|null|undefined} oauthData 菜鸟授权返回数据,字段仍遵循淘宝 OAuth 协议。
* @return {Promise<import('sequelize').Model>} 已保存的店铺模型实例。
*/
async updateCainiaoOauthShop(shop, oauthData) {
const updatePayload = this.buildCainiaoOauthShopUpdatePayload(oauthData);
const saveFields = [
'owner_id',
'shop_name',
'access_token',
'refresh_token',
'token_expires_at',
'refresh_token_expires_at',
'auth_expire_at',
'scope',
'status',
];
return await this.ctx.model.transaction(async transaction => {
const authorizedShop = await this.findAuthorizedOauthShop(
shop,
updatePayload.owner_id,
updatePayload.shop_name,
transaction
);
if (authorizedShop) {
authorizedShop.set(updatePayload);
await authorizedShop.save({
fields: saveFields,
transaction,
});
await shop.destroy({ transaction });
return authorizedShop;
}
shop.set(updatePayload);
await shop.save({
fields: saveFields,
transaction,
});
return shop;
});
}
/**
* 处理平台授权回调请求,解析 query 中的 code 与 state。
* @return {Promise<void>} 无返回值。
@ -313,7 +653,7 @@ class HomeController extends Controller {
},
});
if (shop && String(shop.platform_code || '') === parsedState.platformCode) {
if (shop && this.isMatchedShopPlatform(shop, parsedState.platformCode)) {
const oauthData = pddResult.result && pddResult.result.data
? pddResult.result.data
: pddResult.result;
@ -322,8 +662,35 @@ class HomeController extends Controller {
}
}
break;
case 'CAINIAO':
{
const cainiaoOauthResult = await this.cainiao(code);
if (!cainiaoOauthResult || cainiaoOauthResult.success === false) {
errorMessage = cainiaoOauthResult && cainiaoOauthResult.message
? cainiaoOauthResult.message
: '菜鸟授权失败:未知错误';
break;
}
shop = await ctx.model.Shop.findOne({
where: {
auth_random_code: parsedState.authRandomCode,
},
});
if (shop && this.isMatchedShopPlatform(shop, parsedState.platformCode)) {
const oauthData = cainiaoOauthResult.result && cainiaoOauthResult.result.data
? cainiaoOauthResult.result.data
: cainiaoOauthResult.result;
shop = await this.updateCainiaoOauthShop(shop, oauthData);
}
break;
}
default:
errorMessage = `暂未接入该平台授权回调处理`;
errorMessage = '暂未接入该平台授权回调处理';
break;
}
}
@ -339,6 +706,174 @@ class HomeController extends Controller {
ctx.status = viewData.resultLevel === 'error' ? 400 : 200;
await ctx.render('platform_oauth_callback.html', viewData);
}
/**
* 处理拼多多绑定授权回调。
*
* 流程:校验 code/state -> 解析业务 code -> 复用 pdd(code) 换取 access_token
* -> 写入缓存 bind_pdd_code:{业务code} -> 返回简易成功/失败页。
*
* @return {Promise<void>} 无返回值。
*/
async platformOauthBind() {
const { service } = this.ctx;
const code = typeof this.ctx.query.code === 'string' ? this.ctx.query.code.trim() : '';
const state = typeof this.ctx.query.state === 'string' ? this.ctx.query.state.trim() : '';
const businessCode = this.parsePlatformOauthBindBusinessCode(state);
const failCacheKey = businessCode ? `bind_pdd_code_fail:${businessCode}` : '';
const markBindFailed = async reason => {
if (!businessCode || !failCacheKey) {
return;
}
try {
await this.app.setCacheAsync(failCacheKey, {
status: 'failed',
message: reason || '绑定失败,请重新授权',
});
await service.systems.platform.publishPlatformOauthBindEvent(businessCode, {
status: 'failed',
message: reason || '绑定失败,请重新授权',
});
} catch (error) {
this.ctx.logger.error('[platform-oauth-bind] 失败标记写入异常: %s', error && error.message ? error.message : error);
}
};
if (!code || !state) {
await markBindFailed('绑定失败,请重新授权');
await this.renderPlatformOauthBindResultPage(false);
return;
}
if (!businessCode) {
await this.renderPlatformOauthBindResultPage(false);
return;
}
const pddResult = await this.pdd(code);
if (!pddResult || pddResult.success === false) {
await markBindFailed('绑定失败,请重新授权');
await this.renderPlatformOauthBindResultPage(false);
return;
}
const oauthData = pddResult.result && pddResult.result.data
? pddResult.result.data
: pddResult.result;
const accessToken = oauthData && typeof oauthData.access_token === 'string'
? oauthData.access_token.trim()
: '';
if (!accessToken) {
await markBindFailed('绑定失败,请重新授权');
await this.renderPlatformOauthBindResultPage(false);
return;
}
try {
await this.app.setCacheAsync(`bind_pdd_code:${businessCode}`, accessToken);
if (typeof this.app.delCacheAsync === 'function') {
await this.app.delCacheAsync(failCacheKey);
} else {
await this.app.setCacheAsync(failCacheKey, null, 1);
}
await service.systems.platform.publishPlatformOauthBindEvent(businessCode, {
status: 'success',
access_token: accessToken,
});
} catch (error) {
this.ctx.logger.error('[platform-oauth-bind] 缓存写入失败: %s', error && error.message ? error.message : error);
await markBindFailed('绑定失败,请重新授权');
await this.renderPlatformOauthBindResultPage(false);
return;
}
await this.renderPlatformOauthBindResultPage(true);
}
/**
* 查询拼多多绑定授权码的轮询状态。
*
* 根据 code 先查成功缓存,再查失败标记,最终返回 success / failed / pending 三态。
*
* @return {Promise<void>} 无返回值。
*/
async queryPddCode() {
const code = this.ctx.params && typeof this.ctx.params.code === 'string'
? this.ctx.params.code.trim()
: '';
if (!code) {
this.ctx.status = 400;
this.ctx.body = toFailure({
httpStatus: 400,
message: 'code不能为空',
data: {
status: 'failed',
message: 'code不能为空',
},
});
return;
}
const successCacheKey = `bind_pdd_code:${code}`;
const failCacheKey = `bind_pdd_code_fail:${code}`;
let accessToken = '';
try {
const cachedToken = await this.app.getCacheAsync(successCacheKey);
accessToken = typeof cachedToken === 'string' ? cachedToken.trim() : '';
} catch (error) {
this.ctx.logger.error('[query-pdd-code] 查询 access_token 缓存异常: %s', error && error.message ? error.message : error);
}
if (accessToken) {
this.ctx.body = toSuccess({
status: 'success',
access_token: accessToken,
});
return;
}
let failedCacheValue = null;
try {
failedCacheValue = await this.app.getCacheAsync(failCacheKey);
} catch (error) {
this.ctx.logger.error('[query-pdd-code] 查询失败标记缓存异常: %s', error && error.message ? error.message : error);
}
if (failedCacheValue !== null && failedCacheValue !== undefined && failedCacheValue !== '') {
const failedMessage = '绑定失败,请重新授权';
this.ctx.status = 200;
this.ctx.body = toFailure({
httpStatus: 200,
message: failedMessage,
data: {
status: 'failed',
message: failedMessage,
},
});
return;
}
const failedMessage = '绑定失败,请重新授权';
this.ctx.status = 200;
this.ctx.body = toFailure({
httpStatus: 200,
message: failedMessage,
data: {
status: 'failed',
message: failedMessage,
},
});
}
/**
* 处理奇门统一入口请求,完成参数校验、XML 解析、仓库编码提取与方法分发。
* @return {Promise<void>} 无返回值。

View File

@ -147,4 +147,4 @@ class PddClient {
}
}
module.exports = PddClient;
module.exports = PddClient;

View File

@ -114,7 +114,8 @@ function sign(params = {}, clientSecret) {
return {
signText,
sortedPairs,
sign: crypto.createHash('md5').update(signText, 'utf8').digest('hex').toUpperCase(),
sign: crypto.createHash('md5').update(signText, 'utf8').digest('hex')
.toUpperCase(),
};
}
@ -185,4 +186,4 @@ module.exports = {
normalizeValue,
sign,
stableStringify,
};
};

View File

@ -34,12 +34,17 @@ class PoloApiClient {
if (!config || !config.interface_url) {
throw new Error('[PoloApiClient.request] 未提供有效的 config,无法发送请求');
}
const configWithToken = { ...config, token: token || config.token };
const configWithToken = config;
if (token) {
configWithToken.token = token;
}
console.log('configWithToken', configWithToken);
const signMap = this._buildSignMap(configWithToken, method, config.platid, bizcontent);
console.log('signMap', signMap);
const signText = this._getSignText(signMap, config.app_secret);
const sign = this._md5(signText.toLowerCase());
const sign = this._md5(signText);
const formBody = this._encodeForm({ ...signMap, sign });
console.log('查询菠萝派平台数据,接口URL:', config.interface_url, '入参bizcontent:', JSON.stringify(bizcontent));
const response = await this.ctx.curl(String(config.interface_url || ''), {
method: 'POST',
headers: {
@ -48,6 +53,7 @@ class PoloApiClient {
},
content: formBody,
});
console.log('formBody', formBody);
let result;
if (Buffer.isBuffer(response.data)) {
// 如果是 Buffer,转字符串再解析
@ -84,7 +90,7 @@ class PoloApiClient {
const configWithToken = { ...config, token: token || config.token };
const signMap = this._buildSignMap(configWithToken, method, config.platid, bizcontent);
const signText = this._getSignText(signMap, config.app_secret);
const sign = this._md5(signText.toLowerCase());
const sign = this._md5(signText);
const formBody = this._encodeForm({ ...signMap, sign });
const requestUrl = `http://39.98.7.126/OpenApi/Do?${formBody}`;
@ -122,24 +128,26 @@ class PoloApiClient {
const normalizedBizcontent = bizcontent && typeof bizcontent === 'object'
? JSON.stringify(bizcontent)
: (bizcontent === undefined || bizcontent === null ? '' : bizcontent);
return {
const res = {
method,
appkey: config.appkey,
token: config.token,
platid,
version: config.version,
contenttype: this.contenttype,
bizcontent: normalizedBizcontent,
timestamp: this._formatDate(new Date()),
};
if (config.token) {
res.token = config.token;
}
return res;
}
/**
* 生成签名原文 = secret + key1value1 + key2value2 ... + secret(按 key 字母序)。
* @param {object} signMap 待签名参数映射。
* @param {string} secret 签名密钥。
* @return {string} 签名原文字符串。
* @return {string} 转小写后的签名原文字符串。
*/
_getSignText(signMap, secret) {
let sb = '' + secret;
@ -147,7 +155,7 @@ class PoloApiClient {
sb += key + signMap[key];
});
sb += secret;
return sb;
return sb.toLowerCase();
}
/**

View File

@ -249,16 +249,16 @@ function parseItems(rawItems) {
const parsed = JSON.parse(text);
return parseItems(parsed);
} catch (error) {
function isNoiseQuantityOnlyText(value) {
const isNoiseQuantityOnlyText = value => {
const sample = String(value || '').trim();
if (!sample) {
return true;
}
return /^(?:\[?\s*\d+(?:\.\d+)?\s*\]?|【\s*\d+(?:\.\d+)?\s*】)(?:\s+0+)?$/.test(sample);
}
};
function parseLooseItemText(rawText) {
const parseLooseItemText = rawText => {
const normalizedText = String(rawText || '').replace(/[;;]+$/g, '').trim();
if (!normalizedText || isNoiseQuantityOnlyText(normalizedText)) {
return null;
@ -306,7 +306,7 @@ function parseItems(rawItems) {
quantity,
raw_text: normalizedText,
};
}
};
const itemTextList = text
.split(/\||\r\n|\n|\r/)
@ -453,9 +453,14 @@ function resolveItemQuantity(item) {
* 根据货主配置构建面单自定义区商品信息。
* @param {Array<Object>} items 商品列表。
* @param {Object} policyConfig 策略配置。
* @param {string} lineBreak 换行符。
* @param options
* @return {string} 自定义区文本。
* @param {Object} options 附加选项。
* @param {string} [options.waveNo] 波次号。
* @param {number} [options.wave_total_orders] 波次总订单数。
* @param {number} [options.wave_index] 当前波次内序号。
* @param {number} [options.platforms_index] 平台内序号。
* @param {string} [options.expressInterfaceName] 快递渠道显示名。
* @param {number} [options.fallbackTotalQty] 兜底商品总数。
* @return {Array<string>} 自定义区文本行数组。
*/
function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = {}) {
const safeItems = Array.isArray(items) ? items : [];
@ -638,6 +643,359 @@ function resolveKuaishouCustomDataTemplateURL(templateSample) {
return '';
}
/**
* 从菜鸟模板样例中提取自定义区模板地址。
*
* 优先扫描 template_sample.task.documents,其次扫描 template_sample.documents 和 template_sample.taskList,
* 找到第一个 data.CustomControl 字段对应的内容对象后返回其 templateURL。
*
* @param {Object} templateSample 模板样例对象。
* @return {string} 自定义区模板地址。
*/
function resolveCainiaoCustomControlTemplateURL(templateSample) {
const sample = isPlainObject(templateSample) ? templateSample : {};
const documentGroups = [
sample.task && sample.task.documents,
sample.documents,
sample.taskList,
];
for (const documents of documentGroups) {
if (!Array.isArray(documents) || documents.length === 0) {
continue;
}
for (const document of documents) {
if (!isPlainObject(document) || !Array.isArray(document.contents)) {
continue;
}
for (const content of document.contents) {
if (!isPlainObject(content) || !isPlainObject(content.data)) {
continue;
}
if (!Object.prototype.hasOwnProperty.call(content.data, 'CustomControl')) {
continue;
}
if (Object.prototype.hasOwnProperty.call(content, 'templateURL')) {
return toTrimmedString(content.templateURL);
}
}
}
}
return '';
}
/**
* 深拷贝普通对象/数组,避免直接复用上游引用。
*
* @param {any} value 原始值。
* @return {any} 拷贝后的值。
*/
function cloneStructuredValue(value) {
if (Array.isArray(value)) {
return value.map(item => cloneStructuredValue(item));
}
if (!isPlainObject(value)) {
return value;
}
const cloned = {};
for (const key of Object.keys(value)) {
cloned[key] = cloneStructuredValue(value[key]);
}
return cloned;
}
/**
* 将可能为 JSON 字符串的值解析为对象。
*
* 仅在值为字符串时尝试解析;解析失败时按需记录警告。
*
* @param {any} value 原始值。
* @param {string[]} [warnings=[]] 风险提示列表。
* @param {boolean} [warnOnFailure=false] 解析失败时是否记录警告。
* @return {Object|null} 解析后的对象;非对象或解析失败返回 null。
*/
function parseCainiaoPrintinfoObject(value, warnings = [], warnOnFailure = false) {
const safeWarnings = Array.isArray(warnings) ? warnings : [];
let payload = value;
if (typeof payload === 'string') {
const text = payload.trim();
if (!text) {
return null;
}
try {
payload = JSON.parse(text);
} catch (error) {
if (warnOnFailure) {
safeWarnings.push('菜鸟 printinfo JSON 解析失败,已回退模板骨架');
}
return null;
}
}
return isPlainObject(payload) ? payload : null;
}
/**
* 将候选值归一化为菜鸟主面单 content。
*
* 支持三类输入:
* - 主 content 对象:{ templateURL, data, signature, ... }
* - 纯主 content 对象:{ encryptedData, signature, templateURL, ver, ... }
* - 旧 data 对象:{ cpCode, recipient, waybillCode, ... }
*
* 同时兼容 `data` 为 JSON 字符串的场景,仅解析一层。
*
* @param {any} candidate 候选值。
* @return {Object|null} 归一化后的主面单 content;无法识别返回 null。
*/
function normalizeCainiaoMainContentCandidate(candidate) {
const normalizedCandidate = parseCainiaoPrintinfoObject(candidate);
if (!normalizedCandidate) {
return null;
}
const normalizeTemplateUrlField = value => {
if (!Object.prototype.hasOwnProperty.call(value, 'templateURL')
&& Object.prototype.hasOwnProperty.call(value, 'templateUrl')) {
value.templateURL = toTrimmedString(value.templateUrl);
delete value.templateUrl;
}
return value;
};
const candidateData = parseCainiaoPrintinfoObject(normalizedCandidate.data) || normalizedCandidate.data;
if (isPlainObject(candidateData) && Object.keys(candidateData).length > 0) {
const normalizedContent = cloneStructuredValue(normalizedCandidate);
normalizedContent.data = cloneStructuredValue(candidateData);
return normalizeTemplateUrlField(normalizedContent);
}
if (Object.keys(normalizedCandidate).length === 0) {
return null;
}
const directContentFieldList = [ 'templateURL', 'templateUrl', 'encryptedData', 'signature', 'ver', 'addData' ];
const hasDirectContent = directContentFieldList.some(field => {
return Object.prototype.hasOwnProperty.call(normalizedCandidate, field);
});
if (hasDirectContent) {
return normalizeTemplateUrlField(cloneStructuredValue(normalizedCandidate));
}
const directDataFieldList = [ 'cpCode', 'recipient', 'waybillCode' ];
const hasDirectData = directDataFieldList.some(field => {
return Object.prototype.hasOwnProperty.call(normalizedCandidate, field);
});
if (!hasDirectData) {
return null;
}
const normalizedData = cloneStructuredValue(normalizedCandidate);
const normalizedContent = {};
if (Object.prototype.hasOwnProperty.call(normalizedData, 'templateURL')) {
normalizedContent.templateURL = toTrimmedString(normalizedData.templateURL);
delete normalizedData.templateURL;
}
if (Object.prototype.hasOwnProperty.call(normalizedData, 'templateUrl')) {
normalizedContent.templateURL = toTrimmedString(normalizedData.templateUrl);
delete normalizedData.templateUrl;
}
normalizedContent.data = normalizedData;
return normalizedContent;
}
/**
* 收集菜鸟 printinfo 中可能承载主面单的候选值。
*
* 仅按已知包装路径做有限展开,避免过度泛化:
* - payload 本身
* - payload.data(若可解析为对象)
* - payload.contents[0]
* - payload.documents[0].contents[0]
* - payload.task.documents[0].contents[0]
*
* @param {Object} payload 顶层 printinfo 对象。
* @return {Array<any>} 候选值列表。
*/
function collectCainiaoMainContentCandidates(payload) {
const candidateList = [];
const pushCandidate = value => {
if (value === undefined || value === null) {
return;
}
candidateList.push(value);
};
const rootDataPayload = parseCainiaoPrintinfoObject(payload.data);
const rootPayloadList = [ payload ];
if (rootDataPayload) {
rootPayloadList.push(rootDataPayload);
}
for (const currentPayload of rootPayloadList) {
if (!isPlainObject(currentPayload)) {
continue;
}
pushCandidate(currentPayload);
if (Array.isArray(currentPayload.contents)) {
pushCandidate(currentPayload.contents[0]);
}
if (Array.isArray(currentPayload.documents) && isPlainObject(currentPayload.documents[0])) {
pushCandidate(currentPayload.documents[0].contents && currentPayload.documents[0].contents[0]);
}
if (isPlainObject(currentPayload.task)
&& Array.isArray(currentPayload.task.documents)
&& isPlainObject(currentPayload.task.documents[0])) {
pushCandidate(currentPayload.task.documents[0].contents && currentPayload.task.documents[0].contents[0]);
}
}
return candidateList;
}
/**
* 解析菜鸟 printinfo 并归一化主面单 content。
*
* 兼容以下形态:
* - 形态 A:主 content 对象:{ templateURL, data, signature, ... }
* - 形态 B:纯主 content 对象:{ encryptedData, signature, templateURL, ver, ... }
* - 形态 C:旧 data 对象:{ cpCode, recipient, waybillCode, ... }
* - 形态 D:包装对象:{ contents: [ { templateURL, data, ... } ] }
* - 形态 E:包装对象:{ documents: [ { contents: [ ... ] } ] }
* - 形态 F:包装对象:{ task: { documents: [ { contents: [ ... ] } ] } }
* - 形态 G:`data` 为 JSON 字符串时解析一层
*
* @param {any} printinfo 原始 printinfo。
* @param {string[]} warnings 风险提示列表。
* @return {Object|null} 解析后的主面单 content;失败返回 null。
*/
function resolveCainiaoMainContentFromPrintinfo(printinfo, warnings = []) {
const payload = parseCainiaoPrintinfoObject(printinfo, warnings, true);
if (!payload) {
return null;
}
const candidateList = collectCainiaoMainContentCandidates(payload);
for (const candidate of candidateList) {
const resolvedContent = normalizeCainiaoMainContentCandidate(candidate);
if (resolvedContent) {
return resolvedContent;
}
}
return null;
}
/**
* 清洗菜鸟主面单 data 中的模板占位符,避免将 `__SAMPLE__` 原样下发。
*
* @param {any} value 原始主面单 data。
* @return {any} 清洗后的主面单 data。
*/
function sanitizeCainiaoMainDataPlaceholders(value) {
if (Array.isArray(value)) {
return value.map(item => sanitizeCainiaoMainDataPlaceholders(item));
}
if (isPlainObject(value)) {
const result = {};
for (const key of Object.keys(value)) {
result[key] = sanitizeCainiaoMainDataPlaceholders(value[key]);
}
return result;
}
if (typeof value === 'string') {
const text = toTrimmedString(value);
return text === '__SAMPLE__' ? '' : text;
}
return value;
}
/**
* 解析菜鸟主面单使用的快递公司编码。
*
* 优先使用上游补齐的菜鸟编码;缺失时再回退到原有物流编码来源,保持兼容。
*
* @param {Object} orderExpress 快递单对象。
* @param {Object} orderDelivery 订单对象。
* @return {string} 菜鸟快递公司编码。
*/
function resolveCainiaoCpCode(orderExpress, orderDelivery) {
const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {};
const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {};
return toTrimmedString(
safeOrderExpress.cainiao_cp_code
|| safeOrderExpress.logistics_code
|| safeOrderDelivery.logistics_code
|| safeOrderDelivery.sys_logistics_code
);
}
/**
* 解析菜鸟主面单模板地址。
*
* 仅主面单使用该来源,自定义区模板地址仍沿用原有样例解析逻辑。
*
* @param {Object} orderExpress 快递单对象。
* @return {string} 主面单模板地址。
*/
function resolveCainiaoMainTemplateURL(orderExpress) {
const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {};
return toTrimmedString(safeOrderExpress.cainiao_template_url);
}
/**
* 当菜鸟 printinfo 缺失或无效时,仅基于模板骨架构建最小主面单 data。
*
* 不再使用订单、策略等业务字段回填 sender/recipient/packageInfo 等主面单信息。
*
* @param {Object} templateMainData 模板主面单 data。
* @return {Object} 清洗占位符后的最小主面单 data。
*/
function buildCainiaoFallbackMainData(templateMainData) {
return isPlainObject(templateMainData)
? sanitizeCainiaoMainDataPlaceholders(templateMainData)
: {};
}
/**
* 固定菜鸟主面单 data 来源标记。
*
* @param {Object} mainData 菜鸟主面单 data。
* @param {string} source 数据来源标记。
* @return {Object} 已补齐 `_dataFrom` 的主面单 data。
*/
function ensureCainiaoMainDataSource(mainData, source) {
const normalizedMainData = isPlainObject(mainData) ? mainData : {};
normalizedMainData._dataFrom = toTrimmedString(source) || 'printinfo';
return normalizedMainData;
}
/**
* 归一化签约策略配置。
* @param {Object} input 入参对象。
@ -752,7 +1110,7 @@ function buildBaseData(input, platform, platformMeta) {
* 清洗模板样例,保留结构并裁切样例噪声。
* @param {any} value 原始对象。
* @param {string[]} warnings 警告列表。
* @param currentKey
* @param {string} [currentKey=''] 当前字段名。
* @return {any} 清洗后的对象。
*/
function sanitizeTemplatePrivateFields(value, warnings, currentKey = '') {
@ -821,7 +1179,7 @@ function sanitizeTemplatePrivateFields(value, warnings, currentKey = '') {
* @param {string} platform 归一化平台编码。
* @param {Object} skeleton 打印请求骨架。
* @param {Object} orderExpress 快递单对象。
* @param orderDelivery
* @param {Object} orderDelivery 订单对象。
* @param {string[]} warnings 风险提示列表。
* @param {Object} policyConfig 策略配置对象。
* @param {string} customDataTemplateURL 自定义区模板地址默认值。
@ -845,6 +1203,7 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde
const encryptedData = toTrimmedString(safeOrderExpress.printinfo);
const signature = toTrimmedString(safeOrderExpress.signature);
const key = toTrimmedString(safeOrderExpress.encryptprintinfo);
const version = toTrimmedString(safeOrderExpress.ver);
const waybillCode = toTrimmedString(safeOrderExpress.waybill_code);
const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {};
const composeItems = resolveCustomComposeItems(safeOrderExpress, safeOrderDelivery);
@ -919,6 +1278,9 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde
content.encryptedData = encryptedData || '__UPSTREAM_REQUIRED__';
content.signature = signature || '__UPSTREAM_REQUIRED__';
content.key = key || '__UPSTREAM_REQUIRED__';
if (version) {
content.ver = version;
}
}
const customDataContent = contents.find(content => {
@ -963,7 +1325,7 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde
* @param {string} platform 归一化平台编码。
* @param {Object} skeleton 打印请求骨架。
* @param {Object} orderExpress 快递单对象。
* @param orderDelivery
* @param {Object} orderDelivery 订单对象。
* @param {Object} policyConfig 策略配置对象。
*/
function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig) {
@ -984,6 +1346,7 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli
const encryptedData = toTrimmedString(safeOrderExpress.encryptprintinfo);
const signature = toTrimmedString(safeOrderExpress.signature);
const version = toTrimmedString(safeOrderExpress.ver);
const waybillCode = toTrimmedString(safeOrderExpress.waybill_code);
const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {};
const composeItems = resolveCustomComposeItems(safeOrderExpress, safeOrderDelivery);
@ -1082,6 +1445,9 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli
content.addData.sender.name = toTrimmedString(safePolicyConfig.sender_name);
content.encryptedData = encryptedData;
content.signature = signature;
if (version) {
content.ver = version;
}
}
const customContent = document.contents.find(isPddCustomContent);
@ -1099,6 +1465,153 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli
}
}
/**
* 菜鸟平台主面单与自定义区字段回填。
*
* 规则:
* - wms_order_express.printinfo(字符串/对象)解析后直接回填主 contents[0]
* - documentID 使用 wms_order_express.waybill_code
* - 若模板样例存在 data.CustomControl 对应模板地址,则补充菜鸟自定义区内容
*
* 仅在平台为 cainiao 时生效;主面单优先直接使用 printinfo 解析结果,解析失败时仅回退模板骨架。
*
* @param {string} platform 归一化平台编码。
* @param {Object} skeleton 打印请求骨架。
* @param {Object} orderExpress 快递单对象。
* @param {Object} orderDelivery 订单对象。
* @param {Object} policyConfig 策略配置对象。
* @param {string} customControlTemplateURL 菜鸟自定义区模板地址。
* @param {string[]} warnings 风险提示列表。
*/
function applyCainiaoExpressFieldMapping(
platform,
skeleton,
orderExpress,
orderDelivery,
policyConfig,
customControlTemplateURL,
warnings
) {
if (platform !== 'cainiao') {
return;
}
const safeSkeleton = isPlainObject(skeleton) ? skeleton : {};
const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {};
const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {};
const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {};
const documents = safeSkeleton.task && Array.isArray(safeSkeleton.task.documents)
? safeSkeleton.task.documents
: [];
if (documents.length === 0) {
return;
}
const cainiaoMainContent = resolveCainiaoMainContentFromPrintinfo(safeOrderExpress.printinfo, warnings);
const hasPrintinfoMainContent = isPlainObject(cainiaoMainContent);
const waybillCode = toTrimmedString(safeOrderExpress.waybill_code);
const cainiaoCpCode = resolveCainiaoCpCode(safeOrderExpress, safeOrderDelivery);
const cainiaoMainTemplateURL = resolveCainiaoMainTemplateURL(safeOrderExpress);
const composeItems = resolveCustomComposeItems(safeOrderExpress, safeOrderDelivery);
const customProductInfoLines = buildWaybillCustomProductInfoLines(
composeItems,
safePolicyConfig,
{
waveNo: toTrimmedString(safeOrderDelivery.wave_no),
wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0),
wave_index: Number(safeOrderDelivery.wave_index || 0),
platforms_index: Number(safeOrderDelivery.platforms_index || 0),
expressInterfaceName: toTrimmedString(
safeOrderExpress.logistics_interface_name
|| safeOrderExpress.logistics_name
|| safeOrderDelivery.logistics_interface_name
|| safeOrderDelivery.logistics_name
),
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
}
);
const customControlText = mergeWaybillCustomLines(customProductInfoLines, {
lineBreak: LINE_BREAK_MAP.CR,
});
for (const document of documents) {
if (!isPlainObject(document)) {
continue;
}
if (waybillCode) {
document.documentID = waybillCode;
}
if (!Array.isArray(document.contents)) {
document.contents = [];
}
const contents = document.contents;
let mainContent = contents[0];
if (!isPlainObject(mainContent)) {
mainContent = {};
if (contents.length === 0) {
contents.push(mainContent);
} else {
contents[0] = mainContent;
}
}
if (hasPrintinfoMainContent) {
mainContent = cloneStructuredValue(cainiaoMainContent);
contents[0] = mainContent;
} else {
mainContent = cloneStructuredValue(mainContent);
contents[0] = mainContent;
}
if (hasPrintinfoMainContent) {
if (isPlainObject(mainContent.data)) {
mainContent.data = ensureCainiaoMainDataSource(mainContent.data, 'printinfo');
}
} else {
mainContent.data = ensureCainiaoMainDataSource(
buildCainiaoFallbackMainData(mainContent.data),
'template'
);
}
if (cainiaoCpCode && isPlainObject(mainContent.data)) {
mainContent.data.cpCode = cainiaoCpCode;
mainContent.data.realCpCode = cainiaoCpCode;
}
if (cainiaoMainTemplateURL) {
mainContent.templateURL = cainiaoMainTemplateURL;
}
if (!toTrimmedString(customControlTemplateURL) || !customControlText) {
continue;
}
const customControlContent = contents.find(content => {
return isPlainObject(content)
&& isPlainObject(content.data)
&& Object.prototype.hasOwnProperty.call(content.data, 'CustomControl');
});
if (customControlContent) {
customControlContent.templateURL = toTrimmedString(customControlTemplateURL);
customControlContent.data.CustomControl = customControlText;
} else {
contents.push({
templateURL: toTrimmedString(customControlTemplateURL),
data: {
CustomControl: customControlText,
},
});
}
}
}
/**
* 构建平台请求骨架。
* @param {Object} input 输入对象。
@ -1126,6 +1639,7 @@ function buildPlatformRequestSkeleton(input = {}) {
const warnings = [ ...baseResult.warnings ];
const cleanedTemplateSample = sanitizeTemplatePrivateFields(templateSample, warnings);
const customDataTemplateURL = resolveKuaishouCustomDataTemplateURL(templateSample);
const cainiaoCustomControlTemplateURL = resolveCainiaoCustomControlTemplateURL(templateSample);
const requestId = toTrimmedString(options.requestId || templateSample.requetID || templateSample.requestID);
const taskId = toTrimmedString(options.taskId || requestId);
@ -1195,6 +1709,16 @@ function buildPlatformRequestSkeleton(input = {}) {
warnings.push('template_sample.task.documents 为空或未能解析,已输出空 documents 数组');
}
applyCainiaoExpressFieldMapping(
normalized.platform,
skeleton,
orderExpressForCompose,
orderDeliveryForCompose,
policyConfig,
cainiaoCustomControlTemplateURL,
warnings
);
applyKuaishouExpressFieldMapping(
normalized.platform,
skeleton,

View File

@ -85,16 +85,30 @@ class QimenClient {
return Object.assign({}, baseQueryParams, { sign });
}
/**
* 构建奇门请求查询参数。
* @param {string} method 接口方法名
* @param {string} appKey 应用 Key
* @param {string} version 接口版本
* @param {?string} customerId 货主标识
* @param {Function} formatDate 时间格式化函数
* @return {Object} 查询参数对象
*/
getQueryParams(method, appKey, version, customerId, formatDate) {
return {
const queryParams = {
method,
format: 'xml',
app_key: appKey,
v: version,
sign_method: 'md5',
customerId,
timestamp: formatDate(new Date()),
};
if (customerId != null) {
queryParams.customerId = customerId;
}
return queryParams;
}
generateUrlWithParams(baseUrl, params) {
@ -110,6 +124,14 @@ class QimenClient {
return `${baseUrl}${separator}${queryString}`;
}
/**
* 发送奇门请求并记录请求日志。
* @param {string} method 接口方法名
* @param {?string} customerId 货主标识
* @param {Object} data 业务请求数据
* @param {Object} runtime 运行时依赖
* @return {Promise<{queryId: *, xmlArray: *}>} 查询结果
*/
async send(method, customerId, data, runtime = {}) {
const helpers = this.resolveRuntime(runtime);
@ -141,7 +163,6 @@ class QimenClient {
to_key: wmsAppKey,
method,
sign,
costomer_id: customerId,
v: '2.0',
url,
created_at: new Date(),
@ -149,7 +170,13 @@ class QimenClient {
result: '',
use_time: 0,
};
if (customerId != null) {
logData.costomer_id = customerId;
}
console.log('发送奇门请求,URL:', url, '请求数据:', queryData);
const result = await this.sendRequest(url, queryData, logData, helpers);
console.log('奇门请求响应:', result);
const xmlArray = await helpers.parseXmlToArray(result.res);
return { queryId: result.queryId, xmlArray };
}

View File

@ -0,0 +1,53 @@
'use strict';
const DELETED_SHOP_NAME_PREFIX = 'DELETED_SHOP_';
/**
* 判断店铺名是否为软删除墓碑名。
*
* @param {*} shopName 店铺名称
* @return {boolean} 是否为已软删除店铺
*/
function isDeletedShopName(shopName) {
return String(shopName || '').trim().startsWith(DELETED_SHOP_NAME_PREFIX);
}
/**
* 判断店铺记录是否为软删除状态。
*
* @param {Object} shop 店铺记录或模型实例
* @return {boolean} 是否已软删除
*/
function isSoftDeletedShop(shop) {
if (!shop || typeof shop !== 'object') {
return false;
}
const plainShop = typeof shop.get === 'function'
? shop.get({ plain: true })
: shop;
return isDeletedShopName(plainShop && plainShop.shop_name);
}
/**
* 构建排除软删除店铺的 Sequelize where 条件。
*
* @param {import('egg').Application} app Egg 应用实例
* @param {string} [fieldName='shop_name'] 店铺名字段名
* @return {Object} Sequelize where 条件
*/
function buildNotDeletedShopWhere(app, fieldName = 'shop_name') {
return {
[fieldName]: {
[app.Sequelize.Op.notLike]: `${DELETED_SHOP_NAME_PREFIX}%`,
},
};
}
module.exports = {
DELETED_SHOP_NAME_PREFIX,
isDeletedShopName,
isSoftDeletedShop,
buildNotDeletedShopWhere,
};

View File

@ -1,5 +1,10 @@
'use strict';
/**
* 定义快递基础信息模型。
* @param {import('egg').Application} app Egg 应用实例
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} 快递模型
*/
module.exports = app => {
const { STRING, JSON } = app.Sequelize;
@ -38,6 +43,12 @@ module.exports = app => {
allowNull: true,
comment: '抖音编码',
},
CAINIAO: {
field: 'CAINIAO',
type: STRING(255),
allowNull: true,
comment: '菜鸟编码',
},
}, {
tableName: 'wms_express',
freezeTableName: true,

View File

@ -1,5 +1,10 @@
'use strict';
/**
* 定义快递接口配置模型。
* @param {Object} app Egg 应用对象。
* @return {Object} 快递接口配置模型。
*/
module.exports = app => {
const { INTEGER, STRING, BIGINT, TINYINT, JSON } = app.Sequelize;
@ -36,6 +41,11 @@ module.exports = app => {
allowNull: true,
comment: '仓库编码',
},
shop_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '店铺ID',
},
sender_name: {
type: STRING(50),
allowNull: true,
@ -134,11 +144,22 @@ module.exports = app => {
defaultValue: 0,
comment: '是否上门取件',
},
is_hide_goods: {
type: TINYINT(1),
allowNull: true,
defaultValue: 0,
comment: '是否隐藏物品信息',
},
shipperno: {
type: STRING(255),
allowNull: true,
comment: '寄件网点编码',
},
template_url: {
type: STRING(500),
allowNull: true,
comment: '打印模板链接',
},
ext_data: {
type: JSON,
allowNull: true,
@ -160,12 +181,15 @@ module.exports = app => {
});
/**
* 定义快递接口与系统快递的关联关系。
* 定义快递接口与系统快递、店铺、打印平台的关联关系。
*
* 说明:`wms_express_interface.sys_express_code` 对应 `wms_express.code`。
* 说明:
* - `wms_express_interface.sys_express_code` 对应 `wms_express.code`
* - `wms_express_interface.shop_id` 对应 `wms_shops.id`
* - `wms_express_interface.platform_code` 对应 `wms_print_platform.platform_code`
*/
ExpressInterface.associate = function() {
const { Express } = app.model;
const { Express, Shop, PrintPlatform } = app.model;
if (Express && typeof ExpressInterface.belongsTo === 'function') {
ExpressInterface.belongsTo(Express, {
@ -176,6 +200,24 @@ module.exports = app => {
});
}
if (Shop && typeof ExpressInterface.belongsTo === 'function') {
ExpressInterface.belongsTo(Shop, {
foreignKey: 'shop_id',
targetKey: 'id',
as: 'shop',
constraints: false,
});
}
if (PrintPlatform && typeof ExpressInterface.belongsTo === 'function') {
ExpressInterface.belongsTo(PrintPlatform, {
foreignKey: 'platform_code',
targetKey: 'platform_code',
as: 'printPlatform',
constraints: false,
});
}
};
return ExpressInterface;

View File

@ -102,6 +102,11 @@ module.exports = app => {
allowNull: true,
comment: '加密打印信息',
},
ver: {
type: STRING(50),
allowNull: true,
comment: '打印版本号',
},
encryptedtoken: {
type: TEXT,
allowNull: true,

View File

@ -6,7 +6,7 @@
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} 平台模型
*/
module.exports = app => {
const { STRING, INTEGER } = app.Sequelize;
const { STRING, INTEGER, BIGINT } = app.Sequelize;
const Platform = app.model.define('platform', {
code: {
@ -70,10 +70,10 @@ module.exports = app => {
allowNull: true,
comment: '打印组件标识',
},
auth_base_url: {
type: STRING(255),
print_platform_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '授权基础地址',
comment: '关联打印平台ID',
},
}, {
tableName: 'wms_platform',

View File

@ -0,0 +1,86 @@
'use strict';
/**
* 打印平台元数据模型。
* @param {import('egg').Application} app Egg 应用实例。
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} 打印平台元数据模型。
*/
module.exports = app => {
const { BIGINT, STRING, DATE, TINYINT, INTEGER } = app.Sequelize;
const PrintPlatform = app.model.define('print_platform', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
platform_code: {
type: STRING(50),
allowNull: false,
comment: '打印平台编码',
},
platform_name: {
type: STRING(100),
allowNull: false,
comment: '打印平台名称',
},
platid: {
type: INTEGER(11),
allowNull: true,
comment: '平台ID',
},
status: {
type: STRING(20),
allowNull: false,
defaultValue: 'ACTIVE',
comment: '状态',
},
remark: {
type: STRING(255),
allowNull: true,
comment: '备注',
},
auth_base_url: {
type: STRING(255),
allowNull: true,
comment: '授权基础地址',
},
create_at: {
type: DATE,
allowNull: false,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
update_at: {
type: DATE,
allowNull: false,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
deleted: {
type: TINYINT,
allowNull: false,
defaultValue: 0,
comment: '软删除标记:0-未删除,1-已删除',
},
}, {
tableName: 'wms_print_platform',
timestamps: false,
comment: '打印平台元数据表',
indexes: [
{
name: 'uk_platform_code',
unique: true,
fields: [ 'platform_code' ],
},
{
name: 'idx_status',
fields: [ 'status' ],
},
],
});
return PrintPlatform;
};

View File

@ -133,5 +133,24 @@ module.exports = app => {
],
});
/**
* 定义店铺与打印平台的关联关系。
*
* 说明:
* - `wms_shops.platform_code` 对应 `wms_print_platform.platform_code`
*/
Shop.associate = function() {
const { PrintPlatform } = app.model;
if (PrintPlatform && typeof Shop.belongsTo === 'function') {
Shop.belongsTo(PrintPlatform, {
foreignKey: 'platform_code',
targetKey: 'platform_code',
as: 'printPlatform',
constraints: false,
});
}
};
return Shop;
};
};

View File

@ -73,7 +73,7 @@ module.exports = app => {
comment: '门店ID',
},
device: {
type: STRING(10),
type: STRING(100),
allowNull: true,
comment: '设备',
},

View File

@ -5,6 +5,8 @@ module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
router.get('/auth/platformOauthCallback', controller.home.platformOauthCallback);
router.get('/auth/platformOauthBind', controller.home.platformOauthBind);
router.get('/query/pddCode/:code', controller.home.queryPddCode);
// 内部网关接口
router.post('/internal/v1/gateway', controller.gateway.internal);

File diff suppressed because it is too large Load Diff

View File

@ -1423,6 +1423,72 @@ class WaveService extends OrderBaseService {
return normalizedValue;
}
/**
* 规范化波次列表快递分配状态筛选值。
*
* @param {string} value 入参筛选值。
* @return {string} 规范化后的筛选值,未传时返回空字符串。
*/
normalizeBatchListExpressAssignmentStatusFilter(value) {
if (value === undefined || value === null || value === '') {
return '';
}
const normalizedValue = String(value).trim();
if (!normalizedValue) {
return '';
}
const allowedValueMap = {
unassigned: '未分配',
partially_assigned: '部分分配',
assigned: '已分配',
};
if (allowedValueMap[normalizedValue]) {
return allowedValueMap[normalizedValue];
}
const allowedValues = [ '未分配', '部分分配', '已分配' ];
if (!allowedValues.includes(normalizedValue)) {
throw new Error('express_assignment_status 参数不合法,仅支持: unassigned、partially_assigned、assigned');
}
return normalizedValue;
}
/**
* 规范化波次列表打印状态筛选值。
*
* @param {string} value 入参筛选值。
* @return {string} 规范化后的筛选值,未传时返回空字符串。
*/
normalizeBatchListPrintAssignmentStatusFilter(value) {
if (value === undefined || value === null || value === '') {
return '';
}
const normalizedValue = String(value).trim();
if (!normalizedValue) {
return '';
}
const allowedValueMap = {
unprinted: '未打印',
partially_printed: '部分打印',
printed: '已打印',
};
if (allowedValueMap[normalizedValue]) {
return allowedValueMap[normalizedValue];
}
const allowedValues = [ '未打印', '部分打印', '已打印' ];
if (!allowedValues.includes(normalizedValue)) {
throw new Error('print_assignment_status 参数不合法,仅支持: unprinted、partially_printed、printed');
}
return normalizedValue;
}
/**
* 解析模型对应的 SQL 表名并完成安全转义。
*
@ -1508,11 +1574,110 @@ class WaveService extends OrderBaseService {
};
}
/**
* 构建波次列表快递分配状态筛选 SQL 条件。
*
* @param {string} statusFilter 快递分配状态筛选值。
* @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。
*/
buildBatchListExpressAssignmentFilterClause(statusFilter = '') {
const normalizedStatusFilter = this.normalizeBatchListExpressAssignmentStatusFilter(statusFilter);
if (!normalizedStatusFilter) {
return {
sql: '',
replacements: {},
};
}
const totalExpr = 'COALESCE(wave_order_stats.order_total, 0)';
const expressNoneExpr = 'COALESCE(wave_order_stats.post_none_count, 0)';
const expressFinExpr = 'COALESCE(wave_order_stats.post_fin_count, 0)';
const expressErrorExpr = 'COALESCE(wave_order_stats.post_error_count, 0)';
let whereClause = '';
if (normalizedStatusFilter === '已分配') {
whereClause = `
${expressFinExpr} = ${totalExpr}
AND ${totalExpr} > 0
`;
} else if (normalizedStatusFilter === '部分分配') {
whereClause = `
${expressErrorExpr} = 0
AND ${expressNoneExpr} <> ${totalExpr}
AND ${expressFinExpr} <> ${totalExpr}
`;
} else if (normalizedStatusFilter === '未分配') {
return {
sql: `
AND (
${totalExpr} = 0
OR ${expressErrorExpr} > 0
OR ${expressNoneExpr} = ${totalExpr}
)`,
replacements: {},
};
}
return {
sql: `
AND ${whereClause}`,
replacements: {},
};
}
/**
* 构建波次列表打印状态筛选 SQL 条件。
*
* @param {string} statusFilter 打印状态筛选值。
* @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。
*/
buildBatchListPrintAssignmentFilterClause(statusFilter = '') {
const normalizedStatusFilter = this.normalizeBatchListPrintAssignmentStatusFilter(statusFilter);
if (!normalizedStatusFilter) {
return {
sql: '',
replacements: {},
};
}
const totalExpr = 'COALESCE(wave_order_stats.order_total, 0)';
const printNoneExpr = 'COALESCE(wave_order_stats.print_none_count, 0)';
const printFinExpr = 'COALESCE(wave_order_stats.print_fin_count, 0)';
let whereClause = '';
if (normalizedStatusFilter === '已打印') {
whereClause = `
${printFinExpr} = ${totalExpr}
AND ${totalExpr} > 0
`;
} else if (normalizedStatusFilter === '部分打印') {
whereClause = `
${printNoneExpr} <> ${totalExpr}
AND ${printFinExpr} <> ${totalExpr}
`;
} else if (normalizedStatusFilter === '未打印') {
return {
sql: `
AND (
${totalExpr} = 0
OR ${printNoneExpr} = ${totalExpr}
)`,
replacements: {},
};
}
return {
sql: `
AND ${whereClause}`,
replacements: {},
};
}
/**
* 构建波次列表 where 条件(白名单字段)。
*
* @param {Object} whereData 查询 where 入参。
* @return {{ sql: string, replacements: Object, storageAssignmentStatus: string }} SQL 条件片段、参数与库位分配状态筛选值。
* @return {{ sql: string, replacements: Object, storageAssignmentStatus: string, expressAssignmentStatus: string, printAssignmentStatus: string }} SQL 条件片段、参数与分配状态筛选值。
*/
buildBatchListWhereClause(whereData = {}) {
const normalizedWhere = this.isPlainObject(whereData) ? whereData : {};
@ -1540,6 +1705,8 @@ class WaveService extends OrderBaseService {
'processed_orders_min',
'processed_orders_max',
'storage_assignment_status',
'express_assignment_status',
'print_assignment_status',
];
const invalidFields = whereKeys.filter(key => !allowedFields.includes(key));
@ -1676,11 +1843,19 @@ class WaveService extends OrderBaseService {
const storageAssignmentStatus = this.normalizeBatchListStorageAssignmentStatusFilter(
normalizedWhere.storage_assignment_status
);
const expressAssignmentStatus = this.normalizeBatchListExpressAssignmentStatusFilter(
normalizedWhere.express_assignment_status
);
const printAssignmentStatus = this.normalizeBatchListPrintAssignmentStatusFilter(
normalizedWhere.print_assignment_status
);
return {
sql: conditions.length > 0 ? `\n AND ${conditions.join('\n AND ')}` : '',
replacements,
storageAssignmentStatus,
expressAssignmentStatus,
printAssignmentStatus,
};
}
@ -3630,6 +3805,8 @@ class WaveService extends OrderBaseService {
const orderTableName = this.getModelTableSqlName(orderModel);
const whereClause = this.buildBatchListWhereClause(requestData.where);
const storageAssignmentFilterClause = this.buildBatchListStorageAssignmentFilterClause(whereClause.storageAssignmentStatus);
const expressAssignmentFilterClause = this.buildBatchListExpressAssignmentFilterClause(whereClause.expressAssignmentStatus);
const printAssignmentFilterClause = this.buildBatchListPrintAssignmentFilterClause(whereClause.printAssignmentStatus);
const baseBatchWhereSql = `
warehouse_id = :warehouseId
AND wave_status IN (:waveStatusList)
@ -3670,7 +3847,10 @@ class WaveService extends OrderBaseService {
GROUP BY candidate_wave.wave_id
) wave_order_stats ON wave_order_stats.wave_id = wb.wave_id
WHERE 1 = 1
AND COALESCE(wave_order_stats.order_total, 0) > 0
${storageAssignmentFilterClause.sql}
${expressAssignmentFilterClause.sql}
${printAssignmentFilterClause.sql}
`;
const listSql = `
@ -3705,6 +3885,8 @@ class WaveService extends OrderBaseService {
waveStatusList,
...whereClause.replacements,
...storageAssignmentFilterClause.replacements,
...expressAssignmentFilterClause.replacements,
...printAssignmentFilterClause.replacements,
limit: pageSize,
offset,
},
@ -3715,6 +3897,8 @@ class WaveService extends OrderBaseService {
waveStatusList,
...whereClause.replacements,
...storageAssignmentFilterClause.replacements,
...expressAssignmentFilterClause.replacements,
...printAssignmentFilterClause.replacements,
},
}),
]);

View File

@ -1469,22 +1469,22 @@ class PrintService extends MainService {
};
}
const platformRows = await this.ctx.model.Platform.findAll({
attributes: [ 'code', 'component' ],
const platformRows = await this.ctx.model.PrintPlatform.findAll({
attributes: [ 'platform_code', 'platform_name' ],
where: {
code: platformCodes,
platform_code: platformCodes,
},
raw: true,
});
const platformComponentMap = {};
for (const row of platformRows) {
const platformCode = String(row && row.code ? row.code : '').trim();
const platformCode = String(row && row.platform_code ? row.platform_code : '').trim();
if (!platformCode) {
continue;
}
platformComponentMap[platformCode] = String(row && row.component ? row.component : '').trim();
platformComponentMap[platformCode] = String(row && row.platform_name ? row.platform_name : '').trim();
}
console.log('platformComponentMap', platformComponentMap);
for (const platformCode of platformCodes) {
const component = String(platformComponentMap[platformCode] || '').trim();
if (!component) {

View File

@ -153,6 +153,8 @@ class expressInterfaceService extends MainService {
isPickup: camelIsPickup,
shipperno: shipperNo,
shipperNo: camelShipperNo,
template_url: templateUrl,
templateUrl: camelTemplateUrl,
ext_data: extData,
extData: camelExtData,
...rest
@ -189,6 +191,9 @@ class expressInterfaceService extends MainService {
if (shipperNo !== undefined || camelShipperNo !== undefined) {
payload.shipperno = shipperNo !== undefined ? shipperNo : camelShipperNo;
}
if (templateUrl !== undefined || camelTemplateUrl !== undefined) {
payload.template_url = templateUrl !== undefined ? templateUrl : camelTemplateUrl;
}
if (extData !== undefined || camelExtData !== undefined) {
payload.ext_data = extData !== undefined ? extData : camelExtData;
}
@ -223,6 +228,8 @@ class expressInterfaceService extends MainService {
isPickup: camelIsPickup,
shipperno: shipperNo,
shipperNo: camelShipperNo,
template_url: templateUrl,
templateUrl: camelTemplateUrl,
ext_data: extData,
extData: camelExtData,
...rest
@ -260,6 +267,9 @@ class expressInterfaceService extends MainService {
if (shipperNo !== undefined || camelShipperNo !== undefined) {
payload.shipperno = shipperNo !== undefined ? shipperNo : camelShipperNo;
}
if (templateUrl !== undefined || camelTemplateUrl !== undefined) {
payload.template_url = templateUrl !== undefined ? templateUrl : camelTemplateUrl;
}
if (extData !== undefined || camelExtData !== undefined) {
payload.ext_data = extData !== undefined ? extData : camelExtData;
}

View File

@ -0,0 +1,160 @@
'use strict';
const MainService = require('../main');
/**
* 店铺 methods 出口。
*/
class ShopsMethodService extends MainService {
/**
* 初始化店铺模块鉴权配置。
*
* @param {Egg.Context} ctx 上下文对象
*/
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = '';
const _noNeedLog = '*';
const _noNeedAuth = '';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 统一调用店铺业务服务。
*
* @param {string} methodName 业务方法名
* @param {Object} data 请求参数
* @param {string} fallbackMessage 默认错误文案
* @return {Promise<Object>} methods 标准返回
*/
async callShopsSystem(methodName, data, fallbackMessage) {
const { service } = this;
try {
const result = await service.systems.shops[methodName](data);
return this.success('ok', { data: result, code: 200 });
} catch (error) {
return this.fail(error.message || fallbackMessage, {
code: Number(error.code) || 500,
});
}
}
/**
* shops.list:分页查询店铺。
*
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 查询结果
*/
async list(data = {}) {
const payload = {
...(data && typeof data === 'object' ? data : {}),
};
this.prepareWhereContext(payload, {
specialFieldMap: this.service.systems.shops.getListWhereSpecialFieldMap(),
});
return await this.callShopsSystem('list', payload, '查询店铺列表失败');
}
/**
* shops.add:新增店铺。
*
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 新增结果
*/
async add(data = {}) {
const {
custom_name: customName,
customName: customNameCamel,
platform_code: platformCode,
platformCode: platformCodeCamel,
shop_name: shopName,
shopName: shopNameCamel,
} = data || {};
return await this.callShopsSystem('add', {
custom_name: customName !== undefined ? customName : customNameCamel,
platform_code: platformCode !== undefined ? platformCode : platformCodeCamel,
shop_name: shopName !== undefined ? shopName : shopNameCamel,
}, '新增店铺失败');
}
/**
* shops.del:软删除店铺。
*
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 删除结果
*/
async del(data = {}) {
const {
id,
shop_id: shopId,
shopId: shopIdCamel,
} = data || {};
return await this.callShopsSystem('del', {
id: id !== undefined ? id : (shopId !== undefined ? shopId : shopIdCamel),
}, '删除店铺失败');
}
/**
* shops.edit:编辑店铺。
*
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 编辑结果
*/
async edit(data = {}) {
const {
id,
shop_id: shopId,
shopId: shopIdCamel,
custom_name: customName,
customName: customNameCamel,
platform_code: platformCode,
platformCode: platformCodeCamel,
} = data || {};
const payload = {
id: id !== undefined ? id : (shopId !== undefined ? shopId : shopIdCamel),
};
if (customName !== undefined || customNameCamel !== undefined) {
payload.custom_name = customName !== undefined ? customName : customNameCamel;
}
if (platformCode !== undefined || platformCodeCamel !== undefined) {
payload.platform_code = platformCode !== undefined ? platformCode : platformCodeCamel;
}
return await this.callShopsSystem('edit', payload, '编辑店铺失败');
}
/**
* shop.GetAuthorizeSessionKey:按店铺平台生成授权会话。
*
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 会话结果
*/
async GetAuthorizeSessionKey(data = {}) {
const {
id,
shop_id: shopId,
shopId: shopIdCamel,
callbackurl,
callback_url: callbackUrlSnake,
callbackUrl,
} = data || {};
return await this.callShopsSystem('getAuthorizeSessionKey', {
id: id !== undefined ? id : (shopId !== undefined ? shopId : shopIdCamel),
callbackurl: callbackurl !== undefined
? callbackurl
: (callbackUrlSnake !== undefined ? callbackUrlSnake : callbackUrl),
}, '获取授权会话失败');
}
}
module.exports = ShopsMethodService;

View File

@ -6,6 +6,7 @@ const DEFAULT_CACHE_TTL_SECONDS = 600;
const DEFAULT_EXPRESS_PRODUCT_TYPE_CACHE_TTL_SECONDS = 60 * 60;
const DEFAULT_WAYBILL_BATCH_SIZE = 10;
const WAYBILL_EXCEPTION_STEP = 3;
const WAYBILL_ASYNC_SINGLE_ORDER_PLATFORM_CODES = new Set([ 'cainiao', 'pdd' ]);
const WAYBILL_ORDER_DELIVERY_MIN_ATTRIBUTES = Object.freeze([
'id',
'store_id',
@ -62,20 +63,33 @@ class ExpressService extends Service {
* 生成快递列表缓存键。
*
* @param {number|string} warehouseId 仓库ID
* @param {boolean} [systemOnly=false] 是否仅返回系统基础快递列表
* @param {boolean} [systemOnly=false] 是否仅返回系统基础快递列表
* @param {string} [systemExpressCode=''] 系统快递编码
* @return {string} 缓存键
*/
getExpressListCacheKey(warehouseId = 0, systemOnly = false) {
getExpressListCacheKey(warehouseId = 0, systemOnly = false, systemExpressCode = '') {
const normalizedExpressCode = String(systemExpressCode || '').trim().toUpperCase();
if (systemOnly) {
if (normalizedExpressCode) {
return `express:list:system:${normalizedExpressCode}`;
}
return 'express:list:system';
}
const normalizedWarehouseId = Number(warehouseId || 0);
if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) {
if (normalizedExpressCode) {
return `express:list:${normalizedWarehouseId}:express:${normalizedExpressCode}`;
}
return `express:list:${normalizedWarehouseId}`;
}
if (normalizedExpressCode) {
return `express:list:express:${normalizedExpressCode}`;
}
return 'express:list';
}
/**
@ -368,7 +382,6 @@ class ExpressService extends Service {
const sysPlatformCode = String(order.sys_platform_code || order.sysPlatformCode || '').trim();
const logisticsCode = String(order.logistics_code || order.logisticsCode || '').trim();
const syslogisticsCode = String(order.sys_logistics_code || order.sysLogisticsCode || '').trim();
const platformCode = this.normalizeWaybillCreatePlatformCode(order);
for (const businessKey of businessKeys) {
@ -743,24 +756,32 @@ class ExpressService extends Service {
* 从数据库加载快递设置列表。
*
* @param {number|string} warehouseId 仓库ID
* @param {string} [systemExpressCode=''] 系统快递编码
* @return {Promise<Array>} 快递设置列表
*/
async loadExpressSettingListFromDatabase(warehouseId = 0) {
async loadExpressSettingListFromDatabase(warehouseId = 0, systemExpressCode = '') {
const normalizedWarehouseId = Number(warehouseId || 0);
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
return [];
}
const normalizedExpressCode = String(systemExpressCode || '').trim().toUpperCase();
const expressSettingModel = this.ctx.model && this.ctx.model.ExpressSetting;
if (!expressSettingModel || typeof expressSettingModel.findAll !== 'function') {
return [];
}
const where = {
warehouse_id: normalizedWarehouseId,
};
if (normalizedExpressCode) {
where.express_code = normalizedExpressCode;
}
const rows = await expressSettingModel.findAll({
attributes: [ 'id', 'code', 'name', 'express_code' ],
where: {
warehouse_id: normalizedWarehouseId,
},
where,
order: [[ 'code', 'ASC' ]],
raw: true,
});
@ -772,6 +793,46 @@ class ExpressService extends Service {
return rows;
}
/**
* 构建仓库快递自定义编码列表。
*
* 仅返回快递设置记录,不合并系统快递记录;用于按快递公司编码筛选场景。
*
* @param {Array<Object>} expressList 系统快递列表
* @param {Array<Object>} expressSettingList 快递设置列表
* @return {Array<Object>} 自定义编码列表
*/
buildExpressSettingCustomCodeList(expressList, expressSettingList) {
const normalizedExpressList = Array.isArray(expressList) ? expressList : [];
const expressMap = new Map();
for (const expressItem of normalizedExpressList) {
if (!expressItem || typeof expressItem !== 'object') {
continue;
}
const code = String(expressItem.code || expressItem.value || '').trim();
if (!code || expressMap.has(code)) {
continue;
}
expressMap.set(code, expressItem);
}
const result = [];
for (const row of Array.isArray(expressSettingList) ? expressSettingList : []) {
const mergedItem = this.normalizeExpressSettingRow(row, expressMap);
if (!mergedItem) {
continue;
}
result.push(mergedItem);
}
return result;
}
/**
* 合并系统快递和快递设置列表。
*
@ -870,6 +931,370 @@ class ExpressService extends Service {
};
}
/**
* 规范化快递编码为大写键值。
*
* @param {*} expressCode 原始快递编码
* @return {string} 规范化后的快递编码
*/
normalizeExpressCodeKey(expressCode) {
return String(expressCode || '').trim().toUpperCase();
}
/**
* 判断是否为顺丰快递编码。
*
* @param {*} expressCode 原始快递编码
* @return {boolean} 是否顺丰
*/
isSfExpressCode(expressCode) {
const normalizedExpressCode = this.normalizeExpressCodeKey(expressCode);
return normalizedExpressCode === 'SF' || normalizedExpressCode === 'SHUNFENG';
}
/**
* 从 type_desc 中提取快递产品类型映射。
*
* @param {*} typeDesc 原始 type_desc
* @return {Array<{ code: string, name: string }>} 提取后的产品类型列表
*/
extractExpressProductTypesFromTypeDesc(typeDesc) {
const rawTypeDesc = String(typeDesc || '').trim();
if (!rawTypeDesc) {
return [];
}
const normalizeCode = value => String(value || '').trim();
const normalizeName = value => String(value || '').trim();
const toPair = (codeValue, nameValue) => {
const code = normalizeCode(codeValue);
if (!code) {
return null;
}
return {
code,
name: normalizeName(nameValue) || code,
};
};
const pairs = [];
const appendMapObject = source => {
if (!source || typeof source !== 'object' || Array.isArray(source)) {
return;
}
const preferredSource = source.desc && typeof source.desc === 'object' && !Array.isArray(source.desc)
? source.desc
: source;
for (const [ key, value ] of Object.entries(preferredSource)) {
if (value && typeof value === 'object' && !Array.isArray(value)) {
const nestedCode = String(value.code || value.value || key || '').trim();
const nestedName = String(value.name || value.label || value.desc || value.text || nestedCode || '').trim();
const pair = toPair(nestedCode, nestedName);
if (pair) {
pairs.push(pair);
}
continue;
}
const pair = toPair(key, value);
if (pair) {
pairs.push(pair);
}
}
};
const appendArray = source => {
if (!Array.isArray(source)) {
return;
}
for (const item of source) {
if (item && typeof item === 'object') {
const code = item.code || item.value || item.key || item.id || '';
const name = item.name || item.label || item.desc || item.text || item.title || code;
const pair = toPair(code, name);
if (pair) {
pairs.push(pair);
}
continue;
}
const text = String(item || '').trim();
if (!text) {
continue;
}
const splitIndex = text.indexOf(':') >= 0 ? text.indexOf(':') : text.indexOf('=');
if (splitIndex > 0) {
const pair = toPair(text.slice(0, splitIndex), text.slice(splitIndex + 1));
if (pair) {
pairs.push(pair);
}
continue;
}
const pair = toPair(text, text);
if (pair) {
pairs.push(pair);
}
}
};
try {
const parsed = JSON.parse(rawTypeDesc);
if (Array.isArray(parsed)) {
appendArray(parsed);
} else if (parsed && typeof parsed === 'object') {
appendMapObject(parsed);
}
} catch (error) {
const segments = rawTypeDesc.split(/[,,;;]+/).map(item => item.trim()).filter(Boolean);
appendArray(segments);
}
const dedupedMap = new Map();
for (const item of pairs) {
if (!item || !item.code) {
continue;
}
const existing = dedupedMap.get(item.code);
if (!existing || (!existing.name && item.name)) {
dedupedMap.set(item.code, item);
}
}
return Array.from(dedupedMap.values());
}
/**
* 从拼多多网点服务列表中提取顺丰定时派送产品类型。
*
* @param {Array<Object>} shopExpressList 店铺快递签约列表
* @return {Array<{ express_code: string, code: string, name: string }>} 可写入的产品类型列表
*/
collectPddSfTimedDeliveryProductTypes(shopExpressList = []) {
const result = [];
for (const expressItem of Array.isArray(shopExpressList) ? shopExpressList : []) {
const expressCode = this.normalizeExpressCodeKey(expressItem && expressItem.sys_express_code);
if (!this.isSfExpressCode(expressCode)) {
continue;
}
const accounts = Array.isArray(expressItem && expressItem.accounts) ? expressItem.accounts : [];
for (const account of accounts) {
const services = Array.isArray(account && account.services) ? account.services : [];
for (const serviceItem of services) {
const serviceCode = String(serviceItem && serviceItem.service_code || '').trim().toUpperCase();
if (serviceCode !== 'TIMED-DELIVERY') {
continue;
}
const attributes = Array.isArray(serviceItem && serviceItem.attributes) ? serviceItem.attributes : [];
for (const attribute of attributes) {
const typeDesc = attribute && attribute.type_desc;
const productTypeList = this.extractExpressProductTypesFromTypeDesc(typeDesc);
for (const productType of productTypeList) {
result.push({
express_code: expressCode,
code: String(productType.code || '').trim(),
name: String(productType.name || '').trim() || String(productType.code || '').trim(),
});
}
}
}
}
}
const dedupedMap = new Map();
for (const item of result) {
if (!item || !item.express_code || !item.code) {
continue;
}
const key = `${item.express_code}:${item.code}`;
const existed = dedupedMap.get(key);
if (!existed || (!existed.name && item.name)) {
dedupedMap.set(key, item);
}
}
return Array.from(dedupedMap.values());
}
/**
* 清理快递产品类型缓存。
*
* @param {string} expressCode 快递公司编码
* @return {Promise<void>} 无返回值
*/
async clearExpressProductTypeCache(expressCode = '') {
const cacheKeys = [ this.getExpressProductTypeListCacheKey() ];
const normalizedExpressCode = this.normalizeExpressCodeKey(expressCode);
if (normalizedExpressCode) {
cacheKeys.push(this.getExpressProductTypeListCacheKey(normalizedExpressCode));
}
for (const cacheKey of cacheKeys) {
if (!cacheKey) {
continue;
}
if (this.app && typeof this.app.delCacheAsync === 'function') {
await this.app.delCacheAsync(cacheKey);
} else if (this.app && typeof this.app.setCacheAsync === 'function') {
await this.app.setCacheAsync(cacheKey, null, 0);
}
}
}
/**
* 将快递产品类型列表幂等写入数据库。
*
* @param {Array<{ express_code: string, code: string, name: string }>} items 快递产品类型列表
* @return {Promise<{ createdCount: number, updatedCount: number }>} 写入结果
*/
async upsertExpressProductTypeList(items = []) {
const expressProductTypeModel = this.ctx.model && this.ctx.model.ExpressProductType;
if (!expressProductTypeModel || typeof expressProductTypeModel.findAll !== 'function') {
return { createdCount: 0, updatedCount: 0 };
}
const validItems = Array.isArray(items)
? items.filter(item => item && item.express_code && item.code)
: [];
if (validItems.length === 0) {
return { createdCount: 0, updatedCount: 0 };
}
const { Op } = this.app.Sequelize;
let createdCount = 0;
let updatedCount = 0;
const changedExpressCodeSet = new Set();
const groupedByExpressCode = validItems.reduce((result, item) => {
const expressCode = this.normalizeExpressCodeKey(item.express_code);
if (!expressCode) {
return result;
}
if (!result[expressCode]) {
result[expressCode] = [];
}
result[expressCode].push({
express_code: expressCode,
code: String(item.code || '').trim(),
name: String(item.name || '').trim() || String(item.code || '').trim(),
});
return result;
}, {});
for (const [ expressCode, groupItems ] of Object.entries(groupedByExpressCode)) {
const codeList = Array.from(new Set(groupItems.map(item => item.code).filter(Boolean)));
if (codeList.length === 0) {
continue;
}
const existedRows = await expressProductTypeModel.findAll({
attributes: [ 'id', 'express_code', 'code', 'name' ],
where: {
express_code: expressCode,
code: {
[Op.in]: codeList,
},
},
order: [[ 'id', 'ASC' ]],
raw: true,
});
const existedMap = new Map();
for (const row of Array.isArray(existedRows) ? existedRows : []) {
const rowCode = String(row && row.code || '').trim();
if (!rowCode || existedMap.has(rowCode)) {
continue;
}
existedMap.set(rowCode, row);
}
for (const item of groupItems) {
const existed = existedMap.get(item.code);
if (!existed) {
if (typeof expressProductTypeModel.create === 'function') {
await expressProductTypeModel.create({
express_code: expressCode,
code: item.code,
name: item.name,
});
createdCount += 1;
changedExpressCodeSet.add(expressCode);
}
continue;
}
const existedName = String(existed.name || '').trim();
if (item.name && item.name !== existedName && typeof expressProductTypeModel.update === 'function') {
await expressProductTypeModel.update({
name: item.name,
}, {
where: {
id: existed.id,
},
});
updatedCount += 1;
changedExpressCodeSet.add(expressCode);
}
}
}
if (changedExpressCodeSet.size > 0) {
await this.clearExpressProductTypeCache();
for (const expressCode of changedExpressCodeSet) {
await this.clearExpressProductTypeCache(expressCode);
}
}
return {
createdCount,
updatedCount,
};
}
/**
* 同步拼多多顺丰定时派送服务中的快递产品类型。
*
* 仅处理 service_code 为 TIMED-DELIVERY 且系统快递编码为 SF/SHUNFENG 的数据。
*
* @param {Object} payload 入参
* @param {Array<Object>} payload.shopExpressList 店铺快递签约列表
* @return {Promise<{ createdCount: number, updatedCount: number, parsedCount: number }>} 同步结果
*/
async syncPddSfTimedDeliveryExpressProductTypes(payload = {}) {
const { shopExpressList = [] } = payload && typeof payload === 'object' ? payload : {};
const productTypeList = this.collectPddSfTimedDeliveryProductTypes(shopExpressList);
if (productTypeList.length === 0) {
return {
createdCount: 0,
updatedCount: 0,
parsedCount: 0,
};
}
const upsertResult = await this.upsertExpressProductTypeList(productTypeList);
return {
createdCount: Number(upsertResult.createdCount || 0),
updatedCount: Number(upsertResult.updatedCount || 0),
parsedCount: productTypeList.length,
};
}
normalizeExpressRow(row) {
if (!row || typeof row !== 'object') {
return null;
@ -973,15 +1398,19 @@ class ExpressService extends Service {
/**
* 获取快递列表。
*
* 默认先读取系统快递,再按当前仓库合并快递设置;同一编码只保留一条记录。
* systemOnly 为 true 时仅返回系统快递列表。
* 默认先读取系统快递,再按当前仓库合并快递设置;同一编码只保留一条记录。
* systemOnly 为 true 时仅返回系统快递列表。
*
* @param {boolean} [systemOnly=false] 是否仅返回系统基础快递列表
* 当传入系统快递编码时,按当前仓库与 `express_code` 字段仅返回对应自定义编码列表。
*
* @param {boolean} [systemOnly=false] 是否仅返回系统基础快递列表
* @param {string} [systemExpressCode=''] 系统快递编码
* @return {Promise<Array>} 快递列表
*/
async getExpressList(systemOnly = false) {
async getExpressList(systemOnly = false, systemExpressCode = '') {
const warehouseId = this.getCurrentWarehouseId();
const cacheKey = this.getExpressListCacheKey(warehouseId, systemOnly);
const normalizedExpressCode = String(systemExpressCode || '').trim().toUpperCase();
const cacheKey = this.getExpressListCacheKey(warehouseId, systemOnly, normalizedExpressCode);
try {
const cachedList = await this.app.getCacheAsync(cacheKey);
@ -991,15 +1420,24 @@ class ExpressService extends Service {
if (systemOnly) {
const expressList = await this.getSystemExpressList();
await this.app.setCacheAsync(cacheKey, expressList, DEFAULT_CACHE_TTL_SECONDS);
return expressList;
const filteredExpressList = normalizedExpressCode
? expressList.filter(item => String(item && (item.code || item.value) || '').trim().toUpperCase() === normalizedExpressCode)
: expressList;
await this.app.setCacheAsync(cacheKey, filteredExpressList, DEFAULT_CACHE_TTL_SECONDS);
return filteredExpressList;
}
const [ expressList, expressSettingList ] = await Promise.all([
this.loadExpressListFromDatabase(),
this.loadExpressSettingListFromDatabase(warehouseId),
this.loadExpressSettingListFromDatabase(warehouseId, normalizedExpressCode),
]);
if (normalizedExpressCode) {
const customCodeList = this.buildExpressSettingCustomCodeList(expressList, expressSettingList);
await this.app.setCacheAsync(cacheKey, customCodeList, DEFAULT_CACHE_TTL_SECONDS);
return customCodeList;
}
const mergedList = this.buildMergedExpressList(expressList, expressSettingList);
await this.app.setCacheAsync(cacheKey, mergedList, DEFAULT_CACHE_TTL_SECONDS);
@ -1113,6 +1551,59 @@ class ExpressService extends Service {
return batches;
}
/**
* 从仓库+平台接口配置列表中按订单分组快递编码选择可用配置。
*
* 匹配字段顺序:sys_express_code -> express_code -> express[platform_code]。
* 比对时统一去空格并转小写,匹配命中后按原列表顺序返回首条。
*
* @param {Array<Object>} interfaceList 接口配置列表。
* @param {Object} groupedOrder 订单分组信息。
* @param {Object} matchedPlatform 平台配置。
* @return {Object|null} 匹配到的接口配置,未匹配返回 null。
*/
pickWaybillExpressInterface(interfaceList = [], groupedOrder = {}, matchedPlatform = null) {
const normalizeCode = value => String(value || '').trim().toLowerCase();
const logisticsCode = normalizeCode(
groupedOrder
&& groupedOrder.options
&& groupedOrder.options.logistics_code
);
if (!logisticsCode) {
return null;
}
const platformCode = normalizeCode(
matchedPlatform
&& matchedPlatform.code
|| groupedOrder
&& groupedOrder.options
&& groupedOrder.options.sys_platform_code
);
for (const item of Array.isArray(interfaceList) ? interfaceList : []) {
if (!item || typeof item !== 'object') {
continue;
}
const candidateCodes = [
normalizeCode(item.sys_express_code),
normalizeCode(item.express_code),
];
const expressMap = item.express && typeof item.express === 'object' ? item.express : null;
if (expressMap && platformCode) {
candidateCodes.push(normalizeCode(expressMap[platformCode]));
}
if (candidateCodes.some(code => code && code === logisticsCode)) {
return item;
}
}
return null;
}
/**
* 解析运单后处理可用的平台编码。
*
@ -1451,6 +1942,20 @@ class ExpressService extends Service {
};
}
/**
* 判断异步取号平台是否需要逐单分发。
*
* 当前菜鸟、拼多多平台要求按单请求,避免整批订单透传到平台侧。
*
* @param {string} platformCode 平台编码。
* @return {boolean} 是否逐单分发。
*/
shouldDispatchWaybillAsyncPerOrder(platformCode = '') {
const normalizedPlatformCode = String(platformCode || '').trim().toLowerCase();
return WAYBILL_ASYNC_SINGLE_ORDER_PLATFORM_CODES.has(normalizedPlatformCode);
}
/**
* 将统一业务数据骨架按平台编码分流。
*
@ -1458,6 +1963,7 @@ class ExpressService extends Service {
*
* @param {string} platformCode 平台编码。
* @param {Object} bizcontent 统一业务数据骨架。
* @return {Promise<void>} 无返回值。
*/
async dispatchWaybillAsyncPlatform(platformCode = '', bizcontent = {}) {
const normalizedPlatformCode = String(platformCode).trim().toLowerCase();
@ -1469,12 +1975,43 @@ class ExpressService extends Service {
if (typeof dispatchMethod !== 'function') {
throw new Error(normalizedPlatformCode + '接口未实现');
}
const dispatchResult = await dispatchMethod.call(expressPlatformService, bizcontent);
if (dispatchResult && typeof dispatchResult === 'object' && dispatchResult.flag === 'failure') {
throw new Error(dispatchResult.message || normalizedPlatformCode + '接口调用失败');
const normalizedOrders = Array.isArray(bizcontent && bizcontent.orders)
? bizcontent.orders
: [];
const dispatchPayloads = this.shouldDispatchWaybillAsyncPerOrder(normalizedPlatformCode) && normalizedOrders.length > 1
? normalizedOrders.map(order => ({
...bizcontent,
orders: [ order ],
}))
: [ bizcontent ];
for (const payload of dispatchPayloads) {
const dispatchResult = await dispatchMethod.call(expressPlatformService, payload);
if (dispatchResult && typeof dispatchResult === 'object' && dispatchResult.flag === 'failure') {
throw new Error(dispatchResult.message || normalizedPlatformCode + '接口调用失败');
}
}
}
/**
* 解析运单后处理分发平台编码。
*
* 优先使用平台路由编码,未提供时兼容历史字段。
*
* @param {Object} [matchedPlatform={}] 平台匹配信息。
* @return {string} 后处理分发平台编码。
*/
resolveWaybillAsyncDispatchPlatformCode(matchedPlatform = {}) {
return String(
matchedPlatform.route_platform_code
|| matchedPlatform.platform_code
|| matchedPlatform.code
|| matchedPlatform.default_express_interface
|| ''
).trim();
}
/**
* 硬删除运单异步失败分组对应的订单快递记录。
@ -1651,21 +2188,37 @@ class ExpressService extends Service {
for (const groupedOrder of groupedOrders) {
const matchedPlatform = platformList.find(platform => String(platform.code || '').trim().toLowerCase() === String(groupedOrder.options.sys_platform_code || '').trim().toLowerCase());
const batches = this.splitWaybillOrdersIntoBatches(groupedOrder.orders);
const listByWarehousePlatformCode = await this.service.systems.setting.expressInterface.listByWarehousePlatformCode({ warehouseId, platform_code: groupedOrder.options.sys_platform_code });
const expressInterfacePlatformCode = String(
matchedPlatform && matchedPlatform.default_express_interface
|| groupedOrder.options.sys_platform_code
|| ''
).trim();
const listByWarehousePlatformCode = expressInterfacePlatformCode
? await this.service.systems.setting.expressInterface.listByWarehousePlatformCode({
warehouseId,
platform_code: expressInterfacePlatformCode,
})
: { data: [] };
const expressInterface = this.pickWaybillExpressInterface(
listByWarehousePlatformCode && listByWarehousePlatformCode.data,
groupedOrder,
matchedPlatform
);
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 分组前置条件检查', {
traceId,
warehouseId,
storeId: groupedOrder.options.store_id || 0,
sysPlatformCode: groupedOrder.options.sys_platform_code,
expressInterfacePlatformCode,
logisticsCode: groupedOrder.options.logistics_code,
matchedPlatformCode: matchedPlatform && matchedPlatform.code,
hasExpressInterface: Boolean(listByWarehousePlatformCode && listByWarehousePlatformCode.data && listByWarehousePlatformCode.data[0]),
hasExpressInterface: Boolean(expressInterface),
});
const expressInterface = listByWarehousePlatformCode.data[0];
// 发件人相关字段统一走接口配置,货主配置仅用于打印链路。
const expressInterfaceConfig = expressInterface ? {
...expressInterface,
} : null;
for (const batch of batches) {
// 异步不阻塞调用 createWaybillCode,快速返回结果给前端,后续的订单处理和异常回写都在 createWaybillCode 内部完成。
this.asyncTask(batch, {
@ -1790,6 +2343,7 @@ class ExpressService extends Service {
orderCount: Array.isArray(orders) ? orders.length : 0,
orderIds: (Array.isArray(orders) ? orders : []).slice(0, 50).map(order => Number(order && (order.id || order.order_id))).filter(orderId => Number.isFinite(orderId) && orderId > 0),
platformCode: matchedPlatform && matchedPlatform.code,
routePlatformCode: this.resolveWaybillAsyncDispatchPlatformCode(matchedPlatform),
defaultExpressInterface: matchedPlatform && matchedPlatform.default_express_interface,
warehouseId: listByWarehousePlatformCode && listByWarehousePlatformCode.warehouse_id,
});
@ -2107,17 +2661,18 @@ class ExpressService extends Service {
});
try {
const dispatchPlatformCode = this.resolveWaybillAsyncDispatchPlatformCode(matchedPlatform);
if (Array.isArray(createWaybillResult.orders)
&& createWaybillResult.orders.length > 0
&& matchedPlatform
&& matchedPlatform.default_express_interface) {
&& dispatchPlatformCode) {
try {
this.ctx.logger.info('[ExpressService.createWaybillCode] 平台后处理调用前', {
traceId,
platformInterface: matchedPlatform.default_express_interface,
platformInterface: dispatchPlatformCode,
orderCount: createWaybillResult.orders.length,
});
await this.dispatchWaybillAsyncPlatform(matchedPlatform.default_express_interface, {
await this.dispatchWaybillAsyncPlatform(dispatchPlatformCode, {
matchedPlatform,
listByWarehousePlatformCode,
orders: createWaybillResult.orders,
@ -2125,7 +2680,7 @@ class ExpressService extends Service {
});
this.ctx.logger.info('[ExpressService.createWaybillCode] 平台后处理调用后', {
traceId,
platformInterface: matchedPlatform.default_express_interface,
platformInterface: dispatchPlatformCode,
});
} catch (error) {
throw error;

View File

@ -4,6 +4,94 @@ const MainService = require('../main');
const PddClient = require('../../lib/pdd_client');
const DEFAULT_PDD_ROUTER_URL = 'https://gw-api.pinduoduo.com/api/router';
const DEFAULT_TB_ROUTER_URL = 'https://eco.taobao.com/router/rest';
/**
* 将任意值标准化为数组。
*
* @param {*} value 原始值。
* @return {Array} 标准化后的数组。
*/
function normalizeArray(value) {
return Array.isArray(value) ? value : [];
}
/**
* 将对象包裹的集合字段标准化为数组。
*
* @param {*} value 原始集合值。
* @param {Array<string>} [nestedKeys=[]] 对象包裹时的候选子字段名。
* @return {Array} 标准化后的数组。
*/
function normalizeWrappedArray(value, nestedKeys = []) {
if (Array.isArray(value)) {
return value;
}
if (!value || typeof value !== 'object') {
return [];
}
for (const nestedKey of normalizeArray(nestedKeys)) {
if (!nestedKey || !Object.prototype.hasOwnProperty.call(value, nestedKey)) {
continue;
}
const nestedValue = value[nestedKey];
if (Array.isArray(nestedValue)) {
return nestedValue;
}
if (nestedValue !== null && nestedValue !== undefined) {
return [ nestedValue ];
}
}
return Object.keys(value).length > 0 ? [ value ] : [];
}
/**
* 按候选来源顺序提取首个非空集合。
*
* @param {Array<*>} values 候选来源列表。
* @param {Array<string>} [nestedKeys=[]] 对象包裹时的候选子字段名。
* @return {Array} 首个非空数组。
*/
function normalizeFirstWrappedArray(values, nestedKeys = []) {
for (const value of normalizeArray(values)) {
const normalized = normalizeWrappedArray(value, nestedKeys);
if (normalized.length > 0) {
return normalized;
}
}
return [];
}
/**
* 校验菜鸟电子面单模板地址是否合法。
*
* 仅允许下发 `http` 或 `https` 协议的完整 URL,非法值直接视为不可用。
*
* @param {*} templateUrl 待校验的模板地址。
* @return {boolean} 是否为合法模板地址。
*/
function isValidCainiaoTemplateUrl(templateUrl) {
const normalizedTemplateUrl = String(templateUrl || '').trim();
if (!normalizedTemplateUrl) {
return false;
}
try {
const parsedTemplateUrl = new URL(normalizedTemplateUrl);
return parsedTemplateUrl.protocol === 'http:' || parsedTemplateUrl.protocol === 'https:';
} catch {
return false;
}
}
const DEFAULT_CAINIAO_TEMPLATE_URL = 'http://cloudprint.cainiao.com/cloudprint/template/getStandardTemplate.json?template_id=288948';
/**
* 快递平台服务类。
@ -196,6 +284,31 @@ class ExpressPlatformService extends MainService {
};
}
/**
* 从候选来源中提取可落库的打印版本号字段。
*
* 仅当上游明确返回 ver 且非空字符串时返回 `{ ver }`,
* 避免在回写时写入默认值或覆盖已有有效值。
*
* @param {Array<*>} candidates 候选来源列表。
* @return {{ver?: string}} 可直接合并到 OrderExpress.update 的字段补丁。
*/
buildOrderExpressVerPatch(candidates = []) {
const normalizedCandidates = Array.isArray(candidates) ? candidates : [ candidates ];
for (const candidate of normalizedCandidates) {
if (candidate === null || candidate === undefined) {
continue;
}
const normalized = String(candidate).trim();
if (normalized) {
return {
ver: normalized,
};
}
}
return {};
}
/**
* 构建快递平台链路追踪ID。
*
@ -434,6 +547,7 @@ class ExpressPlatformService extends MainService {
printinfo: item.printinfo,
signature: item.signature,
encryptprintinfo: item.encryptprintinfo,
...this.buildOrderExpressVerPatch([ item.ver ]),
create_at: new Date(),
logistics_code: listByWarehousePlatformCode.logistics_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
@ -464,6 +578,7 @@ class ExpressPlatformService extends MainService {
signature: item.signature,
encryptedtoken: item.encryptedtoken,
encryptprintinfo: item.encryptprintinfo,
...this.buildOrderExpressVerPatch([ item.ver ]),
create_at: new Date(),
logistics_code: listByWarehousePlatformCode.logistics_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
@ -497,6 +612,7 @@ class ExpressPlatformService extends MainService {
signature: item.signature,
encryptedtoken: item.encryptedtoken,
encryptprintinfo: item.encryptprintinfo,
...this.buildOrderExpressVerPatch([ item.ver ]),
create_at: new Date(),
logistics_code: listByWarehousePlatformCode.logistics_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
@ -744,11 +860,540 @@ class ExpressPlatformService extends MainService {
* 菜鸟数据处理接口。
*
* @param {Object} [data={}] 平台业务入参。
* @return {Promise<never>} 当前暂未实现,直接抛出异常。
* @return {Promise<Object>} 处理结果。
*/
async cainiao(data = {}) {
void data;
throw new Error('菜鸟平台接口未实现');
const {
matchedPlatform = {},
listByWarehousePlatformCode = {},
orders = [],
} = data && typeof data === 'object' ? data : {};
const normalizedOrders = Array.isArray(orders) ? orders : [];
const normalizedExtData = this.normalizePddExtData(listByWarehousePlatformCode.ext_data);
const qimenConfig = this.app.config && this.app.config.qimen ? this.app.config.qimen : {};
const appKey = String(qimenConfig.appKey || '').trim();
const appSecret = String(qimenConfig.security || '').trim();
const signService = this.service && this.service.systems ? this.service.systems.sign : null;
const normalizedTemplateUrl = isValidCainiaoTemplateUrl(matchedPlatform.template_url)
? String(matchedPlatform.template_url).trim()
: DEFAULT_CAINIAO_TEMPLATE_URL;
if (!appKey || !appSecret) {
throw new Error('淘宝接口配置缺失');
}
if (!signService || typeof signService.signTopRequest !== 'function') {
throw new Error('签名服务不可用');
}
const tradeOrderList = normalizedOrders.map(
order_tmp => {
const orderDelivery = order_tmp && order_tmp.order_delivery ? order_tmp.order_delivery : {};
const sourceOrderCodes = orderDelivery && orderDelivery.source_order_codes
? String(orderDelivery.source_order_codes)
.split(',')
.map(item => String(item || '').trim())
.filter(Boolean)
: [];
const recipientMobile = orderDelivery && (orderDelivery.mobile || orderDelivery.tel) || '';
const tradeOrderInfo = {
logistics_services: normalizedExtData,
object_id: `${orderDelivery.warehouse_id}_${orderDelivery.id}_${order_tmp.business_key}`,
order_info: {
order_channels_type: String(
orderDelivery.sys_platform_code
|| order_tmp.sys_platform_code
|| matchedPlatform.platform_code
|| listByWarehousePlatformCode.platform_code
|| 'CAINIAO'
).trim() || 'CAINIAO',
trade_order_list: sourceOrderCodes.length > 0
? sourceOrderCodes
: [ orderDelivery && orderDelivery.delivery_order_code || '' ],
},
package_info: {
items: (orderDelivery && orderDelivery.orderItems || []).map(item => ({
name: item.item_name,
count: item.plan_qty,
})) || [],
goods_description: '物品',
},
recipient: {
address: {
country: '中国',
city: orderDelivery && orderDelivery.city || '',
province: orderDelivery && orderDelivery.province || '',
district: orderDelivery && orderDelivery.area || '',
town: orderDelivery && orderDelivery.town || null,
detail: orderDelivery && orderDelivery.detail_address || '',
},
mobile: recipientMobile,
name: orderDelivery && orderDelivery.name || '',
phone: recipientMobile,
oaid: orderDelivery && orderDelivery.oaid || '',
tid: sourceOrderCodes[0] || '',
},
user_id: listByWarehousePlatformCode.shop && listByWarehousePlatformCode.shop.owner_id || 0,
notify_extend_info: normalizedExtData,
};
tradeOrderInfo.template_url = listByWarehousePlatformCode.template_url;
return tradeOrderInfo;
}
);
const cainiaoPayload = {
param_waybill_cloud_print_apply_new_request: {
cp_code: listByWarehousePlatformCode && listByWarehousePlatformCode.express
? (listByWarehousePlatformCode.express.CAINIAO || listByWarehousePlatformCode.express.cainiao_code || '')
: '',
product_code: String(listByWarehousePlatformCode.product_type || '').trim(),
sender: {
address: {
city: listByWarehousePlatformCode.city_name,
detail: listByWarehousePlatformCode.address,
district: listByWarehousePlatformCode.district_name,
province: listByWarehousePlatformCode.province_name,
town: listByWarehousePlatformCode.town_name || null,
},
mobile: listByWarehousePlatformCode.sender_tel,
name: listByWarehousePlatformCode.sender_name,
phone: listByWarehousePlatformCode.sender_tel,
},
trade_order_info_dtos: tradeOrderList,
brand_code: String(listByWarehousePlatformCode.site_code || 'default').trim(),
need_encrypt: true,
customer_code: String(
listByWarehousePlatformCode.customer_code
|| listByWarehousePlatformCode.client_id
|| listByWarehousePlatformCode.shipperno
|| ''
).trim(),
shipping_branch_code: String(listByWarehousePlatformCode.site_code || '').trim(),
},
};
console.log('cainiaoPayload', JSON.stringify(cainiaoPayload));
const requestParams = {
method: 'cainiao.waybill.ii.get',
app_key: appKey,
session: String(listByWarehousePlatformCode.token || '').trim(),
timestamp: this.app.formatDate(new Date()),
format: 'json',
v: '2.0',
sign_method: 'md5',
param_waybill_cloud_print_apply_new_request: JSON.stringify(
cainiaoPayload.param_waybill_cloud_print_apply_new_request
),
};
const sign = signService.signTopRequest(requestParams, '', appSecret, 'md5');
const response = await this.ctx.curl(DEFAULT_TB_ROUTER_URL, {
method: 'POST',
contentType: 'form',
dataType: 'json',
data: {
...requestParams,
sign,
},
});
console.log('菜鸟取号返回数据', JSON.stringify(response));
const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data')
? response.data
: response;
if (responseData && typeof responseData === 'object' && responseData.error_response) {
const errorResponse = responseData.error_response;
throw new Error(errorResponse.sub_msg || errorResponse.msg || '菜鸟平台接口调用失败');
}
const responseRoot = responseData && responseData.cainiao_waybill_ii_get_response
? responseData.cainiao_waybill_ii_get_response
: {};
const modules = normalizeFirstWrappedArray([
responseRoot.modules,
responseRoot.waybill_cloud_print_response_infos,
responseRoot.waybill_cloud_print_response_list,
responseRoot.waybill_cloud_print_response,
], [ 'waybill_cloud_print_response', 'modules', 'module', 'waybill_cloud_print_response_info' ]);
if (modules.length === 0) {
throw new Error('菜鸟平台接口返回数据为空');
}
if (modules.length !== normalizedOrders.length) {
throw new Error(`菜鸟平台接口返回数量异常: 请求 ${normalizedOrders.length} 条, 返回 ${modules.length} 条`);
}
const requestedObjectIdSet = new Set(normalizedOrders.map(order => {
const orderDelivery = order && order.order_delivery ? order.order_delivery : {};
return `${orderDelivery.warehouse_id}_${orderDelivery.id}_${order.business_key}`;
}));
const receivedObjectIdSet = new Set();
const successUpdates = modules.map(moduleItem => {
const objectId = String(moduleItem && moduleItem.object_id || '').trim();
if (!objectId || !requestedObjectIdSet.has(objectId)) {
throw new Error(`菜鸟平台接口返回 object_id 异常: ${objectId || 'empty'}`);
}
if (receivedObjectIdSet.has(objectId)) {
throw new Error(`菜鸟平台接口返回重复 object_id: ${objectId}`);
}
receivedObjectIdSet.add(objectId);
const [ warehouseId, orderId, businessKey ] = objectId.split('_');
const waybillCode = String(moduleItem && (moduleItem.parent_waybill_code || moduleItem.waybill_code) || '').trim();
if (!waybillCode) {
throw new Error(`菜鸟平台接口返回运单号为空: ${objectId}`);
}
const rawPrintData = moduleItem && Object.prototype.hasOwnProperty.call(moduleItem, 'print_data')
? moduleItem.print_data
: moduleItem && Object.prototype.hasOwnProperty.call(moduleItem, 'printData')
? moduleItem.printData
: null;
const parsedPrintData = this.parsePlatformPrintData(rawPrintData, '菜鸟', objectId);
const persistedPrintData = this.stringifyPlatformPrintData(rawPrintData, parsedPrintData);
if (!persistedPrintData) {
throw new Error(`菜鸟平台接口返回 print_data 为空: ${objectId}`);
}
const parsedPrintDataRoot = parsedPrintData && typeof parsedPrintData === 'object' ? parsedPrintData : {};
const printDataContent = parsedPrintDataRoot.data && typeof parsedPrintDataRoot.data === 'object'
? parsedPrintDataRoot.data
: {};
const extraInfo = printDataContent.extraInfo && typeof printDataContent.extraInfo === 'object'
? printDataContent.extraInfo
: {};
const orderExpressVerPatch = this.buildOrderExpressVerPatch([
moduleItem && moduleItem.ver,
parsedPrintDataRoot.ver,
printDataContent.ver,
extraInfo.ver,
]);
const signature = String(
parsedPrintDataRoot.signature
|| printDataContent.signature
|| extraInfo.signature
|| moduleItem && moduleItem.signature
|| ''
).trim() || null;
const encryptPrintInfo = String(
parsedPrintDataRoot.encryptedData
|| parsedPrintDataRoot.key
|| printDataContent.encryptedData
|| printDataContent.encryptWaybillCode
|| extraInfo.encryptWaybillCode
|| extraInfo.key
|| moduleItem && (moduleItem.encrypt_waybill_code || moduleItem.encryptprintinfo)
|| ''
).trim() || null;
return {
warehouse_id: Number(warehouseId) || 0,
order_id: Number(orderId) || 0,
business_key: Number(businessKey) || 0,
waybill_code: waybillCode,
orderExpressValues: {
waybill_code: waybillCode,
printinfo: persistedPrintData,
signature,
encryptprintinfo: encryptPrintInfo,
...orderExpressVerPatch,
create_at: new Date(),
logistics_code: listByWarehousePlatformCode.logistics_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: listByWarehousePlatformCode.logistics_name || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
retry_count: 0,
},
orderDeliveryValues: {
post_status: 'fin',
order_flag: '',
},
};
});
await this.persistWaybillSuccessUpdates(successUpdates, normalizedOrders);
return {
flag: true,
code: 0,
message: '菜鸟平台数据处理成功',
data: responseData,
};
}
/**
* 解析平台返回的打印数据结构。
*
* @param {*} rawPrintData 平台原始打印数据。
* @param {string} platformName 平台名称。
* @param {string} objectId 请求对象标识。
* @return {Object|null} 解析后的打印数据对象。
*/
parsePlatformPrintData(rawPrintData, platformName, objectId) {
if (rawPrintData === null || rawPrintData === undefined || rawPrintData === '') {
return null;
}
if (typeof rawPrintData === 'string') {
try {
return JSON.parse(rawPrintData);
} catch (error) {
throw new Error(`${platformName}平台接口返回 print_data 解析失败: ${objectId}`);
}
}
if (typeof rawPrintData === 'object') {
return rawPrintData;
}
throw new Error(`${platformName}平台接口返回 print_data 结构异常: ${objectId}`);
}
/**
* 将平台打印数据标准化为可落库的字符串。
*
* @param {*} rawPrintData 平台原始打印数据。
* @param {Object|null} parsedPrintData 解析后的打印数据对象。
* @return {string|null} 可落库字符串。
*/
stringifyPlatformPrintData(rawPrintData, parsedPrintData) {
if (typeof rawPrintData === 'string') {
return rawPrintData.trim() || null;
}
const dataToPersist = parsedPrintData !== undefined ? parsedPrintData : rawPrintData;
if (dataToPersist === null || dataToPersist === undefined || dataToPersist === '') {
return null;
}
if (typeof dataToPersist === 'object') {
return JSON.stringify(dataToPersist);
}
return String(dataToPersist).trim() || null;
}
/**
* 构建订单与货主仓库关系映射。
*
* @param {Array} orders 订单列表。
* @return {Map<string, {store_id: number, warehouse_id: number}>} 订单元数据映射。
*/
buildWaybillOrderMetaMap(orders = []) {
const orderMetaMap = new Map();
for (const order of Array.isArray(orders) ? orders : []) {
const orderDelivery = order && order.order_delivery ? order.order_delivery : {};
const warehouseId = Number(orderDelivery && orderDelivery.warehouse_id) || 0;
const orderId = Number(orderDelivery && orderDelivery.id) || 0;
const businessKey = Number(order && order.business_key) || 0;
if (!warehouseId || !orderId || !businessKey) {
continue;
}
orderMetaMap.set(`${warehouseId}_${orderId}_${businessKey}`, {
store_id: Number(orderDelivery && orderDelivery.store_id) || 0,
warehouse_id: warehouseId,
});
}
return orderMetaMap;
}
/**
* 按货主仓库聚合成功获取面单的扣减数量。
*
* @param {Array} successUpdates 成功回写项。
* @param {Map<string, {store_id: number, warehouse_id: number}>} orderMetaMap 订单元数据映射。
* @return {Map<string, {store_id: number, warehouse_id: number, success_count: number}>} 聚合结果。
*/
buildWaybillSettlementRelationMap(successUpdates = [], orderMetaMap = new Map()) {
const settlementRelationMap = new Map();
for (const item of Array.isArray(successUpdates) ? successUpdates : []) {
const relationMeta = orderMetaMap.get(`${item.warehouse_id}_${item.order_id}_${item.business_key}`);
if (!relationMeta || !relationMeta.store_id || !relationMeta.warehouse_id) {
continue;
}
const relationKey = `${relationMeta.store_id}:${relationMeta.warehouse_id}`;
const currentRelation = settlementRelationMap.get(relationKey) || {
store_id: relationMeta.store_id,
warehouse_id: relationMeta.warehouse_id,
success_count: 0,
};
currentRelation.success_count += 1;
settlementRelationMap.set(relationKey, currentRelation);
}
return settlementRelationMap;
}
/**
* 回写成功获取的面单结果,并扣减打印余量与写入操作日志。
*
* @param {Array} successUpdates 成功回写项。
* @param {Array} orders 请求订单列表。
* @return {Promise<void>} 无返回值。
*/
async persistWaybillSuccessUpdates(successUpdates = [], orders = []) {
const normalizedSuccessUpdates = Array.isArray(successUpdates) ? successUpdates : [];
if (normalizedSuccessUpdates.length === 0) {
return;
}
const orderMetaMap = this.buildWaybillOrderMetaMap(orders);
const settlementRelationMap = this.buildWaybillSettlementRelationMap(normalizedSuccessUpdates, orderMetaMap);
const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse;
if (typeof this.ctx.model.transaction === 'function') {
await this.ctx.model.transaction(async transaction => {
for (const item of normalizedSuccessUpdates) {
if (!item.warehouse_id || !item.order_id || !item.business_key) {
throw new Error('平台接口返回 object_id 无法解析');
}
await this.ctx.model.OrderExpress.update(item.orderExpressValues, {
where: {
order_id: item.order_id,
business_key: item.business_key,
warehouse_id: item.warehouse_id,
},
transaction,
});
const orderModel = await this.service.systems.express.getWaybillAsyncOrderDeliveryModel(item.warehouse_id);
if (item.orderDeliveryValues && orderModel && typeof orderModel.update === 'function') {
await orderModel.update(item.orderDeliveryValues, {
where: {
id: item.order_id,
},
transaction,
});
}
}
if (storeWarehouseModel
&& typeof storeWarehouseModel.findAll === 'function'
&& settlementRelationMap.size > 0) {
const { Op } = this.app.Sequelize;
const relationList = Array.from(settlementRelationMap.values());
const relationRows = await storeWarehouseModel.findAll({
attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked' ],
where: {
[Op.or]: relationList.map(item => ({
store_id: item.store_id,
warehouse_id: item.warehouse_id,
})),
},
raw: true,
transaction,
lock: transaction.LOCK.UPDATE,
});
const relationRowMap = new Map();
for (const row of Array.isArray(relationRows) ? relationRows : []) {
const relationKey = `${Number(row && row.store_id) || 0}:${Number(row && row.warehouse_id) || 0}`;
if (relationKey !== '0:0') {
relationRowMap.set(relationKey, row);
}
}
for (const item of relationList) {
const relationKey = `${item.store_id}:${item.warehouse_id}`;
const row = relationRowMap.get(relationKey);
if (!row) {
continue;
}
const currentPrintQuantity = Number(row.print_quantity || 0);
const currentLockedQuantity = Math.max(0, Number(row.print_quantity_locked || 0));
const successCount = Number(item.success_count || 0);
if (successCount <= 0) {
continue;
}
const printDecrement = successCount;
const lockedDecrement = Math.min(currentLockedQuantity, printDecrement);
const nextPrintQuantity = currentPrintQuantity - printDecrement;
const nextLockedQuantity = Math.max(0, currentLockedQuantity - lockedDecrement);
await storeWarehouseModel.update({
print_quantity: nextPrintQuantity,
print_quantity_locked: nextLockedQuantity,
}, {
where: {
id: row.id,
},
transaction,
});
await this.ctx.model.StoreWarehousePrintQuantityLog.create({
contract_id: Number(row.id || 0),
store_id: Number(row.store_id || 0),
warehouse_id: Number(row.warehouse_id || 0),
change_type: 'order_deduct',
business_type: 'order_express',
business_id: null,
change_quantity: -printDecrement,
balance_before: Math.max(0, currentPrintQuantity),
balance_after: Math.max(0, nextPrintQuantity),
reason: '获取快递号成功扣减',
operator_id: null,
created_by: null,
}, {
transaction,
});
}
}
});
}
const operationLogService = this.service && this.service.systems && this.service.systems.operationLog;
const operator = this.getOrderLogOperator();
const logPayloads = normalizedSuccessUpdates
.filter(item => item.warehouse_id && item.order_id)
.map(item => ({
businessType: 'order',
businessId: `${item.order_id}`,
operationCode: 'WAYBILL',
operator,
extras: {
message: `订单${item.order_id}获取快递单成功,单号:${item.waybill_code}`,
warehouseId: item.warehouse_id,
externalLogType: 'API',
},
}));
if (operationLogService && typeof operationLogService.createOperationLogs === 'function' && logPayloads.length > 0) {
await operationLogService.createOperationLogs(logPayloads);
}
}
/**
* 规范化拼多多接口要求的扩展字段字符串。
*
* @param {*} value 扩展字段原始值。
* @return {string} 规范化后的字符串。
*/
normalizePddExtData(value) {
if (value === null || value === undefined || value === '') {
return '';
}
if (typeof value === 'string') {
return value.trim();
}
if (typeof value === 'object') {
return JSON.stringify(value);
}
return String(value);
}
/**
@ -764,69 +1409,69 @@ class ExpressPlatformService extends MainService {
orders = [],
} = data && typeof data === 'object' ? data : {};
const normalizedOrders = Array.isArray(orders) ? orders : [];
const normalizedExtData = this.normalizePddExtData(listByWarehousePlatformCode.ext_data);
console.log('拼多多平台接口入参', data);
const tradeOrderList = normalizedOrders.map(
order_tmp => {
return {
logistics_services:listByWarehousePlatformCode.ext_data || "",
notify_extend_info: listByWarehousePlatformCode.ext_data || "",
logistics_services: normalizedExtData,
object_id: `${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}`,
order_info:{
order_channels_type:"PDD",
trade_order_list:order_tmp.order_delivery && order_tmp.order_delivery.source_order_codes ? order_tmp.order_delivery.source_order_codes.split(',') : [order_tmp.order_delivery && order_tmp.order_delivery.delivery_order_code || ''],
order_info: {
order_channels_type: 'PDD',
trade_order_list: order_tmp.order_delivery && order_tmp.order_delivery.source_order_codes ? order_tmp.order_delivery.source_order_codes.split(',') : [ order_tmp.order_delivery && order_tmp.order_delivery.delivery_order_code || '' ],
},
package_info:{
package_info: {
items: (order_tmp.order_delivery && order_tmp.order_delivery.orderItems || []).map(item => ({
name: item.item_name,
count: item.plan_qty,
})) || [],
},
recipient:{
address:{
country:'中国',
city:order_tmp.order_delivery && order_tmp.order_delivery.city || '',
province:order_tmp.order_delivery && order_tmp.order_delivery.province || '',
district:order_tmp.order_delivery && order_tmp.order_delivery.area || '',
town:order_tmp.order_delivery && order_tmp.order_delivery.town || null,
detail:order_tmp.order_delivery && order_tmp.order_delivery.detail_address || '',
recipient: {
address: {
country: '中国',
city: order_tmp.order_delivery && order_tmp.order_delivery.city || '',
province: order_tmp.order_delivery && order_tmp.order_delivery.province || '',
district: order_tmp.order_delivery && order_tmp.order_delivery.area || '',
town: order_tmp.order_delivery && order_tmp.order_delivery.town || null,
detail: order_tmp.order_delivery && order_tmp.order_delivery.detail_address || '',
},
moblie:order_tmp.order_delivery && (order_tmp.order_delivery.mobile || order_tmp.order_delivery.tel) || '',
name:order_tmp.order_delivery && order_tmp.order_delivery.name || '',
phone:order_tmp.order_delivery && (order_tmp.order_delivery.mobile || order_tmp.order_delivery.tel) || '',
moblie: order_tmp.order_delivery && (order_tmp.order_delivery.mobile || order_tmp.order_delivery.tel) || '',
name: order_tmp.order_delivery && order_tmp.order_delivery.name || '',
phone: order_tmp.order_delivery && (order_tmp.order_delivery.mobile || order_tmp.order_delivery.tel) || '',
},
template_url: matchedPlatform.template_url || '',
user_id: 0,
}
user_id: listByWarehousePlatformCode.shop.owner_id || 0,
};
}
)
//构建pdd接口入参
);
// 构建pdd接口入参
const pddPayload = {
// 这里根据实际需要构建接口入参
type: 'pdd.waybill.get',
accessToken:listByWarehousePlatformCode.token,
param_waybill_cloud_print_apply_new_request:{
need_encrypt:true,
sender:{
address:{
country:'中国',
city:listByWarehousePlatformCode.city_name,
province:listByWarehousePlatformCode.province_name,
district:listByWarehousePlatformCode.district_name,
town:listByWarehousePlatformCode.town_name|| null,
detail:listByWarehousePlatformCode.address,
accessToken: listByWarehousePlatformCode.token,
param_waybill_cloud_print_apply_new_request: {
need_encrypt: true,
sender: {
address: {
country: '中国',
city: listByWarehousePlatformCode.city_name,
province: listByWarehousePlatformCode.province_name,
district: listByWarehousePlatformCode.district_name,
town: listByWarehousePlatformCode.town_name || null,
detail: listByWarehousePlatformCode.address,
},
moblie:listByWarehousePlatformCode.sender_tel,
name:listByWarehousePlatformCode.sender_name,
phone:listByWarehousePlatformCode.sender_tel,
moblie: listByWarehousePlatformCode.sender_tel,
name: listByWarehousePlatformCode.sender_name,
phone: listByWarehousePlatformCode.sender_tel,
},
trade_order_info_dtos:tradeOrderList,
wp_code:listByWarehousePlatformCode && listByWarehousePlatformCode.express
trade_order_info_dtos: tradeOrderList,
wp_code: listByWarehousePlatformCode && listByWarehousePlatformCode.express
? (listByWarehousePlatformCode.express.PDD || '')
: '',
}
},
};
console.log('拼多多平台接口构建的请求参数', JSON.stringify(pddPayload, null, 2));
// 这里写一个调用pdd_client的入参示例
@ -933,6 +1578,11 @@ class ExpressPlatformService extends MainService {
waybill_code: waybillCode,
signature: (parsedPrintData && parsedPrintData.signature) || String(moduleItem && moduleItem.signature || '').trim() || null,
encryptprintinfo: (parsedPrintData && parsedPrintData.encryptedData) || null,
...this.buildOrderExpressVerPatch([
moduleItem && moduleItem.ver,
parsedPrintData && parsedPrintData.ver,
parsedPrintData && parsedPrintData.data && parsedPrintData.data.ver,
]),
create_at: new Date(),
logistics_code: listByWarehousePlatformCode.logistics_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,

View File

@ -526,7 +526,12 @@ class OrderPrintSystemService extends OrderBaseService {
.filter(orderId => Number.isInteger(orderId) && orderId > 0);
const orderExpressRows = await this.queryOrderExpressByOrderIds(orderIds);
this.assertBusinessWaybillCompleteness(orderIds, orderExpressRows);
const orderExpressMap = this.buildOrderExpressMap(orderExpressRows);
const enrichedOrderExpressRows = await this.enrichCainiaoOrderExpressRows(
unlockedOrderRows,
orderExpressRows,
normalizedWarehouseId
);
const orderExpressMap = this.buildOrderExpressMap(enrichedOrderExpressRows);
const policyConfigMap = await this.getPolicyConfigMapByStore(unlockedOrderRows, normalizedWarehouseId);
const pickingCandidateRows = unlockedOrderRows.filter(orderRow => {
const storeId = Number(orderRow && orderRow.store_id || 0);
@ -780,6 +785,7 @@ class OrderPrintSystemService extends OrderBaseService {
'printinfo',
'signature',
'encryptprintinfo',
'ver',
],
where: {
order_id: {
@ -992,6 +998,244 @@ ${waveFilterSql}
return expressMap;
}
/**
* 判断平台编码是否归一化为菜鸟。
*
* @param {string} platformCode 平台编码。
* @return {boolean} 是否为菜鸟平台。
*/
isCainiaoPlatformCode(platformCode = '') {
return PrinterDataBuilder.normalizePlatformAlias(platformCode).platform === 'cainiao';
}
/**
* 收集菜鸟编码映射可能命中的快递编码候选项。
*
* 优先使用系统快递编码,其次兼容订单/运单上的物流编码,避免遗漏历史数据。
*
* @param {Object} orderRow 订单行。
* @param {Object} orderExpress 快递行。
* @return {Array<string>} 去重后的快递编码候选列表。
*/
collectCainiaoExpressLookupCodes(orderRow = {}, orderExpress = {}) {
const codeList = [];
const appendCode = value => {
const normalizedCode = String(value || '').trim();
if (!normalizedCode || codeList.includes(normalizedCode)) {
return;
}
codeList.push(normalizedCode);
};
appendCode(orderRow && orderRow.sys_logistics_code);
appendCode(orderExpress && orderExpress.logistics_code);
appendCode(orderRow && orderRow.logistics_code);
return codeList;
}
/**
* 批量查询快递基础资料中的菜鸟编码映射。
*
* @param {Array<string>} expressCodes 快递编码列表。
* @return {Promise<Map<string, string>>} 快递编码到菜鸟编码的映射。
*/
async queryCainiaoCpCodeMap(expressCodes = []) {
const expressModel = this.ctx.model && this.ctx.model.Express;
const normalizedCodes = Array.from(new Set((Array.isArray(expressCodes) ? expressCodes : [])
.map(code => String(code || '').trim())
.filter(Boolean)));
const cpCodeMap = new Map();
if (!expressModel || typeof expressModel.findAll !== 'function' || normalizedCodes.length === 0) {
return cpCodeMap;
}
const rows = await expressModel.findAll({
attributes: [ 'code', 'CAINIAO' ],
where: {
code: {
[Op.in]: normalizedCodes,
},
},
raw: true,
});
for (const row of Array.isArray(rows) ? rows : []) {
const code = String(row && row.code || '').trim();
const cainiaoCode = String(row && row.CAINIAO || '').trim();
if (!code || !cainiaoCode) {
continue;
}
cpCodeMap.set(code, cainiaoCode);
}
return cpCodeMap;
}
/**
* 读取仓库下菜鸟平台的快递接口配置列表。
*
* @param {number} warehouseId 仓库ID。
* @return {Promise<Array<Object>>} 接口配置列表。
*/
async queryCainiaoExpressInterfaceList(warehouseId) {
const expressInterfaceService = this.service
&& this.service.systems
&& this.service.systems.setting
&& this.service.systems.setting.expressInterface;
if (!expressInterfaceService || typeof expressInterfaceService.listByWarehousePlatformCode !== 'function') {
return [];
}
const result = await expressInterfaceService.listByWarehousePlatformCode({
warehouseId,
platformCode: 'CAINIAO',
});
return Array.isArray(result && result.data) ? result.data : [];
}
/**
* 按订单物流编码匹配菜鸟主面单接口配置。
*
* 优先复用快递服务里的既有匹配规则;若运行上下文未注入该能力,则使用同语义的最小兜底实现。
*
* @param {Array<Object>} interfaceList 接口配置列表。
* @param {Object} orderRow 订单行。
* @param {Object} orderExpress 快递行。
* @return {Object|null} 命中的接口配置。
*/
pickCainiaoExpressInterface(interfaceList = [], orderRow = {}, orderExpress = {}) {
const logisticsCode = String(
orderExpress && orderExpress.logistics_code
|| orderRow && orderRow.logistics_code
|| orderRow && orderRow.sys_logistics_code
|| ''
).trim();
if (!logisticsCode) {
return null;
}
const expressService = this.service && this.service.systems && this.service.systems.express;
if (expressService && typeof expressService.pickWaybillExpressInterface === 'function') {
return expressService.pickWaybillExpressInterface(
interfaceList,
{
options: {
logistics_code: logisticsCode,
sys_platform_code: 'CAINIAO',
},
},
{ code: 'CAINIAO' }
);
}
const normalizedLogisticsCode = logisticsCode.toLowerCase();
for (const item of Array.isArray(interfaceList) ? interfaceList : []) {
if (!this.isPlainObject(item)) {
continue;
}
const candidateCodes = [
String(item.sys_express_code || '').trim().toLowerCase(),
String(item.express_code || '').trim().toLowerCase(),
];
const expressMap = this.isPlainObject(item.express) ? item.express : {};
candidateCodes.push(String(expressMap.CAINIAO || '').trim().toLowerCase());
if (candidateCodes.some(code => code && code === normalizedLogisticsCode)) {
return item;
}
}
return null;
}
/**
* 为菜鸟打印订单补齐主面单专用来源字段。
*
* 仅对打印平台归一化为菜鸟的订单生效;补齐失败时保留原始运单数据,避免影响其他平台打印。
*
* @param {Array<Object>} orderRows 订单列表。
* @param {Array<Object>} orderExpressRows 快递单列表。
* @param {number} warehouseId 仓库ID。
* @return {Promise<Array<Object>>} 补齐后的快递单列表。
*/
async enrichCainiaoOrderExpressRows(orderRows = [], orderExpressRows = [], warehouseId) {
const normalizedOrderRows = Array.isArray(orderRows) ? orderRows : [];
const normalizedOrderExpressRows = Array.isArray(orderExpressRows) ? orderExpressRows : [];
if (normalizedOrderRows.length === 0 || normalizedOrderExpressRows.length === 0) {
return normalizedOrderExpressRows;
}
const orderRowMap = new Map(normalizedOrderRows.map(row => [ Number(row && row.id || 0), row ]));
const cainiaoOrderIds = [];
const expressLookupCodes = [];
for (const row of normalizedOrderExpressRows) {
const orderId = Number(row && row.order_id || 0);
const orderRow = orderRowMap.get(orderId) || {};
const platformCode = this.resolvePrintPlatformCode(orderRow, row);
if (!this.isCainiaoPlatformCode(platformCode)) {
continue;
}
cainiaoOrderIds.push(orderId);
expressLookupCodes.push(...this.collectCainiaoExpressLookupCodes(orderRow, row));
}
if (cainiaoOrderIds.length === 0) {
return normalizedOrderExpressRows;
}
let cainiaoCpCodeMap = new Map();
try {
cainiaoCpCodeMap = await this.queryCainiaoCpCodeMap(expressLookupCodes);
} catch (error) {
this.ctx.logger.warn(
`[orderPrint.enrichCainiaoOrderExpressRows] 查询菜鸟快递编码失败 warehouseId=${warehouseId} message=${error.message}`
);
}
let interfaceList = [];
try {
interfaceList = await this.queryCainiaoExpressInterfaceList(warehouseId);
} catch (error) {
this.ctx.logger.warn(
`[orderPrint.enrichCainiaoOrderExpressRows] 查询菜鸟快递接口失败 warehouseId=${warehouseId} message=${error.message}`
);
}
const cainiaoOrderIdSet = new Set(cainiaoOrderIds);
return normalizedOrderExpressRows.map(row => {
const orderId = Number(row && row.order_id || 0);
if (!cainiaoOrderIdSet.has(orderId)) {
return row;
}
const orderRow = orderRowMap.get(orderId) || {};
const matchedCpCode = this.collectCainiaoExpressLookupCodes(orderRow, row)
.map(code => cainiaoCpCodeMap.get(code) || '')
.find(Boolean) || '';
const matchedInterface = this.pickCainiaoExpressInterface(interfaceList, orderRow, row);
const matchedTemplateUrl = String(matchedInterface && matchedInterface.template_url || '').trim();
if (!matchedCpCode && !matchedTemplateUrl) {
return row;
}
return {
...row,
...(matchedCpCode ? { cainiao_cp_code: matchedCpCode } : {}),
...(matchedTemplateUrl ? { cainiao_template_url: matchedTemplateUrl } : {}),
};
});
}
/**
* 获取波次订单对应货主的签约策略映射。
*
@ -1041,9 +1285,9 @@ ${waveFilterSql}
*/
resolvePrintPlatformCode(orderRow = {}, orderExpress = {}) {
const candidates = [
orderExpress && orderExpress.platform_code,
orderRow && orderRow.sys_platform_code,
orderRow && orderRow.source_platform_code,
orderExpress && orderExpress.platform_code,
];
for (const candidate of candidates) {

View File

@ -2,6 +2,10 @@
const Service = require('egg').Service;
const DEFAULT_PLATFORM_LIST_CACHE_TTL_SECONDS = 600;
const PLATFORM_OAUTH_BIND_SUCCESS_CACHE_PREFIX = 'bind_pdd_code:';
const PLATFORM_OAUTH_BIND_FAIL_CACHE_PREFIX = 'bind_pdd_code_fail:';
const PLATFORM_OAUTH_BIND_EVENT_CHANNEL_PREFIX = 'bind_pdd_code_event:';
const PLATFORM_OAUTH_BIND_LONG_POLL_TIMEOUT_MS = 60000;
class PlatformService extends Service {
/**
@ -19,6 +23,341 @@ class PlatformService extends Service {
return 0;
}
/**
* 规范化平台授权绑定业务编码。
*
* @param {*} code 原始业务编码
* @return {string} 规范化后的业务编码
*/
normalizePlatformOauthBindCode(code) {
return String(code || '').trim();
}
/**
* 获取平台授权绑定成功缓存键。
*
* @param {string} code 业务编码
* @return {string} 成功缓存键
*/
getPlatformOauthBindSuccessCacheKey(code) {
const normalizedCode = this.normalizePlatformOauthBindCode(code);
return `${PLATFORM_OAUTH_BIND_SUCCESS_CACHE_PREFIX}${normalizedCode}`;
}
/**
* 获取平台授权绑定失败缓存键。
*
* @param {string} code 业务编码
* @return {string} 失败缓存键
*/
getPlatformOauthBindFailCacheKey(code) {
const normalizedCode = this.normalizePlatformOauthBindCode(code);
return `${PLATFORM_OAUTH_BIND_FAIL_CACHE_PREFIX}${normalizedCode}`;
}
/**
* 获取平台授权绑定事件频道。
*
* @param {string} code 业务编码
* @return {string} 事件频道名称
*/
getPlatformOauthBindEventChannel(code) {
const normalizedCode = this.normalizePlatformOauthBindCode(code);
return `${PLATFORM_OAUTH_BIND_EVENT_CHANNEL_PREFIX}${normalizedCode}`;
}
/**
* 获取平台授权长轮询超时时间。
*
* @param {*} timeoutMs 原始超时配置
* @return {number} 毫秒级超时时间
*/
getPlatformOauthLongPollTimeoutMs(timeoutMs = PLATFORM_OAUTH_BIND_LONG_POLL_TIMEOUT_MS) {
const waitMs = Number(timeoutMs);
if (Number.isFinite(waitMs) && waitMs > 0) {
return Math.floor(waitMs);
}
return PLATFORM_OAUTH_BIND_LONG_POLL_TIMEOUT_MS;
}
/**
* 判断是否启用平台授权长轮询。
*
* @param {Object} data 请求参数
* @return {boolean} 是否启用长轮询
*/
shouldUsePlatformOauthLongPoll(data = {}) {
return [ true, 1, '1', 'true' ].includes(data.longPoll)
|| [ true, 1, '1', 'true' ].includes(data.long_poll)
|| [ true, 1, '1', 'true' ].includes(data.wait);
}
/**
* 查询平台授权绑定状态。
*
* @param {string} code 业务编码
* @return {Promise<Object>} 当前绑定状态
*/
async getPlatformOauthBindState(code) {
const normalizedCode = this.normalizePlatformOauthBindCode(code);
if (!normalizedCode) {
return {
status: 'failed',
message: 'code不能为空',
access_token: '',
};
}
const successCacheKey = this.getPlatformOauthBindSuccessCacheKey(normalizedCode);
const failCacheKey = this.getPlatformOauthBindFailCacheKey(normalizedCode);
let cachedToken = null;
try {
cachedToken = await this.app.getCacheAsync(successCacheKey);
} catch (error) {
this.ctx.logger.error(`[PlatformService.getPlatformOauthBindState] 查询成功缓存异常: ${error.message}`);
}
const accessToken = typeof cachedToken === 'string' ? cachedToken.trim() : '';
if (accessToken) {
return {
status: 'success',
message: '授权完成',
access_token: accessToken,
};
}
let failedCacheValue = null;
try {
failedCacheValue = await this.app.getCacheAsync(failCacheKey);
} catch (error) {
this.ctx.logger.error(`[PlatformService.getPlatformOauthBindState] 查询失败缓存异常: ${error.message}`);
}
if (failedCacheValue !== null && failedCacheValue !== undefined && failedCacheValue !== '') {
const failedMessage = failedCacheValue && typeof failedCacheValue === 'object' && failedCacheValue.message
? String(failedCacheValue.message).trim()
: '绑定失败,请重新授权';
return {
status: 'failed',
message: failedMessage || '绑定失败,请重新授权',
access_token: '',
};
}
return {
status: 'pending',
message: '等待授权完成',
access_token: '',
};
}
/**
* 发布平台授权绑定结果事件。
*
* @param {string} code 业务编码
* @param {Object} payload 事件负载
* @return {Promise<void>} 无返回值
*/
async publishPlatformOauthBindEvent(code, payload = {}) {
const normalizedCode = this.normalizePlatformOauthBindCode(code);
const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null;
if (!cacheRedis || !normalizedCode) {
return;
}
const channel = this.getPlatformOauthBindEventChannel(normalizedCode);
const eventData = {
code: normalizedCode,
event_at: new Date().toISOString(),
...payload,
};
try {
await cacheRedis.publish(channel, JSON.stringify(eventData));
} catch (error) {
this.app.coreLogger.warn(`发布平台授权绑定事件失败: ${error.message}`);
}
}
/**
* 等待平台授权绑定事件。
*
* @param {string} code 业务编码
* @param {number} timeoutMs 超时时间,单位毫秒
* @return {Promise<Object>} 等待结果
*/
async waitForPlatformOauthBindEvent(code, timeoutMs = PLATFORM_OAUTH_BIND_LONG_POLL_TIMEOUT_MS) {
const normalizedCode = this.normalizePlatformOauthBindCode(code);
const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null;
if (!cacheRedis || !normalizedCode || typeof cacheRedis.duplicate !== 'function') {
return {
timed_out: true,
reason: 'redis_not_available',
event: null,
};
}
const channel = this.getPlatformOauthBindEventChannel(normalizedCode);
const waitMs = this.getPlatformOauthLongPollTimeoutMs(timeoutMs);
const subscriber = cacheRedis.duplicate();
return await new Promise(resolve => {
let settled = false;
let timer = null;
function cleanup() {
subscriber.removeListener('message', onMessage);
subscriber.removeListener('error', onError);
Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => {
if (typeof subscriber.quit === 'function') {
Promise.resolve(subscriber.quit()).catch(() => {
if (typeof subscriber.disconnect === 'function') {
subscriber.disconnect();
}
});
return;
}
if (typeof subscriber.disconnect === 'function') {
subscriber.disconnect();
}
});
}
const finalize = result => {
if (settled) {
return;
}
settled = true;
if (timer) {
clearTimeout(timer);
}
cleanup();
resolve(result);
};
function onMessage(messageChannel, message) {
if (messageChannel !== channel) {
return;
}
let eventData = null;
try {
eventData = message ? JSON.parse(message) : null;
} catch (error) {
eventData = message;
}
finalize({
timed_out: false,
reason: 'event',
event: eventData,
});
}
function onError(error) {
this.app.coreLogger.warn(`订阅平台授权绑定事件失败: ${error.message}`);
finalize({
timed_out: true,
reason: 'subscribe_error',
event: null,
});
}
timer = setTimeout(() => {
finalize({
timed_out: true,
reason: 'timeout',
event: null,
});
}, waitMs);
subscriber.on('message', onMessage);
subscriber.on('error', onError);
Promise.resolve(subscriber.subscribe(channel)).catch(error => {
this.app.coreLogger.warn(`订阅平台授权绑定频道失败: ${error.message}`);
finalize({
timed_out: true,
reason: 'subscribe_failed',
event: null,
});
});
});
}
/**
* 监听平台授权绑定结果。
*
* @param {Object} data 请求参数
* @param {string} [data.code] 业务编码
* @param {string} [data.businessCode] 业务编码
* @param {boolean} [data.longPoll] 是否启用长轮询
* @param {number} [data.timeoutMs] 超时时间,单位毫秒
* @return {Promise<Object>} 监听结果
*/
async listenPlatformOauthBind(data = {}) {
const normalizedCode = this.normalizePlatformOauthBindCode(data.code || data.businessCode || data.business_code);
if (!normalizedCode) {
return {
success: false,
code: 0,
data: null,
message: 'code不能为空',
};
}
const useLongPoll = this.shouldUsePlatformOauthLongPoll(data);
let bindState = await this.getPlatformOauthBindState(normalizedCode);
if (bindState.status !== 'pending' || !useLongPoll) {
return {
success: true,
code: 200,
data: {
code: normalizedCode,
status: bindState.status,
access_token: bindState.access_token,
source: 'cache',
},
message: bindState.message,
};
}
const waitResult = await this.waitForPlatformOauthBindEvent(normalizedCode, data.timeoutMs || data.timeout_ms);
bindState = await this.getPlatformOauthBindState(normalizedCode);
if (bindState.status === 'pending') {
return {
success: true,
code: 200,
data: {
code: normalizedCode,
status: 'pending',
access_token: '',
source: waitResult.timed_out ? 'timeout' : 'event',
},
message: waitResult.timed_out ? '长轮询结束未检测到授权结果,请继续等待' : '授权状态暂未更新,请继续等待',
};
}
return {
success: true,
code: 200,
data: {
code: normalizedCode,
status: bindState.status,
access_token: bindState.access_token,
source: waitResult.timed_out ? 'cache' : 'event',
},
message: bindState.message,
};
}
/**
* 获取平台表的全量字段列表。
*
@ -49,6 +388,158 @@ class PlatformService extends Service {
return Object.keys(rawAttributes);
}
/**
* 获取打印平台模型。
*
* @return {Object|null} 打印平台模型,未注册时返回 null。
*/
getPrintPlatformModel() {
const printPlatformModel = this.ctx && this.ctx.model && this.ctx.model.PrintPlatform;
if (!printPlatformModel || typeof printPlatformModel.findAll !== 'function') {
return null;
}
return printPlatformModel;
}
/**
* 将 Sequelize 记录转换为普通对象。
*
* @param {Object} row 原始记录。
* @return {Object|null} 普通对象。
*/
toPlainRow(row) {
if (!row || typeof row !== 'object') {
return null;
}
if (typeof row.get === 'function') {
return row.get({ plain: true });
}
return row;
}
/**
* 规范化打印平台主键。
*
* @param {*} printPlatformId 打印平台主键。
* @return {number|null} 规范化后的主键。
*/
normalizePrintPlatformId(printPlatformId) {
const normalizedId = Number(printPlatformId || 0);
if (!Number.isFinite(normalizedId) || normalizedId <= 0) {
return null;
}
return normalizedId;
}
/**
* 批量加载打印平台编码映射。
*
* 仅以 `wms_platform.print_platform_id -> wms_print_platform.platform_code`
* 为准;缺少模型、主键或关联记录时返回空映射,避免继续误用旧字段。
*
* @param {Array<Object>} platformRows 平台记录列表。
* @return {Promise<Map<number, string>>} 打印平台ID到平台编码的映射。
*/
async loadPrintPlatformCodeMap(platformRows = []) {
const printPlatformModel = this.getPrintPlatformModel();
if (!printPlatformModel) {
return new Map();
}
const idSet = new Set();
for (const platformRow of Array.isArray(platformRows) ? platformRows : []) {
const plainRow = this.toPlainRow(platformRow);
const printPlatformId = this.normalizePrintPlatformId(plainRow && plainRow.print_platform_id);
if (printPlatformId) {
idSet.add(printPlatformId);
}
}
if (idSet.size <= 0) {
return new Map();
}
const rows = await printPlatformModel.findAll({
attributes: [ 'id', 'platform_code' ],
where: {
id: Array.from(idSet),
},
raw: true,
});
const printPlatformCodeMap = new Map();
for (const row of Array.isArray(rows) ? rows : []) {
const printPlatformId = this.normalizePrintPlatformId(row && row.id);
const platformCode = String(row && row.platform_code || '').trim();
if (!printPlatformId || !platformCode) {
continue;
}
printPlatformCodeMap.set(printPlatformId, platformCode);
}
return printPlatformCodeMap;
}
/**
* 解析平台对应的默认快递接口平台编码。
*
* 仅信任 `PrintPlatform.platform_code`;若模型未注册、主键缺失或未匹配到记录,
* 返回空字符串作为清晰兜底,不再退回到 `wms_platform.platform_code`。
*
* @param {Object} row 平台记录。
* @param {Map<number, string>} [printPlatformCodeMap] 打印平台编码映射。
* @return {string} 默认快递接口平台编码。
*/
resolveDefaultExpressInterface(row, printPlatformCodeMap = new Map()) {
const plainRow = this.toPlainRow(row);
if (!plainRow) {
return '';
}
const nestedPrintPlatform = this.toPlainRow(plainRow.printPlatform);
const nestedPlatformCode = String(nestedPrintPlatform && nestedPrintPlatform.platform_code || '').trim();
if (nestedPlatformCode) {
return nestedPlatformCode;
}
const printPlatformId = this.normalizePrintPlatformId(plainRow.print_platform_id);
if (!printPlatformId || !(printPlatformCodeMap instanceof Map)) {
return '';
}
return String(printPlatformCodeMap.get(printPlatformId) || '').trim();
}
/**
* 解析平台后处理路由编码。
*
* `wms_platform.platform_code` 用于第三方聚合平台后处理路由;
* 未配置时退回平台主编码,保持历史数据兼容。
*
* @param {Object} row 平台记录。
* @return {string} 平台后处理路由编码。
*/
resolveRoutePlatformCode(row) {
const plainRow = this.toPlainRow(row);
if (!plainRow) {
return '';
}
const routePlatformCode = String(plainRow.platform_code || '').trim();
if (routePlatformCode) {
return routePlatformCode;
}
return String(plainRow.code || plainRow.value || '').trim();
}
/**
* 生成平台列表缓存键。
*
@ -99,9 +590,10 @@ class PlatformService extends Service {
* 规范化系统平台记录。
*
* @param {Object} row 数据库记录。
* @param {Map<number, string>} [printPlatformCodeMap] 打印平台编码映射。
* @return {Object|null} 规范化后的记录。
*/
normalizePlatformRow(row) {
normalizePlatformRow(row, printPlatformCodeMap = new Map()) {
if (!row || typeof row !== 'object') {
return null;
}
@ -112,7 +604,7 @@ class PlatformService extends Service {
}
const name = String(row.name || '').trim();
const defaultExpressInterface = String(row.platform_code || '').trim();
const defaultExpressInterface = this.resolveDefaultExpressInterface(row, printPlatformCodeMap);
return {
code,
@ -198,10 +690,11 @@ class PlatformService extends Service {
* 规范化系统平台全量记录。
*
* @param {Object} row 数据库记录。
* @param {Map<number, string>} [printPlatformCodeMap] 打印平台编码映射。
* @return {Object|null} 规范化后的全量记录。
*/
normalizeFullPlatformRow(row) {
const normalizedRow = this.normalizePlatformRow(row);
normalizeFullPlatformRow(row, printPlatformCodeMap = new Map()) {
const normalizedRow = this.normalizePlatformRow(row, printPlatformCodeMap);
if (!normalizedRow) {
return null;
@ -210,6 +703,7 @@ class PlatformService extends Service {
return {
...row,
...normalizedRow,
route_platform_code: this.resolveRoutePlatformCode(row),
};
}
@ -227,9 +721,13 @@ class PlatformService extends Service {
return null;
}
const platformCode = String(row && row.platform_code || '').trim();
const platformItem = platformMap instanceof Map ? platformMap.get(platformCode) : null;
return {
...row,
...normalizedRow,
route_platform_code: String((platformItem && platformItem.route_platform_code) || '').trim(),
};
}
@ -238,7 +736,7 @@ class PlatformService extends Service {
*
* @param {Array<Object>} platformList 系统平台列表。
* @param {Array<Object>} platformSettingList 平台设置列表。
* @param full
* @param {boolean} [full=false] 是否合并全量字段。
* @return {Array<Object>} 合并后的平台列表。
*/
buildMergedPlatformList(platformList, platformSettingList, full = false) {
@ -303,7 +801,7 @@ class PlatformService extends Service {
query.attributes = attributes;
}
} else {
query.attributes = [ 'code', 'name', 'platform_code' ];
query.attributes = [ 'code', 'name', 'print_platform_id' ];
}
const rows = await this.ctx.model.Platform.findAll(query);
@ -312,8 +810,10 @@ class PlatformService extends Service {
return [];
}
const printPlatformCodeMap = await this.loadPrintPlatformCodeMap(rows);
return rows
.map(row => (full ? this.normalizeFullPlatformRow(row) : this.normalizePlatformRow(row)))
.map(row => (full ? this.normalizeFullPlatformRow(row, printPlatformCodeMap) : this.normalizePlatformRow(row, printPlatformCodeMap)))
.filter(Boolean);
}
@ -415,16 +915,17 @@ class PlatformService extends Service {
{
model: this.app.model.Platform,
as: 'platform',
attributes: [ 'code', 'name', 'platform_code' ],
attributes: [ 'code', 'name', 'print_platform_id' ],
},
],
});
if (platformSetting && platformSetting.platform) {
const printPlatformCodeMap = await this.loadPrintPlatformCodeMap([ platformSetting.platform ]);
// 从设置表中找到,并且有关联的平台信息
platformInfo = {
code: platformSetting.platform.code,
name: platformSetting.platform.name,
default_express_interface: String(platformSetting.platform.platform_code || '').trim(),
default_express_interface: this.resolveDefaultExpressInterface(platformSetting.platform, printPlatformCodeMap),
source: 'setting', // 标记来源
setting_id: platformSetting.id,
warehouse_id: warehouseId,
@ -435,14 +936,15 @@ class PlatformService extends Service {
where: {
code: platformCode,
},
attributes: [ 'code', 'name', 'platform_code' ],
attributes: [ 'code', 'name', 'print_platform_id' ],
});
if (basePlatform) {
const printPlatformCodeMap = await this.loadPrintPlatformCodeMap([ basePlatform ]);
platformInfo = {
code: basePlatform.code,
name: basePlatform.name,
default_express_interface: String(basePlatform.platform_code || '').trim(),
default_express_interface: this.resolveDefaultExpressInterface(basePlatform, printPlatformCodeMap),
source: 'base', // 标记来源
warehouse_id: warehouseId,
};

View File

@ -2,6 +2,7 @@
const Service = require('egg').Service;
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
const { buildNotDeletedShopWhere } = require('../../../lib/shop_soft_delete');
const DEFAULT_CACHE_TTL_SECONDS = 600;
@ -270,6 +271,9 @@ class SettingExpressInterfaceService extends Service {
platform_code: {
field: 'platform_code',
},
shop_id: {
field: 'shop_id',
},
sender_name: {
field: 'sender_name',
},
@ -291,6 +295,9 @@ class SettingExpressInterfaceService extends Service {
product_type: {
field: 'product_type',
},
template_url: {
field: 'template_url',
},
shop_name: {
field: 'shop_name',
},
@ -336,26 +343,32 @@ class SettingExpressInterfaceService extends Service {
/**
* 获取快递接口联查配置。
*
* @param options
* @return {Array<Object>} Sequelize 关联配置,仅保留系统快递关联。
* @param {Object} [options={}] 查询选项
* @return {Array<Object>} Sequelize 关联配置。
*/
getInterfaceInclude(options = {}) {
const { ctx } = this;
const { full = false } = options;
const include = {
const includes = [{
model: ctx.model.Express,
as: 'express',
required: false,
};
}];
if (!full) {
include.attributes = [ 'code', 'name' ];
includes[0].attributes = [ 'code', 'name' ];
}
return [
include,
];
if (full && ctx.model && ctx.model.Shop) {
includes.push({
model: ctx.model.Shop,
as: 'shop',
required: false,
});
}
return includes;
}
/**
@ -373,6 +386,66 @@ class SettingExpressInterfaceService extends Service {
return Object.keys(rawAttributes);
}
/**
* 校验模型字段是否存在。
*
* @param {Object} model Sequelize 模型
* @param {string} fieldName 字段名
* @param {string} modelName 模型名称
* @return {boolean} 字段是否存在
*/
ensureModelFieldExists(model, fieldName, modelName) {
const rawAttributes = model && model.rawAttributes;
if (!rawAttributes || !Object.prototype.hasOwnProperty.call(rawAttributes, fieldName)) {
throw this.createError(`${modelName}.${fieldName} 字段不存在,无法继续处理`, 500);
}
return true;
}
/**
* 根据店铺 ID 解析要同步的店铺与 token 信息。
*
* @param {number|null} shopId 规范化后的店铺 ID
* @return {Promise<Object>} 同步后的店铺绑定信息
*/
async resolveShopBinding(shopId) {
this.ensureModelFieldExists(this.ctx.model.Shop, 'access_token', 'Shop');
this.ensureModelFieldExists(this.ctx.model.ExpressInterface, 'token', 'ExpressInterface');
if (shopId === null) {
return {
shopId: null,
token: null,
};
}
const currentStoreId = this.getCurrentStoreId();
const shop = await this.ctx.model.Shop.findOne({
where: {
id: shopId,
warehouse_id: currentStoreId,
...buildNotDeletedShopWhere(this.app),
},
attributes: [ 'id', 'warehouse_id', 'access_token' ],
});
if (!shop) {
throw this.createError('当前仓库下未找到对应店铺,无法同步快递接口 token', 404);
}
const plainShop = shop && typeof shop.get === 'function'
? shop.get({ plain: true })
: shop;
const normalizedToken = this.normalizeOptionalText(plainShop.access_token, 'access_token', 255);
return {
shopId: Number(plainShop.id),
token: normalizedToken || null,
};
}
/**
* 复制普通对象或数组,避免缓存对象被外部修改。
*
@ -417,6 +490,28 @@ class SettingExpressInterfaceService extends Service {
};
}
/**
* 判断列表项中的快递编码是否为系统快递编码。
*
* @param {Object} row 快递接口记录
* @param {Object|null} express 系统快递信息
* @return {number} 是系统快递编码返回 1,否则返回 0
*/
resolveIsSystemExpressCodeFlag(row, express) {
const expressCode = this.normalizeOptionalText(row && row.express_code, 'express_code', 255);
const systemExpressCode = this.normalizeOptionalText(
row && (row.sys_express_code !== undefined && row.sys_express_code !== null ? row.sys_express_code : (express && express.code)),
'sys_express_code',
50
);
if (!expressCode || !systemExpressCode) {
return 0;
}
return expressCode.toUpperCase() === systemExpressCode.toUpperCase() ? 1 : 0;
}
/**
* 获取平台自建快递编码字段名。
*
@ -459,6 +554,107 @@ class SettingExpressInterfaceService extends Service {
return normalizedSysExpressCode;
}
/**
* 校验打印平台编码是否存在。
*
* 当运行环境尚未注册 `PrintPlatform` 模型时跳过校验,保持旧测试桩兼容;
* 已注册模型时统一校验 `wms_print_platform.platform_code`。
*
* @param {string} platformCode 打印平台编码。
* @return {Promise<string>} 规范化后的打印平台编码。
*/
async ensurePrintPlatformExists(platformCode) {
const normalizedPlatformCode = this.normalizePlatformCode(platformCode, 'platform_code', 20);
const printPlatformModel = this.ctx && this.ctx.model && this.ctx.model.PrintPlatform;
if (!printPlatformModel || typeof printPlatformModel.findOne !== 'function') {
return normalizedPlatformCode;
}
const printPlatform = await printPlatformModel.findOne({
where: {
platform_code: normalizedPlatformCode,
},
attributes: [ 'platform_code' ],
});
if (!printPlatform) {
throw this.createError('platform_code 未匹配到打印平台编码', 400);
}
return normalizedPlatformCode;
}
/**
* 规范化打印平台记录。
*
* 返回结构尽量与现有平台/下拉列表风格保持一致。
*
* @param {Object} row 打印平台记录。
* @return {Object|null} 规范化后的打印平台数据。
*/
normalizePrintPlatformRow(row) {
if (!row || typeof row !== 'object') {
return null;
}
const platformCode = this.normalizeOptionalText(row.platform_code, 'platform_code', 20);
if (!platformCode) {
return null;
}
const platformName = this.normalizeOptionalText(row.platform_name, 'platform_name', 100);
const platid = row.platid === undefined || row.platid === null || row.platid === ''
? null
: String(row.platid);
return {
id: row.id === undefined || row.id === null ? null : Number(row.id),
code: platformCode,
name: platformName || platformCode,
value: platformCode,
label: platformName || platformCode,
platform_code: platformCode,
platform_name: platformName,
platid,
status: this.normalizeOptionalText(row.status, 'status', 20) || 'ACTIVE',
remark: this.normalizeOptionalText(row.remark, 'remark', 255),
};
}
/**
* 获取打印平台全量列表。
*
* 仅返回未删除且状态为启用的打印平台,供快递接口配置页下拉选择使用。
*
* @return {Promise<Array<Object>>} 打印平台列表。
*/
async getPrintPlatformList() {
const printPlatformModel = this.ctx && this.ctx.model && this.ctx.model.PrintPlatform;
if (!printPlatformModel || typeof printPlatformModel.findAll !== 'function') {
return [];
}
const rows = await printPlatformModel.findAll({
attributes: [ 'id', 'platform_code', 'platform_name', 'platid', 'status', 'remark' ],
where: {
deleted: 0,
status: 'ACTIVE',
},
order: [[ 'platform_name', 'ASC' ], [ 'id', 'ASC' ]],
});
if (!Array.isArray(rows)) {
return [];
}
return rows
.map(row => (row && typeof row.get === 'function' ? row.get({ plain: true }) : row))
.map(row => this.normalizePrintPlatformRow(row))
.filter(Boolean);
}
/**
* 根据外部快递编码解析系统快递编码。
*
@ -507,21 +703,25 @@ class SettingExpressInterfaceService extends Service {
* 规范化快递接口记录。
*
* @param {Object} row 数据库记录
* @param {Object} [options={}] 规范化选项
* @return {Object|null} 规范化后的记录
*/
normalizeInterfaceRow(row) {
normalizeInterfaceRow(row, options = {}) {
if (!row || typeof row !== 'object') {
return null;
}
const { includeSystemExpressFlag = false } = options;
const express = this.normalizeExpressRow(row.express && typeof row.express === 'object' ? row.express : null);
return {
const normalizedRow = {
id: row.id === undefined || row.id === null ? null : Number(row.id),
name: this.normalizeOptionalText(row.name, 'name', 255),
express_code: this.normalizeOptionalText(row.express_code, 'express_code', 255),
sys_express_code: this.normalizeOptionalText(row.sys_express_code, 'sys_express_code', 50),
warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id),
shop_id: row.shop_id === undefined || row.shop_id === null ? null : Number(row.shop_id),
platform_code: this.normalizeOptionalText(row.platform_code, 'platform_code', 20),
sender_name: this.normalizeOptionalText(row.sender_name, 'sender_name', 50),
sender_tel: this.normalizeOptionalText(row.sender_tel, 'sender_tel', 11),
@ -532,6 +732,7 @@ class SettingExpressInterfaceService extends Service {
is_share: row.is_share === undefined || row.is_share === null ? null : Number(row.is_share),
ispickup: row.ispickup === undefined || row.ispickup === null ? null : Number(row.ispickup),
shipperno: this.normalizeOptionalText(row.shipperno, 'shipperno', 255),
template_url: this.normalizeOptionalText(row.template_url, 'template_url', 500),
ext_data: this.clonePlainValue(row.ext_data === undefined ? null : row.ext_data),
province_name: this.normalizeOptionalText(row.province_name, 'province_name', 255),
city_name: this.normalizeOptionalText(row.city_name, 'city_name', 255),
@ -546,6 +747,12 @@ class SettingExpressInterfaceService extends Service {
express_polyapi_extra_info: express ? express.polyapi_extra_info : null,
express_pdd_code: express ? express.pdd_code : null,
};
if (includeSystemExpressFlag) {
normalizedRow.is_system_express_code = this.resolveIsSystemExpressCodeFlag(row, express);
}
return normalizedRow;
}
/**
@ -573,9 +780,42 @@ class SettingExpressInterfaceService extends Service {
normalized.express = this.clonePlainValue(row.express);
}
if (Object.prototype.hasOwnProperty.call(row, 'shop')) {
normalized.shop = this.clonePlainValue(row.shop);
}
return normalized;
}
/**
* 判断缓存中的仓库平台快递接口数据是否包含店铺联查字段。
*
* @param {Array<Object>} rows 快递接口列表
* @return {boolean} 是否可直接使用缓存
*/
hasWarehousePlatformShopData(rows) {
if (!Array.isArray(rows) || rows.length === 0) {
return true;
}
return rows.every(row => {
if (!row || typeof row !== 'object') {
return false;
}
if (!Object.prototype.hasOwnProperty.call(row, 'shop_id')) {
return true;
}
const shopId = row.shop_id;
if (shopId === null || shopId === undefined) {
return true;
}
return Object.prototype.hasOwnProperty.call(row, 'shop');
});
}
/**
* 规范化快递接口的全量记录数组,并按 weight / id 排序。
*
@ -740,7 +980,6 @@ class SettingExpressInterfaceService extends Service {
* 校验平台接口组合是否可用。
*
* @param {string} platformCode 平台代码
* @param {number} expressPlatformId 快递接口 ID
* @param {number|null} [excludeId=null] 排除的记录 ID
* @return {Promise<boolean>} 是否可用
*/
@ -818,20 +1057,23 @@ class SettingExpressInterfaceService extends Service {
},
include: this.getInterfaceInclude(),
attributes: [
'id', 'name', 'express_code', 'warehouse_id', 'platform_code',
'id', 'name', 'express_code', 'warehouse_id', 'shop_id', 'platform_code',
'sys_express_code',
'sender_name', 'sender_tel', 'weight', 'viewer', 'client_id', 'is_share',
'province_name', 'city_name', 'district_name', 'site_code',
'product_type', 'weight_type', 'shop_name', 'address', 'town_name', 'ispickup', 'shipperno', 'ext_data',
'product_type', 'weight_type', 'shop_name', 'address', 'town_name', 'ispickup', 'shipperno', 'template_url', 'ext_data',
],
order: [[ 'id', 'DESC' ]],
order: [[ 'weight', 'ASC' ], [ 'id', 'DESC' ]],
offset,
limit: pageSize,
distinct: true,
});
const list = Array.isArray(result && result.rows)
? result.rows.map(row => this.normalizeInterfaceRow(row && typeof row.get === 'function' ? row.get({ plain: true }) : row)).filter(Boolean)
? result.rows.map(row => this.normalizeInterfaceRow(
row && typeof row.get === 'function' ? row.get({ plain: true }) : row,
{ includeSystemExpressFlag: true }
)).filter(Boolean)
: [];
return {
@ -862,10 +1104,13 @@ class SettingExpressInterfaceService extends Service {
try {
const cachedValue = await app.getCacheAsync(cacheKey);
if (cachedValue !== null && cachedValue !== undefined) {
return {
code: 200,
data: this.normalizeFullInterfaceRows(cachedValue),
};
const normalizedCached = this.normalizeFullInterfaceRows(cachedValue);
if (this.hasWarehousePlatformShopData(normalizedCached)) {
return {
code: 200,
data: normalizedCached,
};
}
}
} catch (error) {
if (this.ctx && this.ctx.logger && typeof this.ctx.logger.warn === 'function') {
@ -876,7 +1121,7 @@ class SettingExpressInterfaceService extends Service {
}
}
}
console.log('查询入参', warehouseId, platformCode);
const settings = await ctx.model.ExpressInterface.findAll({
where: {
warehouse_id: warehouseId,
@ -925,7 +1170,9 @@ class SettingExpressInterfaceService extends Service {
const name = this.normalizeText(data.name, 'name', 255);
const expressCode = this.normalizeText(data.express_code || data.expressCode, 'express_code', 255).toUpperCase();
const platformCode = this.normalizeText(data.platform_code || data.platformCode, 'platform_code', 20).toUpperCase();
const platformCode = await this.ensurePrintPlatformExists(
data.platform_code !== undefined ? data.platform_code : data.platformCode
);
if (!name) {
@ -950,6 +1197,10 @@ class SettingExpressInterfaceService extends Service {
express_code: expressCode,
platform_code: platformCode,
sys_express_code: sysExpressCode,
shop_id: this.normalizeInteger(data.shop_id !== undefined ? data.shop_id : data.shopId, 'shop_id', {
allowEmpty: true,
min: 1,
}),
sender_name: this.normalizeOptionalText(data.sender_name || data.senderName, 'sender_name', 50),
sender_tel: this.normalizeOptionalText(data.sender_tel || data.senderTel, 'sender_tel', 11),
weight: this.normalizeInteger(data.weight, 'weight', {
@ -962,6 +1213,7 @@ class SettingExpressInterfaceService extends Service {
client_id: this.normalizeOptionalText(data.client_id || data.clientId, 'client_id', 50),
ispickup: this.normalizeFlag(data.ispickup !== undefined ? data.ispickup : data.isPickup, 'ispickup', 0),
shipperno: this.normalizeOptionalText(data.shipperno !== undefined ? data.shipperno : data.shipperNo, 'shipperno', 255),
template_url: this.normalizeOptionalText(data.template_url !== undefined ? data.template_url : data.templateUrl, 'template_url', 500),
ext_data: this.normalizeOptionalJson(data.ext_data !== undefined ? data.ext_data : data.extData, 'ext_data'),
province_name: this.normalizeOptionalText(data.province_name || data.provinceName, 'province_name', 255),
city_name: this.normalizeOptionalText(data.city_name || data.cityName, 'city_name', 255),
@ -1017,6 +1269,8 @@ class SettingExpressInterfaceService extends Service {
const hasWeight = Object.prototype.hasOwnProperty.call(data, 'weight');
const hasWeightType = Object.prototype.hasOwnProperty.call(data, 'weight_type')
|| Object.prototype.hasOwnProperty.call(data, 'weightType');
const hasShopId = Object.prototype.hasOwnProperty.call(data, 'shop_id')
|| Object.prototype.hasOwnProperty.call(data, 'shopId');
const hasViewer = Object.prototype.hasOwnProperty.call(data, 'viewer');
const hasClientId = Object.prototype.hasOwnProperty.call(data, 'client_id')
|| Object.prototype.hasOwnProperty.call(data, 'clientId');
@ -1024,6 +1278,8 @@ class SettingExpressInterfaceService extends Service {
|| Object.prototype.hasOwnProperty.call(data, 'isPickup');
const hasShipperNo = Object.prototype.hasOwnProperty.call(data, 'shipperno')
|| Object.prototype.hasOwnProperty.call(data, 'shipperNo');
const hasTemplateUrl = Object.prototype.hasOwnProperty.call(data, 'template_url')
|| Object.prototype.hasOwnProperty.call(data, 'templateUrl');
const hasProvinceName = Object.prototype.hasOwnProperty.call(data, 'province_name')
|| Object.prototype.hasOwnProperty.call(data, 'provinceName');
const hasCityName = Object.prototype.hasOwnProperty.call(data, 'city_name')
@ -1044,8 +1300,9 @@ class SettingExpressInterfaceService extends Service {
if (!hasName && !hasExpressCode && !hasPlatformCode && !hasSysExpressCode
&& !hasSenderName && !hasSenderTel && !hasWeight && !hasWeightType
&& !hasShopId
&& !hasViewer && !hasClientId && !hasIsPickup
&& !hasShipperNo && !hasProvinceName && !hasCityName
&& !hasShipperNo && !hasTemplateUrl && !hasProvinceName && !hasCityName
&& !hasDistrictName && !hasAddress && !hasTownName && !hasSiteCode
&& !hasProductType && !hasShopName && !hasExtData) {
throw this.createError('至少需要提供一个可更新字段', 400);
@ -1073,7 +1330,11 @@ class SettingExpressInterfaceService extends Service {
}
if (hasPlatformCode) {
const platformCode = this.normalizeText(data.platform_code || data.platformCode, 'platform_code', 20).toUpperCase();
const platformCode = this.normalizePlatformCode(
data.platform_code !== undefined ? data.platform_code : data.platformCode,
'platform_code',
20
);
if (!platformCode) {
throw this.createError('platform_code 参数不能为空', 400);
}
@ -1081,6 +1342,12 @@ class SettingExpressInterfaceService extends Service {
updates.platform_code = platformCode;
}
nextPlatformCode = await this.ensurePrintPlatformExists(nextPlatformCode);
if (Object.prototype.hasOwnProperty.call(updates, 'platform_code')) {
updates.platform_code = nextPlatformCode;
}
if (hasSenderName) {
updates.sender_name = this.normalizeOptionalText(data.sender_name || data.senderName, 'sender_name', 50);
}
@ -1101,6 +1368,17 @@ class SettingExpressInterfaceService extends Service {
});
}
if (hasShopId) {
const normalizedShopId = this.normalizeInteger(data.shop_id !== undefined ? data.shop_id : data.shopId, 'shop_id', {
allowEmpty: true,
min: 1,
});
const shopBinding = await this.resolveShopBinding(normalizedShopId);
updates.shop_id = shopBinding.shopId;
updates.token = shopBinding.token;
}
if (hasViewer) {
updates.viewer = this.normalizeOptionalText(data.viewer, 'viewer', 50);
}
@ -1117,6 +1395,14 @@ class SettingExpressInterfaceService extends Service {
updates.shipperno = this.normalizeOptionalText(data.shipperno !== undefined ? data.shipperno : data.shipperNo, 'shipperno', 255);
}
if (hasTemplateUrl) {
updates.template_url = this.normalizeOptionalText(
data.template_url !== undefined ? data.template_url : data.templateUrl,
'template_url',
500
);
}
if (hasProvinceName) {
updates.province_name = this.normalizeOptionalText(data.province_name || data.provinceName, 'province_name', 255);
}

View File

@ -0,0 +1,692 @@
'use strict';
const Service = require('egg').Service;
const crypto = require('node:crypto');
const {
DELETED_SHOP_NAME_PREFIX,
buildNotDeletedShopWhere,
} = require('../../lib/shop_soft_delete');
/**
* 店铺业务服务。
*/
class ShopsService extends Service {
/**
* 创建业务错误。
*
* @param {string} message 错误信息
* @param {number} [code=500] 错误码
* @return {Error} 业务错误对象
*/
createError(message, code = 500) {
const error = new Error(message);
error.code = code;
return error;
}
/**
* 获取当前仓库 ID。
*
* @return {number} 仓库 ID
*/
getCurrentWarehouseId() {
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id);
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
throw this.createError('未识别到当前仓库', 400);
}
return warehouseId;
}
/**
* 规范化字符串参数。
*
* @param {*} value 原始值
* @param {string} fieldName 字段名
* @param {Object} [options={}] 选项
* @param {boolean} [options.required=false] 是否必填
* @param {number} [options.maxLength=255] 最大长度
* @return {string|null} 规范化结果
*/
normalizeText(value, fieldName, options = {}) {
const { required = false, maxLength = 255 } = options;
if (value === undefined || value === null) {
if (required) {
throw this.createError(`${fieldName} 不能为空`, 400);
}
return null;
}
const normalized = String(value).trim();
if (!normalized) {
if (required) {
throw this.createError(`${fieldName} 不能为空`, 400);
}
return null;
}
if (normalized.length > maxLength) {
throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400);
}
return normalized;
}
/**
* 规范化整数参数。
*
* @param {*} value 原始值
* @param {string} fieldName 字段名
* @param {Object} [options={}] 选项
* @param {boolean} [options.required=false] 是否必填
* @param {number|null} [options.min=null] 最小值
* @return {number|null} 规范化结果
*/
normalizeInteger(value, fieldName, options = {}) {
const { required = false, min = null } = options;
if (value === undefined || value === null || value === '') {
if (required) {
throw this.createError(`${fieldName} 不能为空`, 400);
}
return null;
}
const normalized = Number(value);
if (!Number.isInteger(normalized)) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
if (min !== null && normalized < min) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
return normalized;
}
/**
* 校验并标准化平台编码。
*
* @param {*} platformCode 原始平台编码
* @return {Promise<string>} 标准化平台编码
*/
async ensureShopPrintPlatformExists(platformCode) {
const normalizedPlatformCode = this.normalizeText(platformCode, 'platform_code', {
required: true,
maxLength: 50,
}).toUpperCase();
const printPlatform = await this.ctx.model.PrintPlatform.findOne({
where: {
platform_code: normalizedPlatformCode,
deleted: 0,
status: 'ACTIVE',
},
attributes: [ 'platform_code', 'platform_name', 'auth_base_url' ],
});
if (!printPlatform) {
throw this.createError('platform_code 未匹配到打印平台编码', 400);
}
return normalizedPlatformCode;
}
/**
* 获取店铺列表字段过滤映射。
*
* @return {Object} specialFieldMap 映射
*/
getListWhereSpecialFieldMap() {
return {
id: { field: 'id' },
platform_code: { field: 'platform_code' },
custom_name: { field: 'custom_name' },
shop_name: { field: 'shop_name' },
status: { field: 'status' },
quickWhere: { bucket: 'quick' },
};
}
/**
* 构建店铺列表查询条件。
*
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 查询 where
*/
async buildListWhere(data = {}) {
const { app, ctx } = this;
const { Op } = app.Sequelize;
const parsedResult = ctx.whereParsed || {
dynamicConditions: [],
rawConditionsByField: {},
};
const whereAndConditions = [
{
warehouse_id: this.getCurrentWarehouseId(),
},
buildNotDeletedShopWhere(app),
];
const dynamicConditions = Array.isArray(parsedResult.dynamicConditions)
? parsedResult.dynamicConditions
: [];
if (dynamicConditions.length > 0) {
whereAndConditions.push({ [Op.and]: dynamicConditions });
}
const quickWhereCondition = parsedResult.rawConditionsByField
? parsedResult.rawConditionsByField.quickWhere
: null;
const quickWhereValue = quickWhereCondition && typeof quickWhereCondition === 'object'
? quickWhereCondition.value
: null;
const keyword = String(quickWhereValue || '').trim();
if (keyword) {
whereAndConditions.push({
[Op.or]: [
{ shop_name: { [Op.like]: `%${keyword}%` } },
{ custom_name: { [Op.like]: `%${keyword}%` } },
{ platform_code: { [Op.like]: `%${keyword.toUpperCase()}%` } },
],
});
}
const normalizedPlatformCode = data.platform_code !== undefined
? String(data.platform_code || '').trim()
: String(data.platformCode || '').trim();
if (normalizedPlatformCode) {
whereAndConditions.push({
platform_code: await this.ensureShopPrintPlatformExists(normalizedPlatformCode),
});
}
return {
[Op.and]: whereAndConditions,
};
}
/**
* 规范化分页参数。
*
* @param {Object} [data={}] 请求参数
* @return {{page:number,pageSize:number,offset:number}} 分页信息
*/
normalizePagination(data = {}) {
const pagination = data && typeof data.pagination === 'object' ? data.pagination : {};
const pageSource = pagination.page !== undefined ? pagination.page : (data.page !== undefined ? data.page : data.currentPage);
const pageSizeSource = pagination.pageSize !== undefined
? pagination.pageSize
: (pagination.page_size !== undefined ? pagination.page_size : (data.pageSize !== undefined ? data.pageSize : data.page_size));
const page = Math.max(Number.parseInt(pageSource, 10) || 1, 1);
const pageSize = Math.min(Math.max(Number.parseInt(pageSizeSource, 10) || 20, 1), 200);
return {
page,
pageSize,
offset: (page - 1) * pageSize,
};
}
/**
* 构建店铺关联打印平台查询。
*
* @return {Array<Object>} include 查询配置
*/
buildShopPrintPlatformInclude() {
return [{
model: this.ctx.model.PrintPlatform,
as: 'printPlatform',
required: false,
attributes: [ 'platform_code', 'platform_name', 'status' ],
where: {
deleted: 0,
status: 'ACTIVE',
},
}];
}
/**
* 规范化店铺列表输出。
*
* @param {Object} shopRow 店铺记录
* @return {Object} 输出结构
*/
formatShopRow(shopRow) {
const printPlatform = shopRow && typeof shopRow.printPlatform === 'object'
? shopRow.printPlatform
: null;
return {
id: shopRow.id,
warehouse_id: shopRow.warehouse_id,
platform_code: shopRow.platform_code,
platform_name: printPlatform ? printPlatform.platform_name || '' : '',
shop_name: shopRow.shop_name,
custom_name: shopRow.custom_name,
status: shopRow.status,
created_at: shopRow.created_at,
updated_at: shopRow.updated_at,
};
}
/**
* 查询店铺分页列表。
*
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 列表结果
*/
async list(data = {}) {
const { ctx } = this;
const { page, pageSize, offset } = this.normalizePagination(data);
const where = await this.buildListWhere(data);
const result = await ctx.model.Shop.findAndCountAll({
where,
include: this.buildShopPrintPlatformInclude(),
order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
offset,
limit: pageSize,
});
const rows = Array.isArray(result && result.rows) ? result.rows : [];
const list = rows.map(row => (row && typeof row.get === 'function' ? row.get({ plain: true }) : row))
.map(row => this.formatShopRow(row));
const total = Number(result && result.count ? result.count : 0);
return {
list,
pagination: {
page,
pageSize,
total,
totalPages: pageSize > 0 ? Math.ceil(total / pageSize) : 0,
hasNext: page * pageSize < total,
hasPrevious: page > 1,
},
};
}
/**
* 校验店铺名唯一性。
*
* @param {Object} payload 入参
* @param {number} payload.warehouseId 仓库 ID
* @param {string} payload.platformCode 平台编码
* @param {string} payload.shopName 店铺名
* @param {number|null} [payload.excludeId=null] 排除店铺 ID
* @return {Promise<void>} 无返回
*/
async ensureShopNameUnique(payload) {
const { app, ctx } = this;
const { Op } = app.Sequelize;
const { warehouseId, platformCode, shopName, excludeId = null } = payload;
const where = {
warehouse_id: warehouseId,
platform_code: platformCode,
shop_name: shopName,
...buildNotDeletedShopWhere(app),
};
if (excludeId !== null) {
where.id = { [Op.ne]: excludeId };
}
const existed = await ctx.model.Shop.findOne({ where, attributes: [ 'id' ] });
if (existed) {
throw this.createError('同仓同平台下 shop_name 已存在', 409);
}
}
/**
* 新增店铺。
*
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 新增结果
*/
async add(data = {}) {
const { ctx } = this;
const warehouseId = this.getCurrentWarehouseId();
const platformCode = await this.ensureShopPrintPlatformExists(data.platform_code !== undefined ? data.platform_code : data.platformCode);
const customName = this.normalizeText(data.custom_name !== undefined ? data.custom_name : data.customName, 'custom_name', {
required: true,
maxLength: 100,
});
const shopName = this.normalizeText(data.shop_name !== undefined ? data.shop_name : data.shopName, 'shop_name', {
required: false,
maxLength: 100,
}) || customName;
await this.ensureShopNameUnique({
warehouseId,
platformCode,
shopName,
});
const created = await ctx.model.Shop.create({
warehouse_id: warehouseId,
platform_code: platformCode,
shop_name: shopName,
custom_name: customName,
status: 0,
auth_expire_at: null,
auth_random_code: null,
owner_id: null,
access_token: null,
refresh_token: null,
token_expires_at: null,
refresh_token_expires_at: null,
scope: null,
});
const plainRow = created && typeof created.get === 'function'
? created.get({ plain: true })
: created;
return {
id: plainRow.id,
};
}
/**
* 读取店铺并校验仓库归属。
*
* @param {*} shopId 店铺 ID
* @param {Object} [options={}] 选项
* @param {boolean} [options.allowDeleted=false] 是否允许读取已软删除店铺
* @return {Promise<Object>} 店铺模型实例
*/
async findShopById(shopId, options = {}) {
const { app, ctx } = this;
const { allowDeleted = false } = options;
const where = {
id: this.normalizeInteger(shopId, 'shop_id', { required: true, min: 1 }),
warehouse_id: this.getCurrentWarehouseId(),
};
if (!allowDeleted) {
Object.assign(where, buildNotDeletedShopWhere(app));
}
const shop = await ctx.model.Shop.findOne({ where });
if (!shop) {
throw this.createError('店铺不存在', 404);
}
return shop;
}
/**
* 软删除店铺。
*
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 删除结果
*/
async del(data = {}) {
const { ctx } = this;
const shopId = data.id !== undefined ? data.id : (data.shop_id !== undefined ? data.shop_id : data.shopId);
const shop = await this.findShopById(shopId);
const normalizedShopId = Number(shop.id);
const referencedInterface = await ctx.model.ExpressInterface.findOne({
where: {
warehouse_id: this.getCurrentWarehouseId(),
shop_id: normalizedShopId,
},
attributes: [ 'id' ],
});
if (referencedInterface) {
throw this.createError('店铺存在快递接口引用,无法删除', 409);
}
const deletedSuffix = `${Date.now()}_${crypto.randomBytes(4).toString('hex')}`;
await shop.update({
shop_name: `${DELETED_SHOP_NAME_PREFIX}${normalizedShopId}_${deletedSuffix}`,
custom_name: null,
status: 0,
auth_expire_at: null,
auth_random_code: null,
owner_id: null,
access_token: null,
refresh_token: null,
token_expires_at: null,
refresh_token_expires_at: null,
scope: null,
}, {
fields: [
'shop_name',
'custom_name',
'status',
'auth_expire_at',
'auth_random_code',
'owner_id',
'access_token',
'refresh_token',
'token_expires_at',
'refresh_token_expires_at',
'scope',
],
});
return {
deleted: true,
id: normalizedShopId,
};
}
/**
* 编辑店铺。
*
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 编辑结果
*/
async edit(data = {}) {
const shopId = data.id !== undefined ? data.id : (data.shop_id !== undefined ? data.shop_id : data.shopId);
const shop = await this.findShopById(shopId);
const updates = {};
const hasPlatformCode = Object.prototype.hasOwnProperty.call(data, 'platform_code')
|| Object.prototype.hasOwnProperty.call(data, 'platformCode');
const hasCustomName = Object.prototype.hasOwnProperty.call(data, 'custom_name')
|| Object.prototype.hasOwnProperty.call(data, 'customName');
if (!hasPlatformCode && !hasCustomName) {
throw this.createError('仅允许修改 platform_code 或 custom_name', 400);
}
if (hasPlatformCode) {
updates.platform_code = await this.ensureShopPrintPlatformExists(
data.platform_code !== undefined ? data.platform_code : data.platformCode
);
}
if (hasCustomName) {
updates.custom_name = this.normalizeText(
data.custom_name !== undefined ? data.custom_name : data.customName,
'custom_name',
{ required: true, maxLength: 100 }
);
}
const nextPlatformCode = updates.platform_code || shop.platform_code;
const nextShopName = shop.shop_name;
await this.ensureShopNameUnique({
warehouseId: this.getCurrentWarehouseId(),
platformCode: nextPlatformCode,
shopName: nextShopName,
excludeId: Number(shop.id),
});
await shop.update(updates, {
fields: Object.keys(updates),
});
return {
updated: true,
id: Number(shop.id),
};
}
/**
* 生成平台授权预占码。
*
* @return {string} 预占码
*/
generateAuthorizeRandomCode() {
return crypto.randomBytes(24).toString('hex');
}
/**
* 创建或复用授权预占店铺。
*
* @param {Object} payload 参数
* @param {number} payload.warehouseId 仓库 ID
* @param {string} payload.platformCode 平台编码
* @return {Promise<{shop:Object,authRandomCode:string}>} 预占结果
*/
async createOrReuseAuthorizeReservation(payload) {
const { ctx, app } = this;
const { warehouseId, platformCode } = payload;
const pendingShop = await ctx.model.Shop.findOne({
where: {
warehouse_id: warehouseId,
platform_code: platformCode,
status: 0,
...buildNotDeletedShopWhere(app),
},
order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
});
if (pendingShop && String(pendingShop.auth_random_code || '').trim()) {
return {
shop: pendingShop,
authRandomCode: String(pendingShop.auth_random_code).trim(),
};
}
const maxRetryCount = 5;
for (let retryIndex = 0; retryIndex < maxRetryCount; retryIndex++) {
const authRandomCode = this.generateAuthorizeRandomCode();
try {
if (pendingShop) {
pendingShop.auth_random_code = authRandomCode;
await pendingShop.save({ fields: [ 'auth_random_code' ] });
return {
shop: pendingShop,
authRandomCode,
};
}
const createdShop = await ctx.model.Shop.create({
warehouse_id: warehouseId,
platform_code: platformCode,
shop_name: `PENDING_${authRandomCode}`,
custom_name: null,
status: 0,
auth_expire_at: null,
auth_random_code: authRandomCode,
owner_id: null,
access_token: null,
refresh_token: null,
token_expires_at: null,
refresh_token_expires_at: null,
scope: null,
});
return {
shop: createdShop,
authRandomCode,
};
} catch (error) {
const isUniqueConflict = error && error.name === 'SequelizeUniqueConstraintError';
if (isUniqueConflict && retryIndex < maxRetryCount - 1) {
continue;
}
if (isUniqueConflict) {
throw this.createError('生成唯一授权码失败,请稍后重试', 500);
}
throw error;
}
}
throw this.createError('生成唯一授权码失败,请稍后重试', 500);
}
/**
* 获取店铺授权会话。
*
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 会话信息
*/
async getAuthorizeSessionKey(data = {}) {
const { ctx } = this;
const warehouseId = this.getCurrentWarehouseId();
const shopId = data.id !== undefined ? data.id : (data.shop_id !== undefined ? data.shop_id : data.shopId);
const callbackUrl = this.normalizeText(
data.callbackurl !== undefined ? data.callbackurl : data.callback_url,
'callbackurl',
{ required: true, maxLength: 500 }
);
const shop = await this.findShopById(shopId, { allowDeleted: false });
const shopPlain = typeof shop.get === 'function' ? shop.get({ plain: true }) : shop;
const platformCode = await this.ensureShopPrintPlatformExists(shopPlain.platform_code);
switch (platformCode) {
case 'PDD':
case 'CAINIAO': {
const printPlatform = await ctx.model.PrintPlatform.findOne({
where: {
platform_code: platformCode,
deleted: 0,
status: 'ACTIVE',
},
attributes: [ 'auth_base_url' ],
});
const authBaseUrl = String(printPlatform && printPlatform.auth_base_url || '').trim();
if (!authBaseUrl) {
throw this.createError('平台授权基础地址未配置', 400);
}
const reservation = await this.createOrReuseAuthorizeReservation({
warehouseId,
platformCode,
});
const state = `${platformCode}_${reservation.authRandomCode}`;
const authorizeUrl = `${authBaseUrl}${encodeURIComponent(state)}`;
return {
shop_id: Number(shopPlain.id),
platform_code: platformCode,
callbackurl: callbackUrl,
session_key: reservation.authRandomCode,
authorize_url: authorizeUrl,
state,
};
}
default:
throw this.createError(`平台 ${platformCode} 暂未实现授权会话换取能力`, 501);
}
}
}
module.exports = ShopsService;

View File

@ -2,38 +2,37 @@ const fs = require('fs');
const path = require('path');
const filePath = path.join('app', 'lib', 'printer_data_builder.js');
const code = fs.readFileSync(filePath, 'utf8');
let stack = [];
const stack = [];
let isInString = null;
let isInComment = null;
let isEscaped = false;
let line = 1, column = 1;
let line = 1,
column = 1;
for (let i = 0; i < code.length; i++) {
const char = code[i], nextChar = code[i + 1];
if (isEscaped) { isEscaped = false; if (char === '\n') { line++; column = 1; } else { column++; } continue; }
if (isInString) {
if (char === '\\') isEscaped = true;
else if (char === isInString) isInString = null;
else if (char === '\n') { line++; column = 1; }
} else if (isInComment === '//') {
if (char === '\n') { isInComment = null; line++; column = 1; }
} else if (isInComment === '/*') {
if (char === '*' && nextChar === '/') { isInComment = null; i++; column++; }
else if (char === '\n') { line++; column = 1; }
} else {
if (char === '"' || char === "'" || char === '`') isInString = char;
else if (char === '/' && nextChar === '/') { isInComment = '//'; i++; column++; }
else if (char === '/' && nextChar === '*') { isInComment = '/*'; i++; column++; }
else if (char === '{' || char === '(' || char === '[') stack.push({ char, line, column });
else if (char === '}' || char === ')' || char === ']') {
const last = stack.pop();
const pairs = { '}': '{', ')': '(', ']': '[' };
if (!last || last.char !== pairs[char]) {
console.log(`Unmatched closing symbol "${char}" at line ${line}, column ${column}`);
if (last) stack.push(last);
}
} else if (char === '\n') { line++; column = 1; continue; }
}
column++;
const char = code[i],
nextChar = code[i + 1];
if (isEscaped) { isEscaped = false; if (char === '\n') { line++; column = 1; } else { column++; } continue; }
if (isInString) {
if (char === '\\') isEscaped = true;
else if (char === isInString) isInString = null;
else if (char === '\n') { line++; column = 1; }
} else if (isInComment === '//') {
if (char === '\n') { isInComment = null; line++; column = 1; }
} else if (isInComment === '/*') {
if (char === '*' && nextChar === '/') { isInComment = null; i++; column++; } else if (char === '\n') { line++; column = 1; }
} else {
if (char === '"' || char === "'" || char === '`') isInString = char;
else if (char === '/' && nextChar === '/') { isInComment = '//'; i++; column++; } else if (char === '/' && nextChar === '*') { isInComment = '/*'; i++; column++; } else if (char === '{' || char === '(' || char === '[') stack.push({ char, line, column });
else if (char === '}' || char === ')' || char === ']') {
const last = stack.pop();
const pairs = { '}': '{', ')': '(', ']': '[' };
if (!last || last.char !== pairs[char]) {
console.log(`Unmatched closing symbol "${char}" at line ${line}, column ${column}`);
if (last) stack.push(last);
}
} else if (char === '\n') { line++; column = 1; continue; }
}
column++;
}
stack.forEach(item => console.log(`Unclosed symbol "${item.char}" from line ${item.line}, column ${item.column}`));
if (stack.length === 0) console.log('All symbols are matched.');

View File

@ -125,4 +125,4 @@ module.exports = {
await queryInterface.dropTable(TABLE_NAME);
}
},
};
};

View File

@ -43,4 +43,4 @@ module.exports = {
await queryInterface.removeColumn(tableName, 'auth_base_url');
},
};
};

View File

@ -99,4 +99,4 @@ module.exports = {
await queryInterface.removeColumn(tableName, 'owner_id');
}
},
};
};

View File

@ -39,4 +39,4 @@ module.exports = {
await queryInterface.removeColumn(tableName, 'custom_name');
}
},
};
};

View File

@ -0,0 +1,46 @@
'use strict';
/**
* 为快递接口配置表新增店铺 ID 字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
module.exports = {
/**
* 执行迁移:新增店铺 ID 字段(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
async up(queryInterface, Sequelize) {
const tableName = 'wms_express_interface';
const columns = await queryInterface.describeTable(tableName);
if (columns.shop_id) {
return;
}
await queryInterface.addColumn(tableName, 'shop_id', {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '店铺ID',
});
},
/**
* 回滚迁移:删除店铺 ID 字段(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @return {Promise<void>} 无返回值
*/
async down(queryInterface) {
const tableName = 'wms_express_interface';
const columns = await queryInterface.describeTable(tableName);
if (!columns.shop_id) {
return;
}
await queryInterface.removeColumn(tableName, 'shop_id');
},
};

View File

@ -0,0 +1,61 @@
'use strict';
/**
* 扩容系统日志表 device 字段长度到 100。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
module.exports = {
/**
* 执行迁移:将 wms_system_log.device 调整为 VARCHAR(100)(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
async up(queryInterface, Sequelize) {
const tableName = 'wms_system_log';
const columns = await queryInterface.describeTable(tableName);
if (!columns.device) {
return;
}
const currentLength = Number(columns.device.length || 0);
if (currentLength >= 100) {
return;
}
await queryInterface.changeColumn(tableName, 'device', {
type: Sequelize.STRING(100),
allowNull: true,
comment: '设备',
});
},
/**
* 回滚迁移:将 wms_system_log.device 调整回 VARCHAR(10)(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
async down(queryInterface, Sequelize) {
const tableName = 'wms_system_log';
const columns = await queryInterface.describeTable(tableName);
if (!columns.device) {
return;
}
const currentLength = Number(columns.device.length || 0);
if (currentLength > 0 && currentLength <= 10) {
return;
}
await queryInterface.changeColumn(tableName, 'device', {
type: Sequelize.STRING(10),
allowNull: true,
comment: '设备',
});
},
};

View File

@ -0,0 +1,46 @@
'use strict';
/**
* 为快递基础信息表新增菜鸟编码字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
module.exports = {
/**
* 执行迁移:新增 CAINIAO 字段(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
async up(queryInterface, Sequelize) {
const tableName = 'wms_express';
const columns = await queryInterface.describeTable(tableName);
if (columns.CAINIAO) {
return;
}
await queryInterface.addColumn(tableName, 'CAINIAO', {
type: Sequelize.STRING(255),
allowNull: true,
comment: '菜鸟编码',
});
},
/**
* 回滚迁移:删除 CAINIAO 字段(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @return {Promise<void>} 无返回值
*/
async down(queryInterface) {
const tableName = 'wms_express';
const columns = await queryInterface.describeTable(tableName);
if (!columns.CAINIAO) {
return;
}
await queryInterface.removeColumn(tableName, 'CAINIAO');
},
};

View File

@ -0,0 +1,47 @@
'use strict';
/**
* 为快递接口配置表新增是否隐藏物品信息字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
module.exports = {
/**
* 执行迁移:新增 is_hide_goods 字段(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
async up(queryInterface, Sequelize) {
const tableName = 'wms_express_interface';
const columns = await queryInterface.describeTable(tableName);
if (columns.is_hide_goods) {
return;
}
await queryInterface.addColumn(tableName, 'is_hide_goods', {
type: Sequelize.TINYINT(1),
allowNull: true,
defaultValue: 0,
comment: '是否隐藏物品信息',
});
},
/**
* 回滚迁移:删除 is_hide_goods 字段(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @return {Promise<void>} 无返回值
*/
async down(queryInterface) {
const tableName = 'wms_express_interface';
const columns = await queryInterface.describeTable(tableName);
if (!columns.is_hide_goods) {
return;
}
await queryInterface.removeColumn(tableName, 'is_hide_goods');
},
};

View File

@ -0,0 +1,142 @@
'use strict';
const TABLE_NAME = 'wms_print_platform';
/**
* 获取当前数据库已存在的表名集合。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<Set<string>>} 表名集合。
*/
const getExistingTableSet = async queryInterface => {
const tables = await queryInterface.showAllTables();
return new Set(
tables.map(table => (typeof table === 'string' ? table : table.tableName))
);
};
/**
* 获取指定表的索引名集合。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @return {Promise<Set<string>>} 索引名集合。
*/
const getIndexNameSet = async (queryInterface, tableName) => {
const indexes = await queryInterface.showIndex(tableName);
return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean));
};
/**
* 创建打印平台元数据表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
const createPrintPlatformTable = async (queryInterface, Sequelize) => {
await queryInterface.createTable(TABLE_NAME, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
platform_code: {
type: Sequelize.STRING(50),
allowNull: false,
comment: '打印平台编码',
},
platform_name: {
type: Sequelize.STRING(100),
allowNull: false,
comment: '打印平台名称',
},
status: {
type: Sequelize.STRING(20),
allowNull: false,
defaultValue: 'ACTIVE',
comment: '状态',
},
remark: {
type: Sequelize.STRING(255),
allowNull: true,
comment: '备注',
},
create_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
update_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
deleted: {
type: Sequelize.TINYINT,
allowNull: false,
defaultValue: 0,
comment: '软删除标记:0-未删除,1-已删除',
},
}, {
engine: 'InnoDB',
charset: 'utf8mb4',
collate: 'utf8mb4_general_ci',
comment: '打印平台元数据表',
});
};
/**
* 确保打印平台元数据表索引存在。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
const ensurePrintPlatformIndexes = async queryInterface => {
const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME);
if (!indexNameSet.has('uk_platform_code')) {
await queryInterface.addIndex(TABLE_NAME, [ 'platform_code' ], {
name: 'uk_platform_code',
unique: true,
});
}
if (!indexNameSet.has('idx_status')) {
await queryInterface.addIndex(TABLE_NAME, [ 'status' ], {
name: 'idx_status',
});
}
};
module.exports = {
/**
* 创建打印平台元数据表及索引。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
async up(queryInterface, Sequelize) {
const existingTables = await getExistingTableSet(queryInterface);
if (!existingTables.has(TABLE_NAME)) {
await createPrintPlatformTable(queryInterface, Sequelize);
}
await ensurePrintPlatformIndexes(queryInterface);
},
/**
* 回滚删除打印平台元数据表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
async down(queryInterface, Sequelize) {
void Sequelize;
const existingTables = await getExistingTableSet(queryInterface);
if (existingTables.has(TABLE_NAME)) {
await queryInterface.dropTable(TABLE_NAME);
}
},
};

View File

@ -0,0 +1,46 @@
'use strict';
/**
* 为 wms_platform 新增 print_platform_id 字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
module.exports = {
/**
* 执行迁移:新增 print_platform_id 字段(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
async up(queryInterface, Sequelize) {
const tableName = 'wms_platform';
const columns = await queryInterface.describeTable(tableName);
if (columns.print_platform_id) {
return;
}
await queryInterface.addColumn(tableName, 'print_platform_id', {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '关联打印平台ID',
});
},
/**
* 回滚迁移:删除 print_platform_id 字段(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @return {Promise<void>} 无返回值
*/
async down(queryInterface) {
const tableName = 'wms_platform';
const columns = await queryInterface.describeTable(tableName);
if (!columns.print_platform_id) {
return;
}
await queryInterface.removeColumn(tableName, 'print_platform_id');
},
};

View File

@ -0,0 +1,117 @@
'use strict';
const TABLE_NAME = 'wms_print_platform';
const SORT_INDEX_NAME = 'idx_sort';
/**
* 获取当前数据库已存在的表名集合。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<Set<string>>} 表名集合。
*/
const getExistingTableSet = async queryInterface => {
const tables = await queryInterface.showAllTables();
return new Set(
tables.map(table => (typeof table === 'string' ? table : table.tableName))
);
};
/**
* 获取指定表的字段定义。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @return {Promise<Record<string, object>>} 字段定义映射。
*/
const getTableColumns = async (queryInterface, tableName) => {
return queryInterface.describeTable(tableName);
};
/**
* 获取指定表的索引名集合。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @return {Promise<Set<string>>} 索引名集合。
*/
const getIndexNameSet = async (queryInterface, tableName) => {
const indexes = await queryInterface.showIndex(tableName);
return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean));
};
module.exports = {
/**
* 正向迁移:幂等删除打印平台表中的废弃字段与排序索引。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
async up(queryInterface) {
const existingTables = await getExistingTableSet(queryInterface);
if (!existingTables.has(TABLE_NAME)) {
return;
}
const columns = await getTableColumns(queryInterface, TABLE_NAME);
const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME);
if (indexNameSet.has(SORT_INDEX_NAME)) {
await queryInterface.removeIndex(TABLE_NAME, SORT_INDEX_NAME);
}
if (columns.sort) {
await queryInterface.removeColumn(TABLE_NAME, 'sort');
}
if (columns.aliases) {
await queryInterface.removeColumn(TABLE_NAME, 'aliases');
}
if (columns.template_file) {
await queryInterface.removeColumn(TABLE_NAME, 'template_file');
}
},
/**
* 回滚迁移:幂等恢复打印平台表中的废弃字段与排序索引。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。
* @return {Promise<void>} 无返回值。
*/
async down(queryInterface, Sequelize) {
const existingTables = await getExistingTableSet(queryInterface);
if (!existingTables.has(TABLE_NAME)) {
return;
}
const columns = await getTableColumns(queryInterface, TABLE_NAME);
if (!columns.aliases) {
await queryInterface.addColumn(TABLE_NAME, 'aliases', {
type: Sequelize.JSON,
allowNull: true,
comment: '平台别名数组',
});
}
if (!columns.template_file) {
await queryInterface.addColumn(TABLE_NAME, 'template_file', {
type: Sequelize.STRING(100),
allowNull: true,
comment: '默认模板文件名',
});
}
if (!columns.sort) {
await queryInterface.addColumn(TABLE_NAME, 'sort', {
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: 0,
comment: '排序值',
});
}
const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME);
if (!indexNameSet.has(SORT_INDEX_NAME)) {
await queryInterface.addIndex(TABLE_NAME, [ 'sort' ], {
name: SORT_INDEX_NAME,
});
}
},
};

View File

@ -0,0 +1,248 @@
'use strict';
const SOURCE_TABLE = 'wms_express_interface';
const SOURCE_COLUMN = 'platform_code';
const OLD_TARGET_TABLE = 'wms_platform';
const OLD_TARGET_COLUMN = 'code';
const NEW_TARGET_TABLE = 'wms_print_platform';
const NEW_TARGET_COLUMN = 'platform_code';
const NEW_CONSTRAINT_NAME = 'fk_wms_express_interface_print_platform_code';
/**
* 获取数据库中的真实表名集合。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<Set<string>>} 表名集合。
*/
const getExistingTableSet = async queryInterface => {
const tables = await queryInterface.showAllTables();
return new Set(
tables.map(table => (typeof table === 'string' ? table : table.tableName))
);
};
/**
* 安全读取指定表字段定义。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {Set<string>} existingTableSet 已存在表名集合。
* @param {string} tableName 表名。
* @return {Promise<Object|null>} 字段定义;表不存在时返回 null。
*/
const getTableColumns = async (queryInterface, existingTableSet, tableName) => {
if (!existingTableSet.has(tableName)) {
return null;
}
return queryInterface.describeTable(tableName);
};
/**
* 查询指定列上的外键信息。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 源表名。
* @param {string} columnName 源列名。
* @return {Promise<Array<Object>>} 外键信息列表。
*/
const getColumnForeignKeys = async (queryInterface, tableName, columnName) => {
const [ rows ] = await queryInterface.sequelize.query(
`
SELECT
kcu.CONSTRAINT_NAME AS constraintName,
kcu.TABLE_NAME AS tableName,
kcu.COLUMN_NAME AS columnName,
kcu.REFERENCED_TABLE_NAME AS referencedTableName,
kcu.REFERENCED_COLUMN_NAME AS referencedColumnName,
rc.UPDATE_RULE AS updateRule,
rc.DELETE_RULE AS deleteRule
FROM information_schema.KEY_COLUMN_USAGE kcu
INNER JOIN information_schema.REFERENTIAL_CONSTRAINTS rc
ON rc.CONSTRAINT_SCHEMA = kcu.CONSTRAINT_SCHEMA
AND rc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
AND rc.TABLE_NAME = kcu.TABLE_NAME
WHERE kcu.CONSTRAINT_SCHEMA = DATABASE()
AND kcu.TABLE_NAME = :tableName
AND kcu.COLUMN_NAME = :columnName
AND kcu.REFERENCED_TABLE_NAME IS NOT NULL
`,
{
replacements: {
tableName,
columnName,
},
}
);
return rows;
};
/**
* 删除指定列上指向目标表目标列的所有外键。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} sourceTable 源表名。
* @param {string} sourceColumn 源列名。
* @param {string} targetTable 目标表名。
* @param {string} targetColumn 目标列名。
* @return {Promise<void>} 无返回值。
*/
const dropForeignKeysByReference = async (
queryInterface,
sourceTable,
sourceColumn,
targetTable,
targetColumn
) => {
const foreignKeys = await getColumnForeignKeys(queryInterface, sourceTable, sourceColumn);
for (const foreignKey of foreignKeys) {
if (
foreignKey.referencedTableName === targetTable &&
foreignKey.referencedColumnName === targetColumn
) {
await queryInterface.removeConstraint(sourceTable, foreignKey.constraintName);
}
}
};
/**
* 判断指定引用关系外键是否已存在。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} sourceTable 源表名。
* @param {string} sourceColumn 源列名。
* @param {string} targetTable 目标表名。
* @param {string} targetColumn 目标列名。
* @return {Promise<boolean>} 是否已存在。
*/
const hasForeignKeyReference = async (
queryInterface,
sourceTable,
sourceColumn,
targetTable,
targetColumn
) => {
const foreignKeys = await getColumnForeignKeys(queryInterface, sourceTable, sourceColumn);
return foreignKeys.some(foreignKey => (
foreignKey.referencedTableName === targetTable &&
foreignKey.referencedColumnName === targetColumn
));
};
/**
* 为指定列添加目标外键。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} sourceTable 源表名。
* @param {string} sourceColumn 源列名。
* @param {string} targetTable 目标表名。
* @param {string} targetColumn 目标列名。
* @param {string} constraintName 外键名称。
* @return {Promise<void>} 无返回值。
*/
const addForeignKey = async (
queryInterface,
sourceTable,
sourceColumn,
targetTable,
targetColumn,
constraintName
) => {
await queryInterface.addConstraint(sourceTable, {
fields: [ sourceColumn ],
type: 'foreign key',
name: constraintName,
references: {
table: targetTable,
field: targetColumn,
},
onUpdate: 'RESTRICT',
onDelete: 'RESTRICT',
});
};
module.exports = {
/**
* 将快递接口平台外键从平台表切换到打印平台表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
async up(queryInterface) {
const existingTableSet = await getExistingTableSet(queryInterface);
const sourceColumns = await getTableColumns(queryInterface, existingTableSet, SOURCE_TABLE);
const targetColumns = await getTableColumns(queryInterface, existingTableSet, NEW_TARGET_TABLE);
if (!sourceColumns || !sourceColumns[SOURCE_COLUMN] || !targetColumns || !targetColumns[NEW_TARGET_COLUMN]) {
return;
}
await dropForeignKeysByReference(
queryInterface,
SOURCE_TABLE,
SOURCE_COLUMN,
OLD_TARGET_TABLE,
OLD_TARGET_COLUMN
);
const hasNewForeignKey = await hasForeignKeyReference(
queryInterface,
SOURCE_TABLE,
SOURCE_COLUMN,
NEW_TARGET_TABLE,
NEW_TARGET_COLUMN
);
if (!hasNewForeignKey) {
await addForeignKey(
queryInterface,
SOURCE_TABLE,
SOURCE_COLUMN,
NEW_TARGET_TABLE,
NEW_TARGET_COLUMN,
NEW_CONSTRAINT_NAME
);
}
},
/**
* 回滚快递接口平台外键到原平台表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
async down(queryInterface) {
const existingTableSet = await getExistingTableSet(queryInterface);
const sourceColumns = await getTableColumns(queryInterface, existingTableSet, SOURCE_TABLE);
const oldTargetColumns = await getTableColumns(queryInterface, existingTableSet, OLD_TARGET_TABLE);
if (!sourceColumns || !sourceColumns[SOURCE_COLUMN]) {
return;
}
await dropForeignKeysByReference(
queryInterface,
SOURCE_TABLE,
SOURCE_COLUMN,
NEW_TARGET_TABLE,
NEW_TARGET_COLUMN
);
if (!oldTargetColumns || !oldTargetColumns[OLD_TARGET_COLUMN]) {
return;
}
const hasOldForeignKey = await hasForeignKeyReference(
queryInterface,
SOURCE_TABLE,
SOURCE_COLUMN,
OLD_TARGET_TABLE,
OLD_TARGET_COLUMN
);
if (!hasOldForeignKey) {
await addForeignKey(
queryInterface,
SOURCE_TABLE,
SOURCE_COLUMN,
OLD_TARGET_TABLE,
OLD_TARGET_COLUMN,
'fk_wms_express_interface_platform_code'
);
}
},
};

View File

@ -0,0 +1,242 @@
'use strict';
const SOURCE_TABLE = 'wms_shops';
const SOURCE_COLUMN = 'platform_code';
const OLD_TARGET_TABLE = 'wms_platform';
const OLD_TARGET_COLUMN = 'code';
const NEW_TARGET_TABLE = 'wms_print_platform';
const NEW_TARGET_COLUMN = 'platform_code';
const NEW_CONSTRAINT_NAME = 'fk_wms_shops_print_platform_code';
/**
* 获取数据库中的真实表名集合。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<Set<string>>} 表名集合。
*/
const getExistingTableSet = async queryInterface => {
const tables = await queryInterface.showAllTables();
return new Set(
tables.map(table => (typeof table === 'string' ? table : table.tableName))
);
};
/**
* 安全读取指定表字段定义。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {Set<string>} existingTableSet 已存在表名集合。
* @param {string} tableName 表名。
* @return {Promise<Object|null>} 字段定义;表不存在时返回 null。
*/
const getTableColumns = async (queryInterface, existingTableSet, tableName) => {
if (!existingTableSet.has(tableName)) {
return null;
}
return queryInterface.describeTable(tableName);
};
/**
* 查询指定列上的外键信息。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 源表名。
* @param {string} columnName 源列名。
* @return {Promise<Array<Object>>} 外键信息列表。
*/
const getColumnForeignKeys = async (queryInterface, tableName, columnName) => {
const [ rows ] = await queryInterface.sequelize.query(
`
SELECT
kcu.CONSTRAINT_NAME AS constraintName,
kcu.TABLE_NAME AS tableName,
kcu.COLUMN_NAME AS columnName,
kcu.REFERENCED_TABLE_NAME AS referencedTableName,
kcu.REFERENCED_COLUMN_NAME AS referencedColumnName
FROM information_schema.KEY_COLUMN_USAGE kcu
WHERE kcu.CONSTRAINT_SCHEMA = DATABASE()
AND kcu.TABLE_NAME = :tableName
AND kcu.COLUMN_NAME = :columnName
AND kcu.REFERENCED_TABLE_NAME IS NOT NULL
`,
{
replacements: {
tableName,
columnName,
},
}
);
return rows;
};
/**
* 删除指定列上指向目标表目标列的所有外键。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} sourceTable 源表名。
* @param {string} sourceColumn 源列名。
* @param {string} targetTable 目标表名。
* @param {string} targetColumn 目标列名。
* @return {Promise<void>} 无返回值。
*/
const dropForeignKeysByReference = async (
queryInterface,
sourceTable,
sourceColumn,
targetTable,
targetColumn
) => {
const foreignKeys = await getColumnForeignKeys(queryInterface, sourceTable, sourceColumn);
for (const foreignKey of foreignKeys) {
if (
foreignKey.referencedTableName === targetTable
&& foreignKey.referencedColumnName === targetColumn
) {
await queryInterface.removeConstraint(sourceTable, foreignKey.constraintName);
}
}
};
/**
* 判断指定引用关系外键是否已存在。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} sourceTable 源表名。
* @param {string} sourceColumn 源列名。
* @param {string} targetTable 目标表名。
* @param {string} targetColumn 目标列名。
* @return {Promise<boolean>} 是否已存在。
*/
const hasForeignKeyReference = async (
queryInterface,
sourceTable,
sourceColumn,
targetTable,
targetColumn
) => {
const foreignKeys = await getColumnForeignKeys(queryInterface, sourceTable, sourceColumn);
return foreignKeys.some(foreignKey => (
foreignKey.referencedTableName === targetTable
&& foreignKey.referencedColumnName === targetColumn
));
};
/**
* 为指定列添加目标外键。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} sourceTable 源表名。
* @param {string} sourceColumn 源列名。
* @param {string} targetTable 目标表名。
* @param {string} targetColumn 目标列名。
* @param {string} constraintName 外键名称。
* @return {Promise<void>} 无返回值。
*/
const addForeignKey = async (
queryInterface,
sourceTable,
sourceColumn,
targetTable,
targetColumn,
constraintName
) => {
await queryInterface.addConstraint(sourceTable, {
fields: [ sourceColumn ],
type: 'foreign key',
name: constraintName,
references: {
table: targetTable,
field: targetColumn,
},
onUpdate: 'RESTRICT',
onDelete: 'RESTRICT',
});
};
module.exports = {
/**
* 将店铺平台外键切换到打印平台表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
async up(queryInterface) {
const existingTableSet = await getExistingTableSet(queryInterface);
const sourceColumns = await getTableColumns(queryInterface, existingTableSet, SOURCE_TABLE);
const targetColumns = await getTableColumns(queryInterface, existingTableSet, NEW_TARGET_TABLE);
if (!sourceColumns || !sourceColumns[SOURCE_COLUMN] || !targetColumns || !targetColumns[NEW_TARGET_COLUMN]) {
return;
}
await dropForeignKeysByReference(
queryInterface,
SOURCE_TABLE,
SOURCE_COLUMN,
OLD_TARGET_TABLE,
OLD_TARGET_COLUMN
);
const hasNewForeignKey = await hasForeignKeyReference(
queryInterface,
SOURCE_TABLE,
SOURCE_COLUMN,
NEW_TARGET_TABLE,
NEW_TARGET_COLUMN
);
if (!hasNewForeignKey) {
await addForeignKey(
queryInterface,
SOURCE_TABLE,
SOURCE_COLUMN,
NEW_TARGET_TABLE,
NEW_TARGET_COLUMN,
NEW_CONSTRAINT_NAME
);
}
},
/**
* 回滚店铺平台外键到原平台表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
async down(queryInterface) {
const existingTableSet = await getExistingTableSet(queryInterface);
const sourceColumns = await getTableColumns(queryInterface, existingTableSet, SOURCE_TABLE);
const oldTargetColumns = await getTableColumns(queryInterface, existingTableSet, OLD_TARGET_TABLE);
if (!sourceColumns || !sourceColumns[SOURCE_COLUMN]) {
return;
}
await dropForeignKeysByReference(
queryInterface,
SOURCE_TABLE,
SOURCE_COLUMN,
NEW_TARGET_TABLE,
NEW_TARGET_COLUMN
);
if (!oldTargetColumns || !oldTargetColumns[OLD_TARGET_COLUMN]) {
return;
}
const hasOldForeignKey = await hasForeignKeyReference(
queryInterface,
SOURCE_TABLE,
SOURCE_COLUMN,
OLD_TARGET_TABLE,
OLD_TARGET_COLUMN
);
if (!hasOldForeignKey) {
await addForeignKey(
queryInterface,
SOURCE_TABLE,
SOURCE_COLUMN,
OLD_TARGET_TABLE,
OLD_TARGET_COLUMN,
'fk_wms_shops_platform_code'
);
}
},
};

View File

@ -0,0 +1,93 @@
'use strict';
const PLATFORM_TABLE_NAME = 'wms_platform';
const PRINT_PLATFORM_TABLE_NAME = 'wms_print_platform';
const COLUMN_NAME = 'auth_base_url';
/**
* 获取当前数据库已存在的表名集合。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<Set<string>>} 表名集合。
*/
const getExistingTableSet = async queryInterface => {
const tables = await queryInterface.showAllTables();
return new Set(
tables.map(table => (typeof table === 'string' ? table : table.tableName))
);
};
/**
* 安全读取指定表字段定义。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {Set<string>} existingTableSet 已存在表名集合。
* @param {string} tableName 表名。
* @return {Promise<Object|null>} 字段定义;表不存在时返回 null。
*/
const getTableColumns = async (queryInterface, existingTableSet, tableName) => {
if (!existingTableSet.has(tableName)) {
return null;
}
return queryInterface.describeTable(tableName);
};
/**
* 构建授权基础地址字段定义。
* @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。
* @return {Object} 字段定义。
*/
const buildAuthBaseUrlColumn = Sequelize => ({
type: Sequelize.STRING(255),
allowNull: true,
comment: '授权基础地址',
});
module.exports = {
/**
* 正向迁移:将授权基础地址字段迁移到打印平台表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。
* @return {Promise<void>} 无返回值。
*/
async up(queryInterface, Sequelize) {
const existingTableSet = await getExistingTableSet(queryInterface);
const printPlatformColumns = await getTableColumns(queryInterface, existingTableSet, PRINT_PLATFORM_TABLE_NAME);
const platformColumns = await getTableColumns(queryInterface, existingTableSet, PLATFORM_TABLE_NAME);
if (printPlatformColumns && !printPlatformColumns[COLUMN_NAME]) {
await queryInterface.addColumn(
PRINT_PLATFORM_TABLE_NAME,
COLUMN_NAME,
buildAuthBaseUrlColumn(Sequelize)
);
}
if (platformColumns && platformColumns[COLUMN_NAME]) {
await queryInterface.removeColumn(PLATFORM_TABLE_NAME, COLUMN_NAME);
}
},
/**
* 回滚迁移:将授权基础地址字段恢复到平台表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。
* @return {Promise<void>} 无返回值。
*/
async down(queryInterface, Sequelize) {
const existingTableSet = await getExistingTableSet(queryInterface);
const printPlatformColumns = await getTableColumns(queryInterface, existingTableSet, PRINT_PLATFORM_TABLE_NAME);
const platformColumns = await getTableColumns(queryInterface, existingTableSet, PLATFORM_TABLE_NAME);
if (platformColumns && !platformColumns[COLUMN_NAME]) {
await queryInterface.addColumn(
PLATFORM_TABLE_NAME,
COLUMN_NAME,
buildAuthBaseUrlColumn(Sequelize)
);
}
if (printPlatformColumns && printPlatformColumns[COLUMN_NAME]) {
await queryInterface.removeColumn(PRINT_PLATFORM_TABLE_NAME, COLUMN_NAME);
}
},
};

View File

@ -0,0 +1,46 @@
'use strict';
/**
* 为快递接口配置表新增模板链接字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
module.exports = {
/**
* 执行迁移:新增 template_url 字段(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
async up(queryInterface, Sequelize) {
const tableName = 'wms_express_interface';
const columns = await queryInterface.describeTable(tableName);
if (columns.template_url) {
return;
}
await queryInterface.addColumn(tableName, 'template_url', {
type: Sequelize.STRING(500),
allowNull: true,
comment: '打印模板链接',
});
},
/**
* 回滚迁移:删除 template_url 字段(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @return {Promise<void>} 无返回值
*/
async down(queryInterface) {
const tableName = 'wms_express_interface';
const columns = await queryInterface.describeTable(tableName);
if (!columns.template_url) {
return;
}
await queryInterface.removeColumn(tableName, 'template_url');
},
};

View File

@ -0,0 +1,46 @@
'use strict';
/**
* 为订单快递表新增打印版本号字段 ver。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
module.exports = {
/**
* 执行迁移:新增 ver 字段(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
async up(queryInterface, Sequelize) {
const tableName = 'wms_order_express';
const columns = await queryInterface.describeTable(tableName);
if (columns.ver) {
return;
}
await queryInterface.addColumn(tableName, 'ver', {
type: Sequelize.STRING(50),
allowNull: true,
comment: '打印版本号',
});
},
/**
* 回滚迁移:删除 ver 字段(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @return {Promise<void>} 无返回值
*/
async down(queryInterface) {
const tableName = 'wms_order_express';
const columns = await queryInterface.describeTable(tableName);
if (!columns.ver) {
return;
}
await queryInterface.removeColumn(tableName, 'ver');
},
};

View File

@ -0,0 +1,68 @@
'use strict';
const TABLE_NAME = 'wms_print_platform';
const COLUMN_NAME = 'platid';
/**
* 获取当前数据库已存在的表名集合。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<Set<string>>} 表名集合。
*/
const getExistingTableSet = async queryInterface => {
const tables = await queryInterface.showAllTables();
return new Set(
tables.map(table => (typeof table === 'string' ? table : table.tableName))
);
};
/**
* 构建打印平台 platid 字段定义。
* @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。
* @return {Object} 字段定义。
*/
const buildPlatidColumn = Sequelize => ({
type: Sequelize.INTEGER(11),
allowNull: true,
comment: '平台ID',
});
module.exports = {
/**
* 执行迁移:为打印平台表新增 platid 字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。
* @return {Promise<void>} 无返回值。
*/
async up(queryInterface, Sequelize) {
const existingTableSet = await getExistingTableSet(queryInterface);
if (!existingTableSet.has(TABLE_NAME)) {
return;
}
const columns = await queryInterface.describeTable(TABLE_NAME);
if (columns[COLUMN_NAME]) {
return;
}
await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, buildPlatidColumn(Sequelize));
},
/**
* 回滚迁移:删除打印平台表的 platid 字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
async down(queryInterface) {
const existingTableSet = await getExistingTableSet(queryInterface);
if (!existingTableSet.has(TABLE_NAME)) {
return;
}
const columns = await queryInterface.describeTable(TABLE_NAME);
if (!columns[COLUMN_NAME]) {
return;
}
await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME);
},
};

BIN
final_sf.json Normal file

Binary file not shown.

View File

@ -2107,5 +2107,264 @@
],
"type": "added",
"module": "index"
},
{
"version": "2026.05.22-system-07",
"date": "2026-05-22",
"summary": "同步快递接口文档:is_share 仅展示不可编辑",
"methods": [
"setting.expressInterface.list",
"setting.expressInterface.create",
"setting.expressInterface.update"
],
"notes": [
"create/update 不再接受 is_share",
"list 仍可返回 is_share 作为展示信息",
"仅文档同步,不改业务代码"
],
"type": "updated",
"module": "setting.expressInterface"
},
{
"version": "2026.05.22-system-08",
"date": "2026-05-22",
"summary": "同步快递接口列表文档,移除未返回字段说明",
"methods": [
"setting.expressInterface.list"
],
"notes": [
"根据 app/service/systems/setting/expressInterface.js 的 list() 查询字段与 normalizeInterfaceRow() 返回结构,同步 setting.expressInterface.list 不返回 token。",
"按当前实现清理 response.children 中未返回的 share_id、can_use_count 字段说明。",
"保留 is_share,并明确其仅用于展示,不作为编辑入参。"
],
"type": "updated",
"module": "setting.expressInterface"
},
{
"version": "2026.05.22-system-09",
"date": "2026-05-22",
"summary": "index.getShopList 支持按平台编码筛选店铺",
"methods": [
"index.getShopList"
],
"notes": [
"index.getShopList 兼容 platform_code 与 platformCode 两种传参方式,服务端按 platform_code、platformCode 顺序读取首个 trim 后非空值作为平台筛选条件。",
"未传平台参数时返回当前登录仓库下全部已授权店铺;传入非空平台编码时仅返回该平台的已授权店铺。",
"本次仅补充筛选条件文档,不影响返回结构、排序规则与 owner_id/access_token/refresh_token/auth_random_code 的脱敏规则。",
"仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改任何业务代码。"
],
"type": "updated",
"module": "index"
},
{
"version": "2026.05.22-system-10",
"date": "2026-05-22",
"summary": "快递接口配置新增 shop_id 字段",
"methods": [
"setting.expressInterface.create",
"setting.expressInterface.update",
"setting.expressInterface.list"
],
"notes": [
"create/update 支持 shop_id/shopId(兼容 snake_case 与 camelCase),为店铺 ID,未传或空值按 null 处理。",
"list 返回 shop_id 字段,列表 where 支持按 shop_id 过滤。"
],
"type": "updated"
},
{
"version": "2026.05.22-system-11",
"date": "2026-05-22",
"summary": "调整快递接口列表排序规则",
"methods": [
"setting.expressInterface.list"
],
"notes": [
"setting.expressInterface.list 改为按 weight ASC, id DESC 排序;优先按权重排序,权重相同再按 id 倒序。",
"本次仅同步该接口排序说明,不影响返回结构。"
],
"type": "updated",
"module": "setting.expressInterface"
},
{
"version": "2026.05.22-system-12",
"date": "2026-05-22",
"summary": "index.getShopExpressList 返回新增系统快递编码",
"methods": [
"index.getShopExpressList"
],
"notes": [
"data.list[*] 新增 sys_express_code 字段,由平台快递编码 wp_code 映射系统快递编码,未匹配时返回空字符串。",
"补充 data.list[*].wp_name 说明:由系统快递基础表根据平台快递编码映射得到名称,未匹配时返回空字符串。",
"原有请求参数、鉴权方式与返回主结构保持不变。",
"仅文档同步,不改业务代码。"
],
"type": "updated",
"module": "index"
},
{
"version": "2026.05.23-system-01",
"date": "2026-05-23",
"summary": "补充快递接口列表 is_system_express_code 返回字段说明",
"methods": [
"setting.expressInterface.list"
],
"notes": [
"在 setting.expressInterface.list 的 response.children 中补充 is_system_express_code 字段说明。",
"该字段表示当前行 express_code 是否为系统快递编码;不是系统快递编码返回 0,否则返回 1。",
"仅文档同步,不改业务代码。"
],
"type": "updated",
"module": "setting.expressInterface"
},
{
"version": "2026.05.23-system-02",
"date": "2026-05-23",
"summary": "完善 index.getExpressList 文档:补充过滤规则、返回字段与仓库维度行为",
"methods": [
"index.getExpressList"
],
"notes": [
"补充 `systemOnly`、`express_code`、`expressCode` 的真实入参语义,明确真值识别规则与字段优先级。",
"补充默认模式、系统模式、按快递编码过滤模式下的返回差异,说明当前登录仓库维度来自 `ctx.user.store_id`。",
"补充 `data[*]` 各字段含义,明确系统基础快递与仓库自定义快递编码的差异字段。",
"仅文档同步,不修改业务代码。"
],
"type": "updated",
"module": "index"
},
{
"version": "2026.05.24-system-01",
"date": "2026-05-24",
"summary": "同步 index.getExpressList 文档:移除 expressCode 别名并明确 express_code 筛选语义",
"methods": [
"index.getExpressList"
],
"notes": [
"移除 index.getExpressList 文档中的 expressCode 驼峰别名参数,仅保留 express_code。",
"明确当 systemOnly=false 且传入 express_code 时,接口按自定义映射记录中的系统快递编码字段 express_code 过滤,而不是按自定义 code 过滤。",
"保留 systemOnly=true 按系统快递编码过滤系统基础快递列表,以及默认合并逻辑、缓存优先、仓库维度来源不变的说明。"
],
"type": "updated"
},
{
"version": "2026.05.24-system-02",
"date": "2026-05-24",
"summary": "新增 index.getCainiaoStfTemplates 接口文档并明确模板返回语义",
"methods": [
"index.getCainiaoStfTemplates"
],
"notes": [
"新增无参接口 index.getCainiaoStfTemplates:从当前仓库首个已授权 TB 店铺发起 cainiao.waybill.ii.search 查询菜鸟 STF 模板。",
"补充返回结构说明:data.platform_code 固定为 TB;data.list 返回模板数组并包含 template_id/template_name/template_url/cp_code/wp_code 字段。",
"明确模板列表为宽松结构解析并按 template_id/template_name/template_url 核心语义去重。",
"补充错误码说明:未识别仓库返回 400;当前仓库无已授权 TB 店铺返回 404。"
],
"type": "added"
},
{
"version": "2026.05.24-system-03",
"date": "2026-05-24",
"summary": "调整 index.getCainiaoStfTemplates 为免登录/免鉴权接口",
"methods": [
"index.getCainiaoStfTemplates"
],
"notes": [
"将 index.getCainiaoStfTemplates 的 isNeedLogin 调整为 false,接口改为免登录访问。",
"保持 isNeedAuth=false,并同步免权限拦截配置,避免登录态与鉴权拦截。",
"该接口仍为无请求参数,headers 调整为空数组。"
],
"type": "updated",
"module": "index"
},
{
"version": "2026.05.24-system-04",
"date": "2026-05-24",
"summary": "调整 index.getCainiaoStfTemplates 为公共无参模板查询接口",
"methods": [
"index.getCainiaoStfTemplates"
],
"notes": [
"index.getCainiaoStfTemplates 改为公共无参查询,不再依赖当前仓库、登录态或店铺授权。",
"接口直接调用 requestTbWaybillSearch({ cpCode: '' }) 查询公共模板,返回 data.platform_code='TB' 与模板数组。",
"requestTbWaybillSearch 支持 accessToken 缺失时不下发 session,因此该接口不再依赖 session。"
],
"type": "updated"
},
{
"version": "2026.05.24-system-05",
"date": "2026-05-24",
"summary": "同步 index.getCainiaoStfTemplates 改用淘宝标准模板公共接口",
"methods": [
"index.getCainiaoStfTemplates"
],
"notes": [
"index.getCainiaoStfTemplates 改为调用淘宝开放平台 cainiao.cloudprint.stdtemplates.get,不再复用 cainiao.waybill.ii.search。",
"接口不需要用户授权,不下发 session,继续使用 https://eco.taobao.com/router/rest 与 TOP 公共签名参数。",
"模板列表改为从 cainiao_cloudprint_stdtemplates_get_response.result.datas[*].standard_templates[*] 做宽松兼容解析,统一返回 template_id/template_name/template_url/cp_code/wp_code。"
],
"type": "updated"
},
{
"version": "2026.05.24-system-06",
"date": "2026-05-24",
"summary": "新增 index.getPrintPlatformList 接口文档并明确打印平台下拉返回结构",
"methods": [
"index.getPrintPlatformList"
],
"notes": [
"新增 index.getPrintPlatformList 文档,说明该接口供快递接口新增/编辑页下拉选择使用。",
"补充接口行为:仅返回未删除且状态为 ACTIVE 的打印平台,不分页,按 platform_name 与 id 升序返回。",
"补充 data[*] 返回字段说明,明确 code/name/value/label/platform_code/platform_name/status/remark 的含义。",
"仅文档同步,不修改业务代码。"
],
"type": "added",
"module": "index"
},
{
"version": "2026.05.24-system-07",
"date": "2026-05-24",
"summary": "新增 index.getPrintPlatformTemplateList 文档,明确 express_code 必填与模板过滤语义",
"methods": [
"index.getPrintPlatformTemplateList"
],
"notes": [
"新增 index.getPrintPlatformTemplateList 方法文档,补充 platform_code 与 express_code 入参,其中 express_code 标记为必填。",
"明确业务语义:接口按 platform_code(默认 CAINIAO)定位 wms_express 中对应打印平台字段,并使用 express_code 过滤模板结果后返回。",
"补充返回结构 data.platform_code / data.express_code / data.responseData,说明未实现平台返回空对象。",
"仅文档同步,不修改业务代码。"
],
"type": "added",
"module": "index"
},
{
"version": "2026.05.25-system-01",
"date": "2026-05-25",
"summary": "新增 index.polyapiAuthorizeUrl 接口文档并标注免登录免鉴权特征",
"methods": [
"index.polyapiAuthorizeUrl"
],
"notes": [
"新增基础模块方法 index.polyapiAuthorizeUrl,说明其为公共无参接口。",
"明确接口固定调用菠萝派 Differ.JH.BuildeAuthorizeUrl,返回体中以 data.respone 原样包裹上游响应。",
"同步标注 isNeedLogin=false、isNeedAuth=false,headers 为空数组。"
],
"type": "added"
},
{
"version": "2026.05.25-system-02",
"date": "2026-05-25",
"summary": "新增店铺模块相关接口文档(shops.list/add/del/edit)及授权会话接口 shop.GetAuthorizeSessionKey",
"methods": [
"shops.list",
"shops.add",
"shops.del",
"shops.edit",
"shop.GetAuthorizeSessionKey"
],
"notes": [
"同步实现:shops.list 支持 where 分页与 quickWhere 快速搜索;shops.add/edit 校验 platform_code 存在且为 ACTIVE,custom_name 必填且长度限制;shops.del 为软删除,会返回 deleted=true 并清空敏感字段,若存在快递接口引用返回 409;shop.GetAuthorizeSessionKey 对 PDD/CAINIAO 平台生成预占码并返回 authorize_url,其他平台返回 501。",
"字段命名兼容说明:接口实现兼容 snake_case 与 camelCase 入参,文档以 snake_case 为主并注明兼容性。"
],
"type": "added"
}
]

File diff suppressed because it is too large Load Diff

View File

@ -72,6 +72,7 @@
"test:dispatch-factory": "egg-bin test test/app/model/order_delivery_dispatch_factory.test.js",
"cov": "egg-bin cov",
"lint": "eslint .",
"migration:single": "node ./script/run-single-migration.cjs",
"permission:sync:system-api": "node ./script/sync-system-api-permission.cjs",
"check:model-boundary": "node ./script/model-boundary-check.cjs",
"ci": "npm run lint && npm run check:model-boundary && npm run cov"

BIN
raw_redis.json Normal file

Binary file not shown.

BIN
redis_output.txt Normal file

Binary file not shown.

BIN
result_sf.json Normal file

Binary file not shown.

44
run-target-migration.js Normal file
View File

@ -0,0 +1,44 @@
const { Sequelize, DataTypes } = require('sequelize');
const path = require('path');
const config = require('./database/config.js').development;
const migrationFile = '20260524190000-add-ver-to-wms-order-express.js';
const migrationPath = path.resolve(__dirname, 'database', 'migrations', migrationFile);
async function run() {
const sequelize = new Sequelize(config.database, config.username, config.password, {
host: config.host,
port: config.port,
dialect: config.dialect,
logging: console.log,
});
try {
const migration = require(migrationPath);
console.log(`Executing up() for ${migrationFile}...`);
await migration.up(sequelize.getQueryInterface(), Sequelize);
console.log('Migration up() completed.');
const [ results ] = await sequelize.query('SELECT name FROM SequelizeMeta WHERE name = ?', {
replacements: [ migrationFile ],
type: Sequelize.QueryTypes.SELECT,
});
if (!results) {
console.log(`Inserting ${migrationFile} into SequelizeMeta...`);
await sequelize.query('INSERT INTO SequelizeMeta (name) VALUES (?)', {
replacements: [ migrationFile ],
type: Sequelize.QueryTypes.INSERT,
});
console.log('Inserted into SequelizeMeta.');
} else {
console.log(`${migrationFile} already exists in SequelizeMeta.`);
}
} catch (error) {
console.error('Error executing migration script:', error);
process.exit(1);
} finally {
await sequelize.close();
}
}
run();

View File

@ -3,7 +3,13 @@ const fs = require('fs');
const SequelizeLib = require('sequelize');
(async () => {
const migrationName = '20260507100000-create-wms_order_wave_strategy_match.js';
const migrationName = process.argv[2] || process.env.MIGRATION_NAME;
if (!migrationName) {
console.error('ERROR: 必须通过命令行参数或环境变量 MIGRATION_NAME 传入迁移文件名。');
console.error('USAGE: node ./script/run-single-migration.cjs 20260523130000-add-cainiao-to-wms-express.js');
process.exitCode = 2;
return;
}
const migrationPath = path.join(__dirname, '..', 'database', 'migrations', migrationName);
if (!fs.existsSync(migrationPath)) {
console.error('ERROR: migration file not found:', migrationPath);

BIN
temp.json Normal file

Binary file not shown.

View File

@ -117,4 +117,234 @@ describe('test/app/controller/home.test.js', () => {
''
);
});
it('buildCainiaoOauthShopUpdatePayload 应正确映射菜鸟授权字段中的淘宝协议字段', async () => {
const controller = Object.create(HomeController.prototype);
const payload = controller.buildCainiaoOauthShopUpdatePayload({
taobao_user_id: 'tb-user-1',
taobao_user_nick: '淘宝店铺A',
access_token: 'tb-access-token',
refresh_token: 'tb-refresh-token',
expire_time: 1767225600000,
refresh_token_valid_time: 1769817600000,
});
assert.equal(payload.owner_id, 'tb-user-1');
assert.equal(payload.shop_name, '淘宝店铺A');
assert.equal(payload.access_token, 'tb-access-token');
assert.equal(payload.refresh_token, 'tb-refresh-token');
assert.equal(payload.token_expires_at.getTime(), 1767225600000);
assert.equal(payload.auth_expire_at.getTime(), 1767225600000);
assert.equal(payload.refresh_token_expires_at.getTime(), 1769817600000);
assert.equal(payload.scope, null);
assert.equal(payload.status, 1);
});
it('buildCainiaoOauthShopUpdatePayload 在 taobao_user_nick 缺失时不应输出 shop_name 字段', async () => {
const controller = Object.create(HomeController.prototype);
const payload = controller.buildCainiaoOauthShopUpdatePayload({
taobao_user_id: 'tb-user-2',
access_token: 'tb-access-token-2',
refresh_token: 'tb-refresh-token-2',
expire_time: 1767225600000,
refresh_token_valid_time: 1769817600000,
});
assert.equal(payload.owner_id, 'tb-user-2');
assert.equal(payload.access_token, 'tb-access-token-2');
assert.equal(payload.refresh_token, 'tb-refresh-token-2');
assert.equal(payload.token_expires_at.getTime(), 1767225600000);
assert.equal(payload.refresh_token_expires_at.getTime(), 1769817600000);
assert.equal(payload.auth_expire_at.getTime(), 1767225600000);
assert.equal(Object.prototype.hasOwnProperty.call(payload, 'shop_name'), false);
});
it('buildCainiaoOauthShopUpdatePayload 应解码 URL 编码的 taobao_user_nick 到 shop_name', async () => {
const controller = Object.create(HomeController.prototype);
const payload = controller.buildCainiaoOauthShopUpdatePayload({
taobao_user_id: 'tb-user-3',
taobao_user_nick: '15325687760%E9%BE%99%E6%B8%8A%E9%80%B8',
access_token: 'tb-access-token-3',
refresh_token: 'tb-refresh-token-3',
expire_time: 1767225600000,
refresh_token_valid_time: 1769817600000,
});
assert.equal(payload.shop_name, '15325687760龙渊逸');
});
it('platformOauthCallback 在 CAINIAO 授权失败时不应进入写库流程', async () => {
const controller = Object.create(HomeController.prototype);
let findOneCallCount = 0;
let updateCainiaoOauthShopCallCount = 0;
let renderArgs = null;
controller.app = {
config: {
platformOauthReservationCodePrefix: '',
},
Sequelize: {
Op: {
or: Symbol('or'),
ne: Symbol('ne'),
},
},
};
controller.cainiao = async code => {
assert.equal(code, 'oauth-code-tb-error');
return {
success: false,
message: '菜鸟授权失败:invalid_client',
result: {
data: {
error: 'invalid_client',
},
},
};
};
controller.updateCainiaoOauthShop = async () => {
updateCainiaoOauthShopCallCount += 1;
throw new Error('CAINIAO 授权失败场景不应调用 updateCainiaoOauthShop');
};
controller.ctx = {
query: {
code: 'oauth-code-tb-error',
state: 'CAINIAO_auth-random-tb-error',
},
model: {
Shop: {
async findOne() {
findOneCallCount += 1;
throw new Error('CAINIAO 授权失败场景不应查询店铺');
},
},
},
async render(view, data) {
renderArgs = { view, data };
},
status: null,
};
await controller.platformOauthCallback();
assert.equal(findOneCallCount, 0);
assert.equal(updateCainiaoOauthShopCallCount, 0);
assert.equal(controller.ctx.status, 400);
assert.equal(renderArgs.view, 'platform_oauth_callback.html');
assert.equal(renderArgs.data.platformCode, 'CAINIAO');
assert.equal(renderArgs.data.resultLevel, 'error');
assert.equal(renderArgs.data.resultText, '菜鸟授权失败:invalid_client');
});
it('platformOauthCallback 在 CAINIAO 场景找到店铺时应写回关键字段', async () => {
const controller = Object.create(HomeController.prototype);
const orOperator = Symbol('or');
const neOperator = Symbol('ne');
const findOneCalls = [];
const saveCalls = [];
let renderArgs = null;
const pendingShop = {
id: 1001,
warehouse_id: 2001,
platform_code: 'CAINIAO',
shop_name: '待授权店铺',
status: 0,
set(payload) {
Object.assign(this, payload);
},
async save(options) {
saveCalls.push(options);
return this;
},
async destroy() {
throw new Error('当前场景不应删除原店铺');
},
};
controller.app = {
config: {
platformOauthReservationCodePrefix: '',
},
Sequelize: {
Op: {
or: orOperator,
ne: neOperator,
},
},
};
controller.cainiao = async code => {
assert.equal(code, 'oauth-code-3');
return {
success: true,
result: {
data: {
taobao_user_id: 'tb-user-3',
taobao_user_nick: '淘宝店铺C',
access_token: 'tb-access-token-3',
refresh_token: 'tb-refresh-token-3',
expire_time: 1767225600000,
refresh_token_valid_time: 1769817600000,
},
},
};
};
controller.ctx = {
query: {
code: 'oauth-code-3',
state: 'CAINIAO_auth-random-3',
},
model: {
transaction: async callback => await callback({ id: 'tx-1' }),
Shop: {
async findOne(options) {
findOneCalls.push(options);
if (options.where && options.where.auth_random_code === 'auth-random-3') {
return pendingShop;
}
if (options.where && options.where[orOperator]) {
return null;
}
throw new Error('未预期的 Shop 查询');
},
},
},
async render(view, data) {
renderArgs = { view, data };
},
status: null,
};
await controller.platformOauthCallback();
assert.equal(findOneCalls.length, 2);
assert.equal(pendingShop.owner_id, 'tb-user-3');
assert.equal(pendingShop.shop_name, '淘宝店铺C');
assert.equal(pendingShop.access_token, 'tb-access-token-3');
assert.equal(pendingShop.refresh_token, 'tb-refresh-token-3');
assert.equal(pendingShop.token_expires_at.getTime(), 1767225600000);
assert.equal(pendingShop.auth_expire_at.getTime(), 1767225600000);
assert.equal(pendingShop.refresh_token_expires_at.getTime(), 1769817600000);
assert.equal(pendingShop.status, 1);
assert.equal(saveCalls.length, 1);
assert.deepEqual(saveCalls[0].fields, [
'owner_id',
'shop_name',
'access_token',
'refresh_token',
'token_expires_at',
'refresh_token_expires_at',
'auth_expire_at',
'scope',
'status',
]);
assert.equal(controller.ctx.status, 200);
assert.equal(renderArgs.view, 'platform_oauth_callback.html');
assert.equal(renderArgs.data.platformCode, 'CAINIAO');
assert.equal(renderArgs.data.resultLevel, 'warning');
});
});

View File

@ -89,4 +89,4 @@ describe('test/app/lib/pdd_client.test.js', () => {
assert.equal(requestOptions.options.data.client_id, 'override-client-id');
assert.notEqual(requestOptions.options.data.sign, 'E4DE3ED21002510DED352819E7AE6775');
});
});
});

View File

@ -43,4 +43,4 @@ describe('test/app/lib/pdd_sign.test.js', () => {
assert.equal(result.requestBody.page_size, 10);
assert.equal(result.requestBody.data_type, 'XML');
});
});
});

View File

@ -0,0 +1,67 @@
'use strict';
const assert = require('node:assert/strict');
const crypto = require('crypto');
const PoloApiClient = require('../../../app/lib/polo_api_client');
describe('test/app/lib/polo_api_client.test.js', () => {
it('签名应对整串转小写后再做 UTF-8 MD5', async () => {
let requestOptions = null;
const ctx = {
async curl(url, options) {
requestOptions = { url, options };
return {
data: {
code: 0,
msg: 'ok',
},
};
},
};
const client = new PoloApiClient(ctx);
client._formatDate = () => '2026-05-25 10:00:00';
await client.request({
method: 'Differ.JH.BuildeAuthorizeUrl',
bizcontent: {
appKey: 'AbC123',
callbackUrl: 'http://Example.com/CallBack',
},
config: {
interface_url: 'http://aliyun.polyapi.com/OpenAPI/do',
appkey: 'AppKeyXyZ',
app_secret: 'SeCrEt',
platid: '633',
version: '1.5',
},
});
const requestBody = new URLSearchParams(requestOptions.options.content);
const signMap = {
method: 'Differ.JH.BuildeAuthorizeUrl',
appkey: 'AppKeyXyZ',
platid: '633',
version: '1.5',
contenttype: 'json',
bizcontent: JSON.stringify({
appKey: 'AbC123',
callbackUrl: 'http://Example.com/CallBack',
}),
timestamp: '2026-05-25 10:00:00',
};
const rawSignText = `SeCrEtappkeyAppKeyXyZbizcontent${JSON.stringify({
appKey: 'AbC123',
callbackUrl: 'http://Example.com/CallBack',
})}contenttypejsonmethodDiffer.JH.BuildeAuthorizeUrlplatid633timestamp2026-05-25 10:00:00version1.5SeCrEt`;
const signText = client._getSignText(signMap, 'SeCrEt');
const expectedSignText = rawSignText.toLowerCase();
const expectedSign = crypto.createHash('md5').update(expectedSignText, 'utf8').digest('hex');
const originalCaseSign = crypto.createHash('md5').update(rawSignText, 'utf8').digest('hex');
assert.equal(signText, expectedSignText);
assert.equal(requestBody.get('sign'), expectedSign);
assert.notEqual(requestBody.get('sign'), originalCaseSign);
});
});

View File

@ -115,4 +115,80 @@ describe('test/app/lib/qimen_client.test.js', () => {
assert.match(sentXml, /<orderLines>\s*<orderLine>/);
assert.doesNotMatch(sentXml, /<orderLine>\s*<orderLine>/);
});
it('should omit customerId and costomer_id when customerId is null', async () => {
const app = {
config: {
qimen: {
appKey: 'WMS_APP_KEY',
security: 'WMS_SECRET',
},
},
formatDate() {
return '2026-04-24 10:00:00';
},
};
const client = new QimenClient(app);
let requestUrl = '';
let requestLogData = null;
client.sendRequest = async (url, requestData, logData) => {
requestUrl = url;
requestLogData = logData;
return {
queryId: 'Q-TEST-2',
res: '<response><flag>success</flag><code>200</code><message>ok</message></response>',
};
};
const runtime = {
ctx: {
app,
service: {
qimen: {
async parseXmlToArray() {
return {
response: {
flag: 'success',
code: '200',
message: 'ok',
},
};
},
async saveQimenLog() {
return 2;
},
},
systems: {
sign: {
async toXml(payload) {
assert.ok(payload && payload.request, 'request 根节点应已封包');
return buildRequestXml(payload);
},
async signTopRequest(queryParams) {
assert.equal(Object.prototype.hasOwnProperty.call(queryParams, 'customerId'), false);
return 'MOCK-SIGN';
},
},
},
},
},
};
const sendResult = await client.send('taobao.qimen.deliveryorder.confirm', null, {
deliveryOrder: {
deliveryOrderCode: 'DO-1002',
},
packages: {
package: [],
},
orderLines: [],
}, runtime);
assert.equal(sendResult.queryId, 'Q-TEST-2');
assert.equal(requestUrl.includes('customerId='), false);
assert.ok(requestLogData);
assert.equal(Object.prototype.hasOwnProperty.call(requestLogData, 'costomer_id'), false);
});
});

File diff suppressed because it is too large Load Diff

View File

@ -103,6 +103,10 @@ function createHarness(orderRows = []) {
return true;
}
if (sql.includes(`${totalExpr} > 0`) && total <= 0) {
return false;
}
const { noneExpr, finExpr, errorExpr, withError } = config;
if (sql.includes(`${finExpr} = ${totalExpr}`) && sql.includes(`${totalExpr} > 0`)) {
@ -240,6 +244,14 @@ async function getBatchListResult(orderRows, where = {}) {
}
describe('test/app/service/systemMethods/order/wave.batchList.assignmentStatus.test.js', () => {
it('should filter out waves whose order count is 0', async () => {
const { result } = await getBatchListResult([]);
assert.equal(result.flag, 'success');
assert.equal(result.list.length, 0);
assert.equal(result.pagination.total, 0);
});
it('should keep original behavior when where.storage_assignment_status is missing', async () => {
const { result } = await getBatchListResult([
{ wave_id: 1, storage_status: 'error', post_status: 'none', print_status: 'none' },

View File

@ -180,6 +180,7 @@ describe('test/app/service/systemMethods/setting/expressInterface.test.js', () =
townName: '张江镇',
isPickup: 1,
shipperNo: 'SHIP-001',
templateUrl: 'https://example.com/template/create',
extData: {
mode: 'A4',
},
@ -197,6 +198,7 @@ describe('test/app/service/systemMethods/setting/expressInterface.test.js', () =
town_name: '粤海街道',
ispickup: 0,
shipperno: 'SHIP-002',
template_url: 'https://example.com/template/update',
ext_data: {
mode: 'thermal',
},
@ -221,6 +223,7 @@ describe('test/app/service/systemMethods/setting/expressInterface.test.js', () =
town_name: '张江镇',
ispickup: 1,
shipperno: 'SHIP-001',
template_url: 'https://example.com/template/create',
ext_data: {
mode: 'A4',
},
@ -239,6 +242,7 @@ describe('test/app/service/systemMethods/setting/expressInterface.test.js', () =
town_name: '粤海街道',
ispickup: 0,
shipperno: 'SHIP-002',
template_url: 'https://example.com/template/update',
ext_data: {
mode: 'thermal',
},

View File

@ -0,0 +1,167 @@
'use strict';
const assert = require('node:assert/strict');
const ShopsMethodService = require('../../../../app/service/systemMethods/shops');
function createHarness() {
const calls = {
list: [],
add: [],
del: [],
edit: [],
getAuthorizeSessionKey: [],
prepareWhereContext: [],
};
const ctx = {
app: {
config: {
jwt: {},
},
Sequelize: {},
},
user: {
store_id: 100000,
},
service: {
systems: {
shops: {
getListWhereSpecialFieldMap() {
return {
id: { field: 'id' },
};
},
async list(payload) {
calls.list.push(payload);
return {
list: [],
pagination: {
page: 1,
pageSize: 20,
total: 0,
totalPages: 0,
hasNext: false,
hasPrevious: false,
},
};
},
async add(payload) {
calls.add.push(payload);
return { id: 1 };
},
async del(payload) {
calls.del.push(payload);
return { deleted: true, id: 1 };
},
async edit(payload) {
calls.edit.push(payload);
return { updated: true, id: 1 };
},
async getAuthorizeSessionKey(payload) {
calls.getAuthorizeSessionKey.push(payload);
return {
shop_id: 1,
session_key: 'session-key',
authorize_url: 'https://oauth.example.com/state',
};
},
},
},
},
};
const service = new ShopsMethodService(ctx);
service.prepareWhereContext = function prepareWhereContext(data, options) {
calls.prepareWhereContext.push({ data, options });
return { where: data.where || {} };
};
return {
service,
calls,
};
}
describe('test/app/service/systemMethods/shops.test.js', () => {
it('shops.list 应注入 where 解析并返回统一结构', async () => {
const { service, calls } = createHarness();
const result = await service.list({
page: 1,
pageSize: 20,
where: {
id: {
operator: 'eq',
value: 1,
},
},
});
assert.equal(result.flag, 'success');
assert.equal(result.code, 200);
assert.equal(calls.prepareWhereContext.length, 1);
assert.equal(calls.list.length, 1);
});
it('shops.add 应解构并透传 custom_name/platform_code/shop_name', async () => {
const { service, calls } = createHarness();
const result = await service.add({
custom_name: '自定义店铺A',
platformCode: 'pdd',
shop_name: '店铺A',
});
assert.equal(result.flag, 'success');
assert.deepEqual(calls.add[0], {
custom_name: '自定义店铺A',
platform_code: 'pdd',
shop_name: '店铺A',
});
});
it('shops.del 应兼容 shop_id 并映射为 id', async () => {
const { service, calls } = createHarness();
const result = await service.del({
shop_id: 22,
});
assert.equal(result.flag, 'success');
assert.deepEqual(calls.del[0], {
id: 22,
});
});
it('shops.edit 只透传存在的可编辑字段', async () => {
const { service, calls } = createHarness();
const result = await service.edit({
id: 5,
customName: '新名称',
platform_code: 'CAINIAO',
});
assert.equal(result.flag, 'success');
assert.deepEqual(calls.edit[0], {
id: 5,
custom_name: '新名称',
platform_code: 'CAINIAO',
});
});
it('shop.GetAuthorizeSessionKey 应兼容 callback_url 与 shopId', async () => {
const { service, calls } = createHarness();
const result = await service.GetAuthorizeSessionKey({
shopId: 7,
callback_url: 'https://callback.example.com',
});
assert.equal(result.flag, 'success');
assert.deepEqual(calls.getAuthorizeSessionKey[0], {
id: 7,
callbackurl: 'https://callback.example.com',
});
});
});

View File

@ -8,8 +8,10 @@ function createAsyncDispatchHarness(options = {}) {
sequence: [],
polyapi: 0,
polyapiInput: null,
polyapiInputs: [],
cainiao: 0,
cainiaoInput: null,
cainiaoInputs: [],
orderExpressDestroy: 0,
orderExpressDestroyOptions: null,
orderDeliveryUpdate: 0,
@ -71,6 +73,7 @@ function createAsyncDispatchHarness(options = {}) {
ctx.service.systems.expressPlatform.polyapi = async data => {
calls.polyapi += 1;
calls.polyapiInput = data;
calls.polyapiInputs.push(data);
return {
flag: 'success',
message: 'ok',
@ -85,6 +88,7 @@ function createAsyncDispatchHarness(options = {}) {
ctx.service.systems.expressPlatform.cainiao = async data => {
calls.cainiao += 1;
calls.cainiaoInput = data;
calls.cainiaoInputs.push(data);
return {
flag: 'success',
message: 'ok',
@ -116,6 +120,45 @@ describe('test/app/service/systems/express.async_dispatch.test.js', () => {
assert.strictEqual(calls.polyapiInput, bizcontent);
});
it('should dispatch cainiao orders one by one but keep polyapi batched', async () => {
const { ctx, calls } = createAsyncDispatchHarness({
enableDefaultCainiao: true,
});
const service = new ExpressService(ctx);
const cainiaoBizcontent = {
matchedPlatform: {
default_express_interface: 'cainiao',
},
orders: [
{ order_id: 101 },
{ order_id: 102 },
],
trace_id: 'trace_async_split',
};
const polyapiBizcontent = {
matchedPlatform: {
default_express_interface: 'polyapi',
},
orders: [
{ order_id: 201 },
{ order_id: 202 },
],
trace_id: 'trace_async_batch',
};
await service.dispatchWaybillAsyncPlatform('cainiao', cainiaoBizcontent);
await service.dispatchWaybillAsyncPlatform('polyapi', polyapiBizcontent);
assert.equal(calls.cainiao, 2);
assert.equal(calls.cainiaoInputs.length, 2);
assert.deepEqual(calls.cainiaoInputs.map(item => item.orders.length), [ 1, 1 ]);
assert.deepEqual(calls.cainiaoInputs.map(item => item.orders[0].order_id), [ 101, 102 ]);
assert.equal(calls.polyapi, 1);
assert.strictEqual(calls.polyapiInput, polyapiBizcontent);
assert.equal(calls.polyapiInputs.length, 1);
assert.equal(calls.polyapiInputs[0].orders.length, 2);
});
it('should throw interface not implemented when platform method is missing', async () => {
const { ctx } = createAsyncDispatchHarness({
serviceMethods: {

View File

@ -906,4 +906,28 @@ describe('test/app/service/systems/express.createWaybillCode.balance.test.js', (
assert.equal(settled, true);
assert.deepEqual(result.orders.map(item => item.order_id), [ 101 ]);
});
it('should use route platform code for async dispatch instead of default_express_interface', async () => {
const { service } = createBalanceHarness();
const dispatchCalls = [];
service.dispatchWaybillAsyncPlatform = async (platformCode, bizcontent) => {
dispatchCalls.push({ platformCode, bizcontent });
return {
flag: 'success',
message: 'ok',
};
};
await service.createWaybillCode(buildWaybillOrders([ 101 ]), {
code: 'PDD',
platform_code: 'LEGACY_CODE',
route_platform_code: 'PDD_ROUTE',
default_express_interface: 'POLYAPI',
});
assert.equal(dispatchCalls.length, 1);
assert.equal(dispatchCalls[0].platformCode, 'PDD_ROUTE');
assert.equal(dispatchCalls[0].bizcontent.matchedPlatform.default_express_interface, 'POLYAPI');
});
});

View File

@ -0,0 +1,254 @@
'use strict';
const assert = require('node:assert/strict');
const ExpressService = require('../../../../app/service/systems/express');
/**
* 创建 createWaybillCodePipeline 的最小测试上下文。
*
* @param {Object} [options={}] 测试覆盖配置。
* @return {{ ctx: Object, calls: Object }} 测试上下文与调用记录。
*/
function createPipelineHarness(options = {}) {
const calls = {
listByWarehousePlatformCodePayloads: [],
asyncTaskPayloads: [],
};
const orderDeliveryRows = Array.isArray(options.orderDeliveryRows)
? options.orderDeliveryRows
: [
{
id: 1,
sys_platform_code: 'PDD',
logistics_code: 'SF',
sys_platform_name: '拼多多',
logistics_name: '顺丰',
store_id: 100000,
},
];
const listData = Array.isArray(options.listData) ? options.listData : [];
const platformList = Array.isArray(options.platformList) ? options.platformList : [{
code: 'PDD',
default_express_interface: 'POLYAPI',
}];
const ctx = {
app: {
Sequelize: {
Op: {
in: 'in',
},
},
},
user: {
store_id: 100000,
},
model: {
OrderDeliveryFactory: {
async getCurrentModel() {
return {
async findAll() {
return orderDeliveryRows;
},
async update() {
return [ 1 ];
},
};
},
},
},
service: {
systems: {
platform: {
async getPlatformList() {
return platformList;
},
},
setting: {
expressInterface: {
async listByWarehousePlatformCode(payload) {
calls.listByWarehousePlatformCodePayloads.push(payload);
return {
data: listData,
};
},
},
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
};
return {
ctx,
calls,
};
}
describe('test/app/service/systems/express.createWaybillCodePipeline.matchExpressInterface.test.js', () => {
it('should choose matched SF interface instead of first YTO item', async () => {
const { ctx, calls } = createPipelineHarness({
orderDeliveryRows: [
{
id: 101,
sys_platform_code: 'PDD',
logistics_code: ' sf ',
sys_platform_name: '拼多多',
logistics_name: '顺丰',
store_id: 100000,
},
],
listData: [
{
id: 11,
sys_express_code: 'YTO',
express_code: 'YTO',
},
{
id: 22,
sys_express_code: ' SF ',
express_code: 'SF',
},
],
});
const service = new ExpressService(ctx);
service.asyncTask = (batch, options, matchedPlatform, expressInterfaceConfig) => {
calls.asyncTaskPayloads.push({ batch, options, matchedPlatform, expressInterfaceConfig });
};
await service.createWaybillCodePipeline([
{
order_id: 101,
business_key: 9001,
},
]);
assert.deepEqual(calls.listByWarehousePlatformCodePayloads[0], {
warehouseId: 100000,
platform_code: 'POLYAPI',
});
assert.equal(calls.asyncTaskPayloads.length, 1);
assert.equal(calls.asyncTaskPayloads[0].matchedPlatform.code, 'PDD');
assert.equal(calls.asyncTaskPayloads[0].expressInterfaceConfig.id, 22);
assert.equal(calls.asyncTaskPayloads[0].expressInterfaceConfig.sys_express_code.trim(), 'SF');
});
it('should not fallback to first item when no interface matches logistics code', async () => {
const { ctx, calls } = createPipelineHarness({
orderDeliveryRows: [
{
id: 102,
sys_platform_code: 'PDD',
logistics_code: 'SF',
sys_platform_name: '拼多多',
logistics_name: '顺丰',
store_id: 100000,
},
],
listData: [
{
id: 31,
sys_express_code: 'YTO',
express_code: 'YTO',
},
],
});
const service = new ExpressService(ctx);
service.asyncTask = (batch, options, matchedPlatform, expressInterfaceConfig) => {
calls.asyncTaskPayloads.push({ batch, options, matchedPlatform, expressInterfaceConfig });
};
await service.createWaybillCodePipeline([
{
order_id: 102,
business_key: 9002,
},
]);
assert.deepEqual(calls.listByWarehousePlatformCodePayloads[0], {
warehouseId: 100000,
platform_code: 'POLYAPI',
});
assert.equal(calls.asyncTaskPayloads.length, 1);
assert.equal(calls.asyncTaskPayloads[0].matchedPlatform.code, 'PDD');
assert.equal(calls.asyncTaskPayloads[0].expressInterfaceConfig, null);
});
it('should fallback to sys platform code when print platform code is absent', async () => {
const { ctx, calls } = createPipelineHarness({
platformList: [
{
code: 'PDD',
default_express_interface: '',
},
],
listData: [
{
id: 41,
sys_express_code: 'SF',
express_code: 'SF',
},
],
});
const service = new ExpressService(ctx);
service.asyncTask = (batch, options, matchedPlatform, expressInterfaceConfig) => {
calls.asyncTaskPayloads.push({ batch, options, matchedPlatform, expressInterfaceConfig });
};
await service.createWaybillCodePipeline([
{
order_id: 1,
business_key: 1,
},
]);
assert.deepEqual(calls.listByWarehousePlatformCodePayloads[0], {
warehouseId: 100000,
platform_code: 'PDD',
});
assert.equal(calls.asyncTaskPayloads[0].expressInterfaceConfig.id, 41);
});
it('should keep route platform code and default_express_interface with different values', async () => {
const { ctx, calls } = createPipelineHarness({
platformList: [
{
code: 'PDD',
route_platform_code: 'PDD_ROUTE',
default_express_interface: 'POLYAPI',
},
],
listData: [
{
id: 51,
sys_express_code: 'SF',
express_code: 'SF',
},
],
});
const service = new ExpressService(ctx);
service.asyncTask = (batch, options, matchedPlatform, expressInterfaceConfig) => {
calls.asyncTaskPayloads.push({ batch, options, matchedPlatform, expressInterfaceConfig });
};
await service.createWaybillCodePipeline([
{
order_id: 1,
business_key: 1,
},
]);
assert.deepEqual(calls.listByWarehousePlatformCodePayloads[0], {
warehouseId: 100000,
platform_code: 'POLYAPI',
});
assert.equal(calls.asyncTaskPayloads[0].matchedPlatform.route_platform_code, 'PDD_ROUTE');
assert.equal(calls.asyncTaskPayloads[0].matchedPlatform.default_express_interface, 'POLYAPI');
});
});

View File

@ -9,11 +9,26 @@ function createExpressServiceHarness(options = {}) {
expressFindAll: 0,
expressSettingFindAll: 0,
expressProductTypeFindAll: 0,
expressProductTypeCreate: 0,
expressProductTypeUpdate: 0,
orderDeliveryFindAll: 0,
getCache: 0,
setCache: 0,
delCache: 0,
};
const expressProductTypeRows = Array.isArray(options.expressProductTypeRows)
? options.expressProductTypeRows.map((item, index) => ({
id: Number(item.id || index + 1),
code: item.code,
name: item.name,
express_code: item.express_code,
}))
: [
{ id: 1, code: 'SF-EXP', name: '顺丰标准', express_code: 'SF' },
{ id: 2, code: 'SF-ECON', name: '顺丰经济', express_code: 'SF' },
];
const orderDeliveryRows = Array.isArray(options.orderDeliveryRows) ? options.orderDeliveryRows : [];
const orderDeliveryModel = {
async findAll(query) {
@ -46,6 +61,13 @@ function createExpressServiceHarness(options = {}) {
return await options.setCacheAsync(cacheKey, value, ttl);
}
},
async delCacheAsync(cacheKey) {
calls.delCache += 1;
calls.delCacheKey = cacheKey;
if (typeof options.delCacheAsync === 'function') {
return await options.delCacheAsync(cacheKey);
}
},
},
user: options.user || null,
model: {
@ -68,17 +90,57 @@ function createExpressServiceHarness(options = {}) {
async findAll(query) {
calls.expressSettingFindAll += 1;
calls.expressSettingFindAllQuery = query;
return options.expressSettingRows || [];
const where = query && query.where ? query.where : {};
let rows = Array.isArray(options.expressSettingRows) ? options.expressSettingRows : [];
if (where.warehouse_id !== undefined) {
rows = rows.filter(item => Number(item.warehouse_id) === Number(where.warehouse_id));
}
if (where.express_code) {
rows = rows.filter(item => String(item.express_code) === String(where.express_code));
}
return rows;
},
},
ExpressProductType: {
async findAll(query) {
calls.expressProductTypeFindAll += 1;
calls.expressProductTypeFindAllQuery = query;
return options.expressProductTypeRows || [
{ code: 'SF-EXP', name: '顺丰标准', express_code: 'SF' },
{ code: 'SF-ECON', name: '顺丰经济', express_code: 'SF' },
];
const where = query && query.where ? query.where : null;
let rows = expressProductTypeRows;
if (where && where.express_code) {
rows = rows.filter(item => item.express_code === where.express_code);
}
if (where && where.code && typeof where.code === 'object' && Array.isArray(where.code.in)) {
const codeSet = new Set(where.code.in.map(item => String(item)));
rows = rows.filter(item => codeSet.has(String(item.code)));
}
return rows;
},
async create(values) {
calls.expressProductTypeCreate += 1;
const created = {
id: expressProductTypeRows.length + 1,
...values,
};
expressProductTypeRows.push(created);
return created;
},
async update(values, optionsForUpdate) {
calls.expressProductTypeUpdate += 1;
const where = optionsForUpdate && optionsForUpdate.where ? optionsForUpdate.where : {};
for (const row of expressProductTypeRows) {
if (where.id && Number(row.id) !== Number(where.id)) {
continue;
}
Object.assign(row, values);
}
return [ 1 ];
},
},
},
@ -288,12 +350,14 @@ describe('test/app/service/systems/express.test.js', () => {
const { ctx } = createExpressServiceHarness();
let serviceCalls = 0;
let receivedSystemOnly = null;
let receivedExpressCode = null;
ctx.service = {
systems: {
express: {
async getExpressList(systemOnly) {
async getExpressList(systemOnly, expressCode) {
serviceCalls += 1;
receivedSystemOnly = systemOnly;
receivedExpressCode = expressCode;
return [
{ code: 'STO', name: '顺丰', value: 'STO', label: '顺丰' },
];
@ -307,6 +371,7 @@ describe('test/app/service/systems/express.test.js', () => {
assert.equal(serviceCalls, 1);
assert.equal(receivedSystemOnly, false);
assert.equal(receivedExpressCode, '');
assert.equal(result.flag, 'success');
assert.equal(result.message, 'ok');
assert.equal(result.code, 200);
@ -319,12 +384,14 @@ describe('test/app/service/systems/express.test.js', () => {
const { ctx } = createExpressServiceHarness();
let serviceCalls = 0;
let receivedSystemOnly = null;
let receivedExpressCode = null;
ctx.service = {
systems: {
express: {
async getExpressList(systemOnly) {
async getExpressList(systemOnly, expressCode) {
serviceCalls += 1;
receivedSystemOnly = systemOnly;
receivedExpressCode = expressCode;
return [
{ code: 'SF', name: '顺丰', value: 'SF', label: '顺丰' },
];
@ -338,6 +405,7 @@ describe('test/app/service/systems/express.test.js', () => {
assert.equal(serviceCalls, 1);
assert.equal(receivedSystemOnly, true);
assert.equal(receivedExpressCode, '');
assert.equal(result.flag, 'success');
assert.equal(result.message, 'ok');
assert.equal(result.code, 200);
@ -346,6 +414,102 @@ describe('test/app/service/systems/express.test.js', () => {
]);
});
it('should delegate index.getExpressList with express_code to the express service', async () => {
const { ctx } = createExpressServiceHarness();
let serviceCalls = 0;
let receivedSystemOnly = null;
let receivedExpressCode = null;
ctx.service = {
systems: {
express: {
async getExpressList(systemOnly, expressCode) {
serviceCalls += 1;
receivedSystemOnly = systemOnly;
receivedExpressCode = expressCode;
return [
{ code: 'SF-001', name: 'SF-001 (顺丰)', value: 'SF-001', label: 'SF-001 (顺丰)', express_code: 'SF' },
];
},
},
},
};
const methodService = new IndexMethodService(ctx);
const result = await methodService.getExpressList({ express_code: 'SF' });
assert.equal(serviceCalls, 1);
assert.equal(receivedSystemOnly, false);
assert.equal(receivedExpressCode, 'SF');
assert.equal(result.flag, 'success');
assert.equal(result.message, 'ok');
assert.equal(result.code, 200);
assert.deepEqual(result.data, [
{ code: 'SF-001', name: 'SF-001 (顺丰)', value: 'SF-001', label: 'SF-001 (顺丰)', express_code: 'SF' },
]);
});
it('should not read expressCode alias in index.getExpressList', async () => {
const { ctx } = createExpressServiceHarness();
let serviceCalls = 0;
let receivedSystemOnly = null;
let receivedExpressCode = null;
ctx.service = {
systems: {
express: {
async getExpressList(systemOnly, expressCode) {
serviceCalls += 1;
receivedSystemOnly = systemOnly;
receivedExpressCode = expressCode;
return [];
},
},
},
};
const methodService = new IndexMethodService(ctx);
const result = await methodService.getExpressList({ expressCode: 'SF' });
assert.equal(serviceCalls, 1);
assert.equal(receivedSystemOnly, false);
assert.equal(receivedExpressCode, '');
assert.equal(result.flag, 'success');
assert.equal(result.message, 'ok');
assert.equal(result.code, 200);
assert.deepEqual(result.data, []);
});
it('should return custom code list by system express_code for current warehouse', async () => {
const { ctx, calls } = createExpressServiceHarness({
user: {
store_id: 100000,
},
rows: [
{ code: 'SF', name: '顺丰' },
],
expressSettingRows: [
{ id: 31, code: 'SF-001', name: '顺丰设置1', express_code: 'SF', warehouse_id: 100000 },
{ id: 32, code: 'SF-002', name: '顺丰设置2', express_code: 'SF', warehouse_id: 100000 },
{ id: 33, code: 'SF', name: '同名自定义编码但系统编码不匹配', express_code: 'YTO', warehouse_id: 100000 },
],
});
const service = new ExpressService(ctx);
const result = await service.getExpressList(false, 'sf');
assert.equal(calls.getCache, 1);
assert.equal(calls.expressFindAll, 1);
assert.equal(calls.expressSettingFindAll, 1);
assert.equal(calls.cachePayload.cacheKey, 'express:list:100000:express:SF');
assert.deepEqual(calls.expressSettingFindAllQuery.where, {
warehouse_id: 100000,
express_code: 'SF',
});
assert.deepEqual(result, [
{ code: 'SF-001', name: 'SF-001 (顺丰)', value: 'SF-001', label: 'SF-001 (顺丰)', express_code: 'SF', is_system_setting: true, id: 31, alias: '顺丰设置1' },
{ code: 'SF-002', name: 'SF-002 (顺丰)', value: 'SF-002', label: 'SF-002 (顺丰)', express_code: 'SF', is_system_setting: true, id: 32, alias: '顺丰设置2' },
]);
});
it('should delegate index.getExpressProductTypeList to the express service', async () => {
const { ctx } = createExpressServiceHarness();
let serviceCalls = 0;
@ -377,6 +541,87 @@ describe('test/app/service/systems/express.test.js', () => {
]);
});
it('should sync PDD SF timed-delivery type_desc into express product types with idempotency', async () => {
const { ctx, calls } = createExpressServiceHarness({
expressProductTypeRows: [
{ id: 1, code: 'T6', name: '旧名称', express_code: 'SF' },
],
});
const service = new ExpressService(ctx);
const payload = {
shopExpressList: [
{
sys_express_code: 'SF',
accounts: [
{
services: [
{
service_code: 'TIMED-DELIVERY',
attributes: [
{
type_desc: '{"T6":"特快","T7":"标快"}',
},
],
},
],
},
],
},
{
sys_express_code: 'SF',
accounts: [
{
services: [
{
service_code: 'OTHER-SERVICE',
attributes: [
{
type_desc: '{"X1":"无效"}',
},
],
},
],
},
],
},
{
sys_express_code: 'YTO',
accounts: [
{
services: [
{
service_code: 'TIMED-DELIVERY',
attributes: [
{
type_desc: '{"Y1":"圆通"}',
},
],
},
],
},
],
},
],
};
const firstResult = await service.syncPddSfTimedDeliveryExpressProductTypes(payload);
const secondResult = await service.syncPddSfTimedDeliveryExpressProductTypes(payload);
assert.deepEqual(firstResult, {
createdCount: 1,
updatedCount: 1,
parsedCount: 2,
});
assert.deepEqual(secondResult, {
createdCount: 0,
updatedCount: 0,
parsedCount: 2,
});
assert.equal(calls.expressProductTypeCreate, 1);
assert.equal(calls.expressProductTypeUpdate, 1);
});
it('should group waybill orders by sys_platform_code and logistics_code before creating batches', async () => {
const { ctx } = createExpressServiceHarness({
orderDeliveryRows: [

View File

@ -0,0 +1,338 @@
'use strict';
const assert = require('node:assert/strict');
const ExpressPlatformService = require('../../../../app/service/systems/express_platform');
const DEFAULT_CAINIAO_TEMPLATE_URL = 'http://cloudprint.cainiao.com/cloudprint/template/getStandardTemplate.json?template_id=288948';
/**
* 构建菜鸟服务测试桩。
*
* @param {Object} [options={}] 测试选项。
* @return {{service: Object, calls: Object}} 服务实例与调用记录。
*/
function createCainiaoHarness(options = {}) {
const calls = {
signTopRequest: 0,
signTopRequestArgs: null,
curl: 0,
curlOptions: null,
transaction: 0,
orderExpressUpdate: 0,
orderExpressUpdateArgs: [],
orderDeliveryUpdate: 0,
storeWarehouseFindAll: 0,
storeWarehouseUpdate: 0,
storeWarehouseUpdateArgs: [],
printQuantityLogCreate: 0,
operationLogCreateOperationLogs: 0,
operationLogPayloads: [],
};
const relationRows = [
{
id: 501,
store_id: 5001,
warehouse_id: 100000,
print_quantity: 10,
print_quantity_locked: 2,
},
];
const ctx = {
app: {
config: {
qimen: {
appKey: 'tb-app-key',
security: 'tb-app-secret',
},
},
Sequelize: {
Op: {
or: 'or',
},
},
formatDate() {
return '2026-05-24 12:00:00';
},
},
model: {
async transaction(callback) {
calls.transaction += 1;
const transaction = {
LOCK: {
UPDATE: 'UPDATE',
},
};
return callback(transaction);
},
OrderExpress: {
async update(values, query) {
calls.orderExpressUpdate += 1;
calls.orderExpressUpdateArgs.push({ values, query });
return [ 1 ];
},
},
StoreWarehouse: {
async findAll() {
calls.storeWarehouseFindAll += 1;
return relationRows;
},
async update(values, query) {
calls.storeWarehouseUpdate += 1;
calls.storeWarehouseUpdateArgs.push({ values, query });
return [ 1 ];
},
},
StoreWarehousePrintQuantityLog: {
async create() {
calls.printQuantityLogCreate += 1;
return {};
},
},
},
service: {
systems: {
sign: {
signTopRequest(params, body, secret, signMethod) {
calls.signTopRequest += 1;
calls.signTopRequestArgs = {
params,
body,
secret,
signMethod,
};
return 'TB_TEST_SIGN';
},
},
express: {
async getWaybillAsyncOrderDeliveryModel() {
return {
async update() {
calls.orderDeliveryUpdate += 1;
return [ 1 ];
},
};
},
},
operationLog: {
async createOperationLogs(payloads = []) {
calls.operationLogCreateOperationLogs += 1;
calls.operationLogPayloads.push(...payloads);
return payloads;
},
},
},
},
state: {
user: {
employees_id: 9001,
employees_name: '测试员',
},
},
logger: {
info() {},
warn() {},
error() {},
},
async curl(url, optionsArg) {
calls.curl += 1;
calls.curlOptions = {
url,
options: optionsArg,
};
if (options.responseData) {
return {
data: options.responseData,
};
}
return {
data: {
cainiao_waybill_ii_get_response: {
modules: {
waybill_cloud_print_response: [
{
object_id: '100000_2001_3001',
waybill_code: 'CNWB-001',
print_data: JSON.stringify({
data: {
extraInfo: {
encryptWaybillCode: 'ENC-WB-001',
},
},
signature: 'SIG-001',
}),
},
],
},
},
},
};
},
};
return {
service: new ExpressPlatformService(ctx),
calls,
};
}
/**
* 构造菜鸟接口入参。
*
* @return {Object} 菜鸟接口测试入参。
*/
function buildPayload() {
return {
matchedPlatform: {
template_url: 'https://example.com/cainiao-template',
platform_code: 'CAINIAO',
},
listByWarehousePlatformCode: {
id: 91,
token: 'tb-access-token',
ext_data: {
order_tag: 'normal',
},
city_name: '上海市',
province_name: '上海市',
district_name: '浦东新区',
town_name: '花木街道',
address: '世纪大道100号',
sender_tel: '13800000000',
sender_name: '测试发件人',
logistics_code: 'TB-EXP',
logistics_name: '淘宝快递',
name: '淘宝接口',
platform_code: 'CAINIAO',
customer_code: 'CUST-001',
site_code: 'SITE-001',
express: {
CAINIAO: 'YTO',
},
shop: {
owner_id: 'owner-1',
},
},
orders: [
{
business_key: 3001,
order_delivery: {
id: 2001,
warehouse_id: 100000,
store_id: 5001,
sys_platform_code: 'CAINIAO',
source_order_codes: 'SO-1,SO-2',
delivery_order_code: 'DO-1',
orderItems: [
{
item_name: '商品A',
plan_qty: 2,
},
],
city: '上海市',
province: '上海市',
area: '浦东新区',
town: '花木街道',
detail_address: '测试地址1号',
mobile: '13900000000',
tel: '021-00000000',
name: '收件人A',
},
},
],
};
}
describe('test/app/service/systems/express_platform.cainiao.test.js', () => {
it('should call taobao router/rest with signed top params', async () => {
const { service, calls } = createCainiaoHarness();
const result = await service.cainiao(buildPayload());
assert.equal(calls.curl, 1);
assert.equal(calls.curlOptions.url, 'https://eco.taobao.com/router/rest');
assert.equal(calls.curlOptions.options.method, 'POST');
assert.equal(calls.curlOptions.options.contentType, 'form');
assert.equal(calls.signTopRequest, 1);
assert.equal(calls.signTopRequestArgs.secret, 'tb-app-secret');
assert.equal(calls.signTopRequestArgs.signMethod, 'md5');
assert.equal(calls.signTopRequestArgs.body, '');
assert.equal(calls.signTopRequestArgs.params.method, 'cainiao.waybill.ii.get');
assert.equal(calls.signTopRequestArgs.params.app_key, 'tb-app-key');
assert.equal(calls.signTopRequestArgs.params.session, 'tb-access-token');
assert.equal(calls.signTopRequestArgs.params.format, 'json');
assert.equal(calls.signTopRequestArgs.params.v, '2.0');
assert.equal(calls.signTopRequestArgs.params.sign_method, 'md5');
const requestBody = calls.curlOptions.options.data;
const bizBody = JSON.parse(requestBody.param_waybill_cloud_print_apply_new_request);
assert.equal(bizBody.cp_code, 'YTO');
assert.equal(bizBody.customer_code, 'CUST-001');
assert.equal(bizBody.shipping_branch_code, 'SITE-001');
assert.equal(bizBody.sender.mobile, '13800000000');
assert.equal(bizBody.trade_order_info_dtos[0].object_id, '100000_2001_3001');
assert.equal(result.flag, true);
assert.equal(result.code, 0);
assert.equal(result.message, '菜鸟平台数据处理成功');
});
it('should persist success updates and write operation logs', async () => {
const { service, calls } = createCainiaoHarness();
await service.cainiao(buildPayload());
assert.equal(calls.transaction, 1);
assert.equal(calls.orderExpressUpdate, 1);
assert.equal(calls.orderDeliveryUpdate, 1);
assert.equal(calls.storeWarehouseFindAll, 1);
assert.equal(calls.storeWarehouseUpdate, 1);
assert.equal(calls.printQuantityLogCreate, 1);
assert.equal(calls.operationLogCreateOperationLogs, 1);
const updateValues = calls.orderExpressUpdateArgs[0].values;
assert.equal(updateValues.waybill_code, 'CNWB-001');
assert.equal(updateValues.signature, 'SIG-001');
assert.equal(updateValues.encryptprintinfo, 'ENC-WB-001');
assert.equal(typeof updateValues.printinfo, 'string');
assert.equal(calls.storeWarehouseUpdateArgs[0].values.print_quantity, 9);
assert.equal(calls.storeWarehouseUpdateArgs[0].values.print_quantity_locked, 1);
assert.equal(calls.operationLogPayloads[0].businessId, '2001');
});
it('should fallback to default template_url when matchedPlatform.template_url is invalid', async () => {
const { service, calls } = createCainiaoHarness();
const payload = buildPayload();
payload.matchedPlatform.template_url = 'invalid-template-url';
await service.cainiao(payload);
const requestBody = calls.curlOptions.options.data;
const bizBody = JSON.parse(requestBody.param_waybill_cloud_print_apply_new_request);
assert.equal(bizBody.trade_order_info_dtos[0].template_url, DEFAULT_CAINIAO_TEMPLATE_URL);
});
it('should throw when taobao returns error_response', async () => {
const { service } = createCainiaoHarness({
responseData: {
error_response: {
msg: 'isv.invalid-parameter',
sub_msg: '参数错误',
},
},
});
await assert.rejects(
async () => {
await service.cainiao(buildPayload());
},
/参数错误/
);
});
});

View File

@ -0,0 +1,207 @@
'use strict';
const assert = require('node:assert/strict');
const ExpressPlatformService = require('../../../../app/service/systems/express_platform');
/**
* 构建拼多多服务最小测试桩。
*
* @return {{ service: Object, calls: Object }} 服务实例与调用记录。
*/
function createPddHarness() {
const calls = {
curl: 0,
curlOptions: null,
transaction: 0,
orderExpressUpdate: 0,
orderDeliveryUpdate: 0,
storeWarehouseFindAll: 0,
storeWarehouseUpdate: 0,
printQuantityLogCreate: 0,
operationLogCreateOperationLogs: 0,
};
const ctx = {
app: {
config: {
pdd: {
client_id: 'test-client-id',
client_secret: 'test-client-secret',
},
},
Sequelize: {
Op: {
or: 'or',
},
},
},
model: {
async transaction(callback) {
calls.transaction += 1;
const transaction = {
LOCK: {
UPDATE: 'UPDATE',
},
};
return callback(transaction);
},
OrderExpress: {
async update() {
calls.orderExpressUpdate += 1;
return [ 1 ];
},
},
StoreWarehouse: {
async findAll() {
calls.storeWarehouseFindAll += 1;
return [];
},
async update() {
calls.storeWarehouseUpdate += 1;
return [ 1 ];
},
},
StoreWarehousePrintQuantityLog: {
async create() {
calls.printQuantityLogCreate += 1;
return {};
},
},
},
service: {
systems: {
express: {
async getWaybillAsyncOrderDeliveryModel() {
return {
async update() {
calls.orderDeliveryUpdate += 1;
return [ 1 ];
},
};
},
},
operationLog: {
async createOperationLogs() {
calls.operationLogCreateOperationLogs += 1;
return [];
},
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
async curl(url, options) {
calls.curl += 1;
calls.curlOptions = {
url,
options,
};
return {
data: {
pdd_waybill_get_response: {
modules: [
{
object_id: '100000_2001_3001',
waybill_code: 'WB-2001',
},
],
},
},
};
},
};
return {
service: new ExpressPlatformService(ctx),
calls,
};
}
/**
* 构造拼多多接口入参。
*
* @return {Object} 拼多多接口测试入参。
*/
function buildPayload() {
return {
matchedPlatform: {
template_url: 'https://example.com/template',
},
listByWarehousePlatformCode: {
id: 91,
token: 'test-token',
ext_data: {
category: 'fragile',
tags: [ 'cold', 'urgent' ],
},
city_name: '上海市',
province_name: '上海市',
district_name: '浦东新区',
town_name: '花木街道',
address: '世纪大道100号',
sender_tel: '13800000000',
sender_name: '测试发件人',
logistics_code: 'PDD-EXP',
logistics_name: '拼多多快递',
name: '拼多多接口',
platform_code: 'PDD',
express: {
PDD: 'YTO',
},
},
orders: [
{
business_key: 3001,
order_delivery: {
id: 2001,
warehouse_id: 100000,
store_id: 5001,
source_order_codes: 'SO-1',
delivery_order_code: 'DO-1',
orderItems: [
{
item_name: '商品A',
plan_qty: 2,
},
],
city: '上海市',
province: '上海市',
area: '浦东新区',
town: '花木街道',
detail_address: '测试地址1号',
mobile: '13900000000',
tel: '021-00000000',
name: '收件人A',
},
},
],
};
}
describe('test/app/service/systems/express_platform.pdd.ext_data.test.js', () => {
it('should stringify object ext_data for logistics_services and notify_extend_info', async () => {
const { service, calls } = createPddHarness();
const payload = buildPayload();
const result = await service.pdd(payload);
assert.equal(calls.curl, 1);
assert.ok(calls.curlOptions);
const requestBody = calls.curlOptions.options.data;
const waybillRequest = JSON.parse(requestBody.param_waybill_cloud_print_apply_new_request);
const orderItem = waybillRequest.trade_order_info_dtos[0];
assert.equal(typeof orderItem.logistics_services, 'string');
assert.equal(typeof orderItem.notify_extend_info, 'string');
assert.equal(orderItem.logistics_services, JSON.stringify(payload.listByWarehousePlatformCode.ext_data));
assert.equal(orderItem.notify_extend_info, JSON.stringify(payload.listByWarehousePlatformCode.ext_data));
assert.equal(result.flag, true);
assert.equal(result.code, 0);
});
});

View File

@ -17,12 +17,32 @@ function createOrderPrintServiceHarness() {
error() {},
},
model: {
Express: {
async findAll() {
return [];
},
},
QueryTypes: {
SELECT: 'SELECT',
},
},
service: {
systems: {
express: {
pickWaybillExpressInterface() {
return null;
},
},
setting: {
expressInterface: {
async listByWarehousePlatformCode() {
return {
code: 200,
data: [],
};
},
},
},
storeWarehouse: {
async getContractConfig() {
return {
@ -152,7 +172,9 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
orderExpress: {
waybill_code: ' WB201 ',
printinfo: ' ENC_FROM_DB_PDD ',
encryptprintinfo: ' ENC_FROM_DB_PDD ',
signature: ' SIG_FROM_DB_PDD ',
ver: ' 12 ',
logistics_name: '中通',
logistics_interface_name: '顺丰空运',
},
@ -206,6 +228,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
assert.equal(result.print_data.documentID, 'WB201');
assert.equal(result.print_data.contents[0].encryptedData, 'ENC_FROM_DB_PDD');
assert.equal(result.print_data.contents[0].signature, 'SIG_FROM_DB_PDD');
assert.equal(result.print_data.contents[0].ver, '12');
assert.equal(result.print_data.contents[0].addData.sender.address.province, '广东省');
assert.equal(result.print_data.contents[0].addData.sender.address.city, '深圳市');
assert.equal(result.print_data.contents[0].addData.sender.address.district, '南山区');
@ -320,6 +343,362 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
assert.ok(customContent.data.list[0].text.includes('C1-01-01 9988776655443 【3】'));
});
it('should use cainiao pure main content from printinfo directly and keep custom control content', () => {
const service = createOrderPrintServiceHarness();
const result = service.buildOrderPlatformPrintItem({
orderRow: {
id: 207,
wave_id: 26,
wave_no: 'W026',
delivery_order_code: 'DO207',
store_id: 1,
warehouse_id: 100000,
items: JSON.stringify([
{
item_name: '运动短袖',
pick_location: 'E1区01-19-01',
barcode: '988948487',
quantity: 2,
},
]),
},
orderExpress: {
waybill_code: 'WB207',
printinfo: JSON.stringify({
encryptedData: 'ENC-001',
signature: 'SIG-001',
templateURL: 'https://upstream.example.com/cainiao/main-template.xml',
ver: '1.0',
}),
cainiao_cp_code: 'STO_CAINIAO',
cainiao_template_url: 'https://example.com/cainiao/main-template.xml',
logistics_name: '申通快递',
},
policyConfig: {
waybill_custom_display_type: '5',
},
platformCode: 'cainiao',
templateSample: {
cmd: 'print',
requestID: 'REQ-207',
version: '1.0',
task: {
documents: [
{
documentID: 'DOC-207',
contents: [
{
templateURL: 'http://cloudprint.cainiao.com/cloudprint/template/getStandardTemplate.json?template_id=288948',
data: {
cpCode: '__SAMPLE__',
recipient: '__SAMPLE__',
waybillCode: '__SAMPLE__',
},
},
{
templateURL: 'http://cloudprint.cainiao.com/cloudprint/customArea/queryCustomAreaList4Top.json?custom_area_id=6474956',
data: {
CustomControl: '__SAMPLE__',
},
},
],
},
],
},
},
});
assert.equal(result.print_data.documentID, 'WB207');
assert.ok(Array.isArray(result.print_data.contents));
assert.equal(result.print_data.contents.length, 2);
const mainContent = result.print_data.contents[0];
assert.ok(mainContent);
assert.equal(mainContent.templateURL, 'https://example.com/cainiao/main-template.xml');
assert.equal(mainContent.encryptedData, 'ENC-001');
assert.equal(mainContent.signature, 'SIG-001');
assert.equal(mainContent.ver, '1.0');
assert.equal(mainContent.data, undefined);
const customContent = result.print_data.contents[1];
assert.ok(customContent);
assert.equal(customContent.templateURL, 'http://cloudprint.cainiao.com/cloudprint/customArea/queryCustomAreaList4Top.json?custom_area_id=6474956');
assert.ok(customContent.data.CustomControl.includes('商品数量【2】'));
assert.ok(customContent.data.CustomControl.includes('E1区01-19-01 运动短袖 988948487 【2】'));
});
it('should unwrap cainiao main content from wrapped contents printinfo without falling back order fields', () => {
const service = createOrderPrintServiceHarness();
const result = service.buildOrderPlatformPrintItem({
orderRow: {
id: 209,
wave_id: 27,
wave_no: 'W027',
delivery_order_code: 'DO209',
store_id: 1,
warehouse_id: 100000,
name: '订单收件人',
mobile: '13999990000',
province: '浙江省',
city: '杭州市',
area: '西湖区',
detail_address: '订单回填地址 1 号',
items: JSON.stringify([
{
item_name: 'fallback 运动短袖',
pick_location: 'A1-01-01',
barcode: '111111111',
quantity: 1,
},
]),
},
orderExpress: {
waybill_code: 'WB209',
printinfo: JSON.stringify({
contents: [
{
templateURL: 'https://upstream.example.com/cainiao/main-content.xml',
signature: 'SIG-CONTENT-209',
data: {
cpCode: 'STO_UPSTREAM',
recipient: {
name: '接口收件人',
mobile: '13888880000',
},
sender: {
name: '接口发件人',
},
packageInfo: {
goodsDescription: '接口商品描述',
items: [
{
count: 9,
name: '接口商品',
},
],
},
routingInfo: {
routeCode: 'CN-HZ-001',
},
waybillCode: 'WB209',
},
},
],
}),
cainiao_cp_code: 'STO_CAINIAO',
cainiao_template_url: 'https://example.com/cainiao/wrapped-template.xml',
logistics_name: '申通快递',
},
policyConfig: {
sender_name: '策略发件人',
sender_tel: '13777770000',
province_name: '上海市',
city_name: '上海市',
district_name: '闵行区',
address: '策略发件地址 2 号',
waybill_custom_display_type: '5',
},
platformCode: 'cainiao',
templateSample: {
cmd: 'print',
requestID: 'REQ-209',
version: '1.0',
task: {
documents: [
{
documentID: 'DOC-209',
contents: [
{
templateURL: 'http://cloudprint.cainiao.com/cloudprint/template/getStandardTemplate.json?template_id=288948',
data: {
cpCode: '__SAMPLE__',
recipient: {
name: '__SAMPLE__',
},
sender: {
name: '__SAMPLE__',
},
packageInfo: {
goodsDescription: '__SAMPLE__',
},
routingInfo: {
routeCode: '__SAMPLE__',
},
waybillCode: '__SAMPLE__',
},
},
{
templateURL: 'http://cloudprint.cainiao.com/cloudprint/customArea/queryCustomAreaList4Top.json?custom_area_id=6474956',
data: {
CustomControl: '__SAMPLE__',
},
},
],
},
],
},
},
});
const mainContent = result.print_data.contents[0];
assert.equal(mainContent.templateURL, 'https://example.com/cainiao/wrapped-template.xml');
assert.equal(mainContent.signature, 'SIG-CONTENT-209');
assert.equal(mainContent.data._dataFrom, 'printinfo');
assert.equal(mainContent.data.cpCode, 'STO_CAINIAO');
assert.equal(mainContent.data.realCpCode, 'STO_CAINIAO');
assert.equal(mainContent.data.recipient.name, '接口收件人');
assert.equal(mainContent.data.recipient.mobile, '13888880000');
assert.equal(mainContent.data.sender.name, '接口发件人');
assert.equal(mainContent.data.packageInfo.goodsDescription, '接口商品描述');
assert.deepEqual(mainContent.data.packageInfo.items, [
{
count: 9,
name: '接口商品',
},
]);
assert.equal(mainContent.data.routingInfo.routeCode, 'CN-HZ-001');
assert.notEqual(mainContent.data.recipient.name, '订单收件人');
assert.notEqual(mainContent.data.sender.name, '策略发件人');
const customContent = result.print_data.contents[1];
assert.ok(customContent);
assert.ok(customContent.data.CustomControl.includes('商品数量【1】'));
assert.ok(customContent.data.CustomControl.includes('A1-01-01 fallback 运动短袖 111111111 【1】'));
});
it('should fallback cainiao main content to template skeleton when printinfo is invalid', () => {
const service = createOrderPrintServiceHarness();
const result = service.buildOrderPlatformPrintItem({
orderRow: {
id: 208,
wave_id: 26,
wave_no: 'W026',
delivery_order_code: 'DO208',
store_id: 1,
warehouse_id: 100000,
logistics_code: 'YTO',
sys_logistics_code: 'YTO_SYS',
name: '李四',
mobile: '13911112222',
tel: '020-12345678',
province: '广东省',
city: '广州市',
area: '白云区',
detail_address: '鹤龙一路 88 号',
items: JSON.stringify([
{
item_name: '运动短袖',
quantity: 2,
},
{
item_name: '纯棉长裤',
quantity: 1,
},
]),
},
orderExpress: {
waybill_code: 'WB208',
printinfo: '{invalid-json',
cainiao_cp_code: 'YTO_CAINIAO',
cainiao_template_url: 'https://example.com/cainiao/fallback-template.xml',
logistics_code: '',
logistics_name: '圆通速递',
},
policyConfig: {
sender_name: '仓库发货人',
sender_tel: '13812345678',
province_name: '浙江省',
city_name: '杭州市',
district_name: '余杭区',
address: '良睦路 999 号',
},
platformCode: 'cainiao',
templateSample: {
cmd: 'print',
requestID: 'REQ-208',
version: '1.0',
task: {
documents: [
{
documentID: 'DOC-208',
contents: [
{
templateURL: 'http://cloudprint.cainiao.com/cloudprint/template/getStandardTemplate.json?template_id=288948',
data: {
cpCode: '__SAMPLE__',
realCpCode: '__SAMPLE__',
recipient: {
name: '__SAMPLE__',
mobile: '__SAMPLE__',
tel: '__SAMPLE__',
address: {
province: '__SAMPLE__',
city: '__SAMPLE__',
district: '__SAMPLE__',
detail: '__SAMPLE__',
},
},
sender: {
name: '__SAMPLE__',
mobile: '__SAMPLE__',
address: {
province: '__SAMPLE__',
city: '__SAMPLE__',
district: '__SAMPLE__',
detail: '__SAMPLE__',
},
},
packageInfo: {
goodsDescription: '__SAMPLE__',
items: [
{
count: '__SAMPLE__',
name: '__SAMPLE__',
},
],
},
waybillCode: '__SAMPLE__',
},
},
],
},
],
},
},
});
const mainData = result.print_data.contents[0].data;
assert.equal(result.print_data.contents[0].templateURL, 'https://example.com/cainiao/fallback-template.xml');
assert.equal(mainData.waybillCode, '');
assert.equal(mainData._dataFrom, 'template');
assert.equal(mainData.cpCode, 'YTO_CAINIAO');
assert.equal(mainData.realCpCode, 'YTO_CAINIAO');
assert.equal(mainData.recipient.name, '');
assert.equal(mainData.recipient.mobile, '');
assert.equal(mainData.recipient.tel, '');
assert.equal(mainData.recipient.address.province, '');
assert.equal(mainData.recipient.address.city, '');
assert.equal(mainData.recipient.address.district, '');
assert.equal(mainData.recipient.address.detail, '');
assert.equal(mainData.sender.name, '');
assert.equal(mainData.sender.mobile, '');
assert.equal(mainData.sender.address.province, '');
assert.equal(mainData.sender.address.city, '');
assert.equal(mainData.sender.address.district, '');
assert.equal(mainData.sender.address.detail, '');
assert.equal(mainData.packageInfo.goodsDescription, '');
assert.deepEqual(mainData.packageInfo.items, [
{
count: '',
name: '',
},
]);
assert.equal(mainData.routingInfo, undefined);
});
it('should parse string policy_config in getPolicyConfigMapByStore', async () => {
const service = createOrderPrintServiceHarness();
service.ctx.service.systems.storeWarehouse.getContractConfig = async () => ({
@ -696,6 +1075,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
assert.ok(capturedAttributes.includes('printinfo'));
assert.ok(capturedAttributes.includes('signature'));
assert.ok(capturedAttributes.includes('encryptprintinfo'));
assert.ok(capturedAttributes.includes('ver'));
assert.ok(capturedAttributes.includes('logistics_interface_name'));
assert.equal(capturedWhere.business_key, 1);
});
@ -1553,4 +1933,177 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
assert.equal(result.summary.locked_count, 1);
assert.equal(result.summary.total_locked_orders, 1);
});
it('should prefer order_express platform_code for wave platform print data', async () => {
const service = createOrderPrintServiceHarness();
service.queryWavesByIds = async () => ([
{ wave_id: 70, wave_no: 'W070' },
]);
service.queryOrdersByWaveIds = async () => ([
{
id: 701,
wave_id: 70,
wave_no: 'W070',
warehouse_id: 100000,
store_id: 1,
delivery_order_code: 'O701',
post_status: 'fin',
print_lock_status: 'none',
sys_platform_code: 'TB',
},
]);
service.filterFullyAssignedExpressWaves = () => ({
validWaveIds: [ 70 ],
filteredWaveIds: [],
});
service.queryOrderExpressByOrderIds = async () => ([
{
order_id: 701,
business_key: 1,
waybill_code: 'WB701',
platform_code: 'CAINIAO',
},
]);
service.getPolicyConfigMapByStore = async () => new Map([
[ 1, {}],
]);
service.queryWaveOrderIndexMapByOrderIds = async () => new Map();
service.queryWaveTotalOrderCountMap = async () => new Map();
service.buildOrderExpressMap = rows => new Map((Array.isArray(rows) ? rows : []).map(row => [ row.order_id, row ]));
service.loadTemplateSampleByPlatform = () => ({});
service.buildOrderPlatformPrintItem = ({ orderRow, platformCode }) => ({
wave_id: Number(orderRow.wave_id),
wave_no: String(orderRow.wave_no),
order_id: Number(orderRow.id),
order_no: String(orderRow.delivery_order_code),
platform: String(platformCode),
platform_name: platformCode === 'CAINIAO' ? '菜鸟' : '淘宝',
print_data: {
order_id: Number(orderRow.id),
platform: String(platformCode),
},
});
const result = await service.getWavePlatformPrintData({
waveIds: [ 70 ],
warehouseId: 100000,
});
assert.equal(result.waveGroups[0].platforms[0].platform, 'CAINIAO');
assert.equal(result.waveGroups[0].platforms[0].platform_name, '菜鸟');
});
it('should enrich cainiao cpCode and main template url before building print data', async () => {
const service = createOrderPrintServiceHarness();
const captured = {
expressCodes: null,
interfacePayload: null,
pickArgs: null,
orderExpress: null,
};
service.queryWavesByIds = async () => ([
{ wave_id: 80, wave_no: 'W080' },
]);
service.queryOrdersByWaveIds = async () => ([
{
id: 801,
wave_id: 80,
wave_no: 'W080',
warehouse_id: 100000,
store_id: 1,
delivery_order_code: 'O801',
post_status: 'fin',
sys_platform_code: 'cainiao',
sys_logistics_code: 'YTO_SYS',
logistics_code: 'YTO',
},
]);
service.filterFullyAssignedExpressWaves = () => ({
validWaveIds: [ 80 ],
filteredWaveIds: [],
});
service.queryOrderExpressByOrderIds = async () => ([
{
order_id: 801,
business_key: 1,
waybill_code: 'WB801',
logistics_code: 'YTO',
platform_code: 'CAINIAO',
},
]);
service.getPolicyConfigMapByStore = async () => new Map([
[ 1, {}],
]);
service.queryWaveOrderIndexMapByOrderIds = async () => new Map();
service.queryWaveTotalOrderCountMap = async () => new Map();
service.loadTemplateSampleByPlatform = () => ({});
service.ctx.model.Express.findAll = async options => {
captured.expressCodes = options && options.where && options.where.code && options.where.code[Symbol.for('sequelize.operator.in')];
return [
{
code: 'YTO_SYS',
CAINIAO: 'YTO_CAINIAO',
},
];
};
service.ctx.service.systems.setting.expressInterface.listByWarehousePlatformCode = async payload => {
captured.interfacePayload = payload;
return {
code: 200,
data: [
{
id: 1,
sys_express_code: 'YTO_SYS',
express_code: 'YTO',
template_url: 'https://example.com/cainiao/order-main.xml',
express: {
CAINIAO: 'YTO_CAINIAO',
},
},
],
};
};
service.ctx.service.systems.express.pickWaybillExpressInterface = (interfaceList, groupedOrder, matchedPlatform) => {
captured.pickArgs = {
interfaceList,
groupedOrder,
matchedPlatform,
};
return interfaceList[0];
};
service.buildOrderPlatformPrintItem = ({ orderExpress }) => {
captured.orderExpress = orderExpress;
return {
wave_id: 80,
wave_no: 'W080',
order_id: 801,
order_no: 'O801',
platform: 'CAINIAO',
platform_name: '菜鸟',
sys_logistics_code: 'YTO_SYS',
sys_logistics_name: '圆通',
waybill_code: 'WB801',
print_data: {
order_id: 801,
},
};
};
const result = await service.getWavePlatformPrintData({
waveIds: [ 80 ],
warehouseId: 100000,
});
assert.equal(result.waveGroups.length, 1);
assert.deepEqual(captured.interfacePayload, {
warehouseId: 100000,
platformCode: 'CAINIAO',
});
assert.equal(captured.pickArgs.groupedOrder.options.logistics_code, 'YTO');
assert.equal(captured.pickArgs.matchedPlatform.code, 'CAINIAO');
assert.equal(captured.orderExpress.cainiao_cp_code, 'YTO_CAINIAO');
assert.equal(captured.orderExpress.cainiao_template_url, 'https://example.com/cainiao/order-main.xml');
});
});

View File

@ -15,11 +15,28 @@ function createPlatformServiceHarness(options = {}) {
findAll: 0,
platformFindAll: 0,
platformSettingFindAll: 0,
printPlatformFindAll: 0,
qimenAppFindAll: 0,
getCache: 0,
setCache: 0,
};
const printPlatformModel = options.hasPrintPlatformModel === false ? undefined : {
async findAll(query) {
calls.findAll += 1;
calls.printPlatformFindAll += 1;
calls.printPlatformFindAllQuery = query;
const printPlatformRows = options.printPlatformRows || [
{ id: 201, platform_code: 'OPEN_API' },
{ id: 202, platform_code: 'QM_WMS' },
];
const whereIds = query && query.where && Array.isArray(query.where.id) ? query.where.id.map(Number) : [];
return printPlatformRows.filter(row => whereIds.includes(Number(row.id)));
},
};
const ctx = {
user: {
store_id: options.storeId === undefined ? 100000 : options.storeId,
@ -47,8 +64,8 @@ function createPlatformServiceHarness(options = {}) {
calls.platformFindAll += 1;
calls.platformFindAllQuery = query;
return options.rows || [
{ code: 'JD', name: '京东平台', platform_code: 'OPEN_API' },
{ code: 'TB', name: '淘宝平台', platform_code: 'QM_WMS' },
{ code: 'JD', name: '京东平台', platform_code: 'DIFF_ROUTER', print_platform_id: 201 },
{ code: 'TB', name: '淘宝平台', platform_code: 'TB_ROUTE', print_platform_id: 202 },
];
},
},
@ -74,6 +91,7 @@ function createPlatformServiceHarness(options = {}) {
];
},
},
PrintPlatform: printPlatformModel,
},
logger: {
info() {},
@ -96,9 +114,10 @@ describe('test/app/service/systems/platform.test.js', () => {
const result = await service.getPlatformList();
assert.equal(calls.getCache, 1);
assert.equal(calls.findAll, 2);
assert.equal(calls.findAll, 3);
assert.equal(calls.platformFindAll, 1);
assert.equal(calls.platformSettingFindAll, 1);
assert.equal(calls.printPlatformFindAll, 1);
assert.equal(calls.setCache, 1);
assert.equal(calls.cachePayload.cacheKey, 'platform:list:100000');
assert.equal(calls.cachePayload.ttl, 600);
@ -139,6 +158,28 @@ describe('test/app/service/systems/platform.test.js', () => {
assert.equal(result[2].label, 'JD-STORE (京东平台)');
});
it('should expose route_platform_code and default_express_interface separately in full mode', async () => {
const { ctx } = createPlatformServiceHarness({
rows: [
{ code: 'KS', name: '快手平台', platform_code: 'KS_ROUTE', print_platform_id: 9527 },
],
printPlatformRows: [
{ id: 9527, platform_code: 'POLYAPI' },
],
settingRows: [
{ id: 31, code: 'KS-STORE', platform_code: 'KS', warehouse_id: 100000, name: 'KS-STORE' },
],
});
const service = new PlatformService(ctx);
const result = await service.getPlatformList(false, true);
assert.equal(result[0].route_platform_code, 'KS_ROUTE');
assert.equal(result[0].default_express_interface, 'POLYAPI');
assert.equal(result[1].route_platform_code, 'KS_ROUTE');
assert.equal(result[1].default_express_interface, 'POLYAPI');
});
it('should keep flat and full platform list caches isolated', async () => {
const cacheValues = new Map([
[ 'platform:list:100000', [
@ -184,7 +225,7 @@ describe('test/app/service/systems/platform.test.js', () => {
it('should merge platform setting code to real platform code and name', async () => {
const { ctx } = createPlatformServiceHarness({
rows: [
{ code: 'TB', name: '淘宝平台', platform_code: 'QM_WMS' },
{ code: 'TB', name: '淘宝平台', platform_code: 'TB_ROUTE', print_platform_id: 202 },
],
settingRows: [
{ id: 21, code: 'TB-STORE', platform_code: 'TB', warehouse_id: 100000 },
@ -200,10 +241,33 @@ describe('test/app/service/systems/platform.test.js', () => {
]);
});
it('should derive default_express_interface from PrintPlatform.platform_code instead of platform.platform_code', async () => {
const { ctx, calls } = createPlatformServiceHarness({
rows: [
{ code: 'JD', name: '京东平台', platform_code: 'DIFF_ROUTER', print_platform_id: 9527 },
],
printPlatformRows: [
{ id: 9527, platform_code: 'OPEN_API' },
],
settingRows: [
{ id: 11, code: 'JD-STORE', platform_code: 'JD', warehouse_id: 100000 },
],
});
const service = new PlatformService(ctx);
const result = await service.getPlatformList();
assert.equal(calls.printPlatformFindAll, 1);
assert.deepEqual(result, [
{ code: 'JD', name: '京东平台', default_express_interface: 'OPEN_API', value: 'JD', label: '京东平台', platform_code: 'JD', platform_name: '京东平台', is_system_setting: false },
{ id: 11, code: 'JD-STORE', name: 'JD-STORE (京东平台)', value: 'JD-STORE', label: 'JD-STORE (京东平台)', is_system_setting: true, alias: '', platform_code: 'JD', platform_name: '京东平台', default_express_interface: 'OPEN_API' },
]);
});
it('should load system platform list and cache it with the system cache key when systemOnly is true', async () => {
const { ctx, calls } = createPlatformServiceHarness({
rows: [
{ code: 'JD', name: '京东平台', platform_code: 'OPEN_API' },
{ code: 'JD', name: '京东平台', platform_code: 'DIFF_ROUTER', print_platform_id: 201 },
],
});
const service = new PlatformService(ctx);
@ -211,6 +275,7 @@ describe('test/app/service/systems/platform.test.js', () => {
const result = await service.getPlatformList(true);
assert.equal(calls.getCache, 1);
assert.equal(calls.printPlatformFindAll, 1);
assert.equal(calls.platformFindAll, 1);
assert.equal(calls.platformSettingFindAll, 0);
assert.equal(calls.setCache, 1);
@ -289,6 +354,40 @@ describe('test/app/service/systems/platform.test.js', () => {
]);
});
it('should delegate index.getPlatformList with is_system to the platform service', async () => {
const { ctx } = createPlatformServiceHarness();
let serviceCalls = 0;
let receivedSystemOnly = null;
let receivedFull = null;
ctx.service = {
systems: {
platform: {
async getPlatformList(systemOnly, full) {
serviceCalls += 1;
receivedSystemOnly = systemOnly;
receivedFull = full;
return [
{ code: 'JD', name: '京东平台', platform_code: 'OPEN_API', value: 'JD', label: '京东平台' },
];
},
},
},
};
const methodService = new IndexMethodService(ctx);
const result = await methodService.getPlatformList({ is_system: 1, full: 0 });
assert.equal(serviceCalls, 1);
assert.equal(receivedSystemOnly, true);
assert.equal(receivedFull, false);
assert.equal(result.flag, 'success');
assert.equal(result.message, 'ok');
assert.equal(result.code, 200);
assert.deepEqual(result.data, [
{ code: 'JD', name: '京东平台', platform_code: 'OPEN_API', value: 'JD', label: '京东平台' },
]);
});
it('should return cached qimen app list without querying database', async () => {
const cachedValue = [
{ id: 1, name: '奇门应用A', app_key: 'app-key-a' },

View File

@ -34,6 +34,10 @@ function createHarness(options = {}) {
findOneCalls: [],
findAllCalls: 0,
expressFindOneCalls: [],
printPlatformFindOneCalls: [],
printPlatformFindAllCalls: 0,
printPlatformFindAllQuery: null,
shopFindOneCalls: [],
createPayload: null,
updatePayload: null,
destroyPayload: null,
@ -90,6 +94,7 @@ function createHarness(options = {}) {
town_name: '粤海街道',
ispickup: 1,
shipperno: 'SHIPPER-001',
template_url: 'https://example.com/template/default',
},
{
id: 12,
@ -140,6 +145,7 @@ function createHarness(options = {}) {
platform_code: {},
sys_express_code: {},
warehouse_id: {},
shop_id: {},
sender_name: {},
sender_tel: {},
weight: {},
@ -160,6 +166,7 @@ function createHarness(options = {}) {
town_name: {},
ispickup: {},
shipperno: {},
template_url: {},
ext_data: {},
};
@ -169,6 +176,24 @@ function createHarness(options = {}) {
{ code: 'ZTO', name: '中通', PDD: 'ZTO-PDD', KS: 'ZTO-KS', DYXD: 'ZTO-DYXD' },
];
const shopRows = options.shopRows || [
{
id: 301,
warehouse_id: 100000,
access_token: 'shop-access-token-301',
},
{
id: 302,
warehouse_id: 100000,
access_token: null,
},
{
id: 401,
warehouse_id: 200000,
access_token: 'shop-access-token-401',
},
];
const ctx = {
user: {
store_id: options.storeId || 100000,
@ -200,6 +225,65 @@ function createHarness(options = {}) {
},
},
model: {
PrintPlatform: {
async findAll(query) {
calls.printPlatformFindAllCalls += 1;
calls.printPlatformFindAllQuery = query;
const printPlatformRows = Array.isArray(options.printPlatformRows)
? options.printPlatformRows
: [
{ id: 1, platform_code: 'CAINIAO', platform_name: '菜鸟电子面单', platid: '1001', status: 'ACTIVE', deleted: 0, remark: '默认平台' },
{ id: 2, platform_code: 'PDD', platform_name: '拼多多电子面单', platid: '1002', status: 'ACTIVE', deleted: 0, remark: null },
{ id: 3, platform_code: 'DY', platform_name: '抖音电子面单', platid: '1003', status: 'DISABLED', deleted: 0, remark: null },
{ id: 4, platform_code: 'KS', platform_name: '快手电子面单', platid: '1004', status: 'ACTIVE', deleted: 1, remark: null },
];
const where = query && query.where ? query.where : {};
return printPlatformRows.filter(row => {
if (where.deleted !== undefined && Number(row.deleted || 0) !== Number(where.deleted)) {
return false;
}
if (where.status !== undefined && String(row.status || '') !== String(where.status || '')) {
return false;
}
return true;
});
},
async findOne(query) {
calls.printPlatformFindOneCalls.push(query);
const where = query.where || {};
const targetCode = String(where.platform_code || '');
const printPlatformRows = Array.isArray(options.printPlatformRows)
? options.printPlatformRows
: [{ platform_code: 'TB' }, { platform_code: 'JD' }, { platform_code: 'PDD' }, { platform_code: 'WX' }];
const found = printPlatformRows.find(row => String(row.platform_code || '') === targetCode);
return found ? { ...found } : null;
},
},
Shop: {
rawAttributes: {
id: {},
warehouse_id: {},
access_token: {},
},
async findOne(query) {
calls.shopFindOneCalls.push(query);
const where = query.where || {};
const found = shopRows.find(row => (
Number(row.id) === Number(where.id)
&& Number(row.warehouse_id) === Number(where.warehouse_id)
));
return found ? {
...found,
get() {
return { ...found };
},
} : null;
},
},
Express: {
async findOne(query) {
calls.expressFindOneCalls.push(query);
@ -286,6 +370,46 @@ function createHarness(options = {}) {
}
describe('test/app/service/systems/setting/expressInterface.test.js', () => {
it('should list active print platforms for express interface dropdown', async () => {
const { ctx, calls } = createHarness();
const service = new SettingExpressInterfaceService(ctx);
const result = await service.getPrintPlatformList();
assert.equal(calls.printPlatformFindAllCalls, 1);
assert.deepEqual(calls.printPlatformFindAllQuery.where, {
deleted: 0,
status: 'ACTIVE',
});
assert.deepEqual(calls.printPlatformFindAllQuery.order, [[ 'platform_name', 'ASC' ], [ 'id', 'ASC' ]]);
assert.deepEqual(result, [
{
id: 1,
code: 'CAINIAO',
name: '菜鸟电子面单',
value: 'CAINIAO',
label: '菜鸟电子面单',
platform_code: 'CAINIAO',
platform_name: '菜鸟电子面单',
platid: '1001',
status: 'ACTIVE',
remark: '默认平台',
},
{
id: 2,
code: 'PDD',
name: '拼多多电子面单',
value: 'PDD',
label: '拼多多电子面单',
platform_code: 'PDD',
platform_name: '拼多多电子面单',
platid: '1002',
status: 'ACTIVE',
remark: null,
},
]);
});
it('should list express interfaces with pagination and quick where', async () => {
const { ctx, calls } = createHarness({
where: {
@ -341,6 +465,7 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => {
site_code: 'SITE-01',
product_type: 'STD',
shop_name: '旗舰店',
template_url: 'https://example.com/template/list',
ext_data: {
print_mode: 'A4',
enabled: true,
@ -370,6 +495,8 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => {
assert.equal(result.data.list[0].name, '顺丰接口');
assert.equal(result.data.list[0].platform_code, 'TB');
assert.equal(result.data.list[0].sys_express_code, 'SF');
assert.equal(result.data.list[0].template_url, 'https://example.com/template/list');
assert.equal(result.data.list[0].is_system_express_code, 1);
assert.deepEqual(result.data.list[0].ext_data, {
print_mode: 'A4',
enabled: true,
@ -383,18 +510,69 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => {
assert.equal(Object.prototype.hasOwnProperty.call(result.data.list[0], 'express_platform_interface_url'), false);
});
it('should mark non-system express_code as 0 in list response', async () => {
const { ctx } = createHarness({
listRows: [
{
id: 11,
warehouse_id: 100000,
sys_express_code: 'SF',
name: '拼多多顺丰接口',
express_code: 'SF-PDD',
platform_code: 'PDD',
ext_data: null,
express: {
code: 'SF',
name: '顺丰',
PDD: 'SF-PDD',
},
},
],
});
const service = new SettingExpressInterfaceService(ctx);
const result = await service.list({
page: 1,
page_size: 20,
});
assert.equal(result.code, 200);
assert.equal(result.data.list[0].express_code, 'SF-PDD');
assert.equal(result.data.list[0].sys_express_code, 'SF');
assert.equal(result.data.list[0].is_system_express_code, 0);
});
it('should load full express interface list by warehouse and platform code, sort it, and write cache on miss', async () => {
const { ctx, calls } = createHarness({
listRows: [
{
id: 20,
warehouse_id: 100000,
shop_id: 301,
sys_express_code: 'SYS-YTO',
name: '圆通接口',
express_code: 'YTO',
platform_code: 'TB',
express_platform_id: 2,
weight: 20,
shop: {
id: 301,
warehouse_id: 100000,
platform_code: 'TB',
shop_name: '圆通店铺',
custom_name: '圆通店铺别名',
status: 1,
auth_expire_at: null,
auth_random_code: null,
owner_id: 'owner-301',
access_token: 'shop-token-301',
refresh_token: 'shop-refresh-301',
token_expires_at: null,
refresh_token_expires_at: null,
scope: [ 'express', 'order' ],
created_at: '2026-05-24 10:00:00',
updated_at: '2026-05-24 10:00:00',
},
express: {
code: 'YTO',
name: '圆通',
@ -459,6 +637,8 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => {
assert.equal(result.data[0].express_code, 'SF');
assert.equal(result.data[1].express_code, 'ZTO');
assert.equal(result.data[2].express_code, 'YTO');
assert.equal(result.data[2].shop.id, 301);
assert.equal(result.data[2].shop.shop_name, '圆通店铺');
assert.equal(result.data[0].weight, 10);
assert.equal(result.data[1].weight, 10);
assert.equal(result.data[2].weight, 20);
@ -476,12 +656,31 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => {
{
id: 12,
warehouse_id: 100000,
shop_id: 302,
sys_express_code: 'SYS-YTO',
name: '圆通接口',
express_code: 'YTO',
platform_code: 'TB',
express_platform_id: 2,
weight: 20,
shop: {
id: 302,
warehouse_id: 100000,
platform_code: 'TB',
shop_name: '圆通店铺缓存',
custom_name: null,
status: 1,
auth_expire_at: null,
auth_random_code: null,
owner_id: null,
access_token: 'shop-token-302',
refresh_token: null,
token_expires_at: null,
refresh_token_expires_at: null,
scope: null,
created_at: '2026-05-24 10:00:00',
updated_at: '2026-05-24 10:00:00',
},
express: {
code: 'YTO',
name: '圆通',
@ -522,9 +721,81 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => {
assert.equal(result.data.length, 2);
assert.equal(result.data[0].express_code, 'SF');
assert.equal(result.data[1].express_code, 'YTO');
assert.equal(result.data[1].shop.id, 302);
assert.equal(result.data[1].shop.shop_name, '圆通店铺缓存');
assert.equal(result.data[0].express.polyapi_code, 'SF_API');
});
it('should bypass stale cache without shop field and reload from database', async () => {
const { ctx, calls, cacheStore } = createHarness({
listRows: [
{
id: 12,
warehouse_id: 100000,
shop_id: 302,
sys_express_code: 'SYS-YTO',
name: '圆通接口',
express_code: 'YTO',
platform_code: 'TB',
express_platform_id: 2,
weight: 20,
shop: {
id: 302,
warehouse_id: 100000,
platform_code: 'TB',
shop_name: '数据库圆通店铺',
custom_name: null,
status: 1,
auth_expire_at: null,
auth_random_code: null,
owner_id: null,
access_token: 'shop-token-302',
refresh_token: null,
token_expires_at: null,
refresh_token_expires_at: null,
scope: null,
created_at: '2026-05-24 10:00:00',
updated_at: '2026-05-24 10:00:00',
},
express: {
code: 'YTO',
name: '圆通',
polyapi_code: 'YTO_API',
polyapi_extra_info: null,
pdd_code: 'YTO-PDD',
},
},
],
});
const service = new SettingExpressInterfaceService(ctx);
const cacheKey = 'express_interface:warehouse:100000:platform:TB';
cacheStore.set(cacheKey, [
{
id: 12,
warehouse_id: 100000,
shop_id: 302,
sys_express_code: 'SYS-YTO',
name: '圆通接口',
express_code: 'YTO',
platform_code: 'TB',
express_platform_id: 2,
weight: 20,
},
]);
const result = await service.listByWarehousePlatformCode({
warehouseId: 100000,
platformCode: 'tb',
});
assert.equal(calls.findAllCalls, 1);
assert.equal(calls.cacheWrites.length, 1);
assert.equal(result.data.length, 1);
assert.equal(result.data[0].shop.id, 302);
assert.equal(result.data[0].shop.shop_name, '数据库圆通店铺');
});
it('should create a new express interface and normalize codes', async () => {
const { ctx, calls } = createHarness({
createdRowFactory: payload => ({
@ -564,6 +835,7 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => {
town_name: '望京街道',
ispickup: 1,
shipperno: 'SNO-001',
template_url: 'https://example.com/template/create',
extData: {
retry: 2,
channel: 'polyapi',
@ -574,16 +846,21 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => {
assert.equal(calls.createPayload.express_code, 'JD');
assert.equal(calls.createPayload.sys_express_code, 'JD');
assert.equal(calls.createPayload.platform_code, 'TB');
assert.equal(calls.printPlatformFindOneCalls.length, 1);
assert.deepEqual(calls.printPlatformFindOneCalls[0].where, {
platform_code: 'TB',
});
assert.equal(result.data.express_code, 'JD');
assert.equal(result.data.sys_express_code, 'JD');
assert.equal(result.data.platform_code, 'TB');
assert.equal(result.data.sender_name, '李四');
assert.equal(result.data.token, 'token-2');
assert.equal(result.data.weight_type, 2);
assert.equal(result.data.address, '朝阳区望京');
assert.equal(result.data.town_name, '望京街道');
assert.equal(result.data.ispickup, 1);
assert.equal(result.data.shipperno, 'SNO-001');
assert.equal(calls.createPayload.template_url, 'https://example.com/template/create');
assert.equal(result.data.template_url, 'https://example.com/template/create');
assert.deepEqual(calls.createPayload.ext_data, {
retry: 2,
channel: 'polyapi',
@ -645,13 +922,12 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => {
name: '顺丰接口-更新',
express_code: 'sf-pdd',
platform_code: 'pdd',
token: ' token-updated ',
can_use_count: 0,
weight_type: 3,
address: '上海市浦东新区',
town_name: '张江镇',
ispickup: 0,
shipperno: 'SHIPPER-NEW',
template_url: 'https://example.com/template/update',
ext_data: {
print_mode: 'thermal',
},
@ -662,18 +938,22 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => {
assert.equal(calls.updatePayload.updates.name, '顺丰接口-更新');
assert.equal(calls.updatePayload.updates.express_code, 'SF-PDD');
assert.equal(calls.updatePayload.updates.platform_code, 'PDD');
assert.equal(calls.printPlatformFindOneCalls.length, 1);
assert.deepEqual(calls.printPlatformFindOneCalls[0].where, {
platform_code: 'PDD',
});
assert.equal(calls.updatePayload.updates.sys_express_code, 'SF');
assert.equal(calls.updatePayload.updates.token, 'token-updated');
assert.equal(calls.updatePayload.updates.can_use_count, 0);
assert.equal(calls.updatePayload.updates.weight_type, 3);
assert.equal(calls.updatePayload.updates.address, '上海市浦东新区');
assert.equal(calls.updatePayload.updates.town_name, '张江镇');
assert.equal(calls.updatePayload.updates.ispickup, 0);
assert.equal(calls.updatePayload.updates.shipperno, 'SHIPPER-NEW');
assert.equal(calls.updatePayload.updates.template_url, 'https://example.com/template/update');
assert.deepEqual(calls.updatePayload.updates.ext_data, {
print_mode: 'thermal',
});
assert.equal(result.data.name, '顺丰接口-更新');
assert.equal(result.data.template_url, 'https://example.com/template/update');
assert.deepEqual(result.data.ext_data, {
print_mode: 'thermal',
});
@ -683,6 +963,40 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => {
assert.equal(calls.cacheDeletes.includes('express_interface:warehouse:100000:platform:PDD'), true);
});
it('should sync token from shop access_token when updating shop_id', async () => {
const { ctx, calls } = createHarness();
const service = new SettingExpressInterfaceService(ctx);
const result = await service.update({
id: 11,
shop_id: '301',
});
assert.equal(calls.shopFindOneCalls.length, 1);
assert.deepEqual(calls.shopFindOneCalls[0].where, {
id: 301,
warehouse_id: 100000,
});
assert.equal(calls.updatePayload.updates.shop_id, 301);
assert.equal(calls.updatePayload.updates.token, 'shop-access-token-301');
assert.equal(result.data.shop_id, 301);
});
it('should clear token when shop_id is cleared', async () => {
const { ctx, calls } = createHarness();
const service = new SettingExpressInterfaceService(ctx);
const result = await service.update({
id: 11,
shopId: '',
});
assert.equal(calls.shopFindOneCalls.length, 0);
assert.equal(calls.updatePayload.updates.shop_id, null);
assert.equal(calls.updatePayload.updates.token, null);
assert.equal(result.data.shop_id, null);
});
it('should clear old and new cache keys when platform code changes on update', async () => {
const { ctx, calls } = createHarness();
const service = new SettingExpressInterfaceService(ctx);
@ -696,6 +1010,21 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => {
assert.equal(calls.cacheDeletes.includes('express_interface:warehouse:100000:platform:WX'), true);
});
it('should reject create when print platform code does not exist', async () => {
const { ctx } = createHarness({
printPlatformRows: [{ platform_code: 'TB' }],
});
const service = new SettingExpressInterfaceService(ctx);
await assert.rejects(async () => {
await service.create({
name: '无效平台接口',
express_code: 'SF',
platform_code: 'PDD',
});
}, /platform_code 未匹配到打印平台编码/);
});
it('should allow updating ext_data only', async () => {
const { ctx, calls } = createHarness();
const service = new SettingExpressInterfaceService(ctx);
@ -715,6 +1044,36 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => {
});
});
it('should reject update when existing print platform code does not exist', async () => {
const { ctx, calls } = createHarness({
rows: [
{
id: 11,
warehouse_id: 100000,
name: '顺丰接口',
express_code: 'SF',
platform_code: 'INVALID',
express_platform_id: 1,
},
],
printPlatformRows: [{ platform_code: 'TB' }, { platform_code: 'PDD' }],
});
const service = new SettingExpressInterfaceService(ctx);
await assert.rejects(async () => {
await service.update({
id: 11,
name: '顺丰接口-仅改名称',
});
}, /platform_code 未匹配到打印平台编码/);
assert.equal(calls.printPlatformFindOneCalls.length, 1);
assert.deepEqual(calls.printPlatformFindOneCalls[0].where, {
platform_code: 'INVALID',
});
assert.equal(calls.updatePayload, null);
});
it('should delete a record only inside the current warehouse', async () => {
const { ctx, calls } = createHarness();
const service = new SettingExpressInterfaceService(ctx);

View File

@ -0,0 +1,236 @@
'use strict';
const assert = require('node:assert/strict');
const ShopsService = require('../../../../app/service/systems/shops');
function createFindOneResult(row) {
if (!row) {
return null;
}
return {
...row,
get() {
return { ...row };
},
async save() {
return this;
},
async update(payload) {
Object.assign(this, payload);
return this;
},
};
}
function createHarness(options = {}) {
const calls = {
shopFindAndCountAll: null,
shopFindOneCalls: [],
shopCreatePayload: null,
expressInterfaceFindOneCalls: [],
printPlatformFindOneCalls: [],
};
const shopRows = Array.isArray(options.shopRows) ? options.shopRows : [];
const printPlatforms = Array.isArray(options.printPlatforms)
? options.printPlatforms
: [{ platform_code: 'PDD', platform_name: '拼多多', auth_base_url: 'https://oauth.pdd.com?state=', deleted: 0, status: 'ACTIVE' }];
const ctx = {
app: {
Sequelize: {
Op: {
and: Symbol('and'),
or: Symbol('or'),
like: Symbol('like'),
notLike: Symbol('notLike'),
ne: Symbol('ne'),
in: Symbol('in'),
},
},
},
user: {
store_id: 100000,
},
whereParsed: options.whereParsed || {
dynamicConditions: [],
rawConditionsByField: {},
},
model: {
Shop: {
async findAndCountAll(query) {
calls.shopFindAndCountAll = query;
return {
count: shopRows.length,
rows: shopRows.map(row => createFindOneResult(row)),
};
},
async findOne(query) {
calls.shopFindOneCalls.push(query);
if (typeof options.shopFindOne === 'function') {
return await options.shopFindOne(query);
}
const where = query && query.where ? query.where : {};
const id = Number(where.id || 0);
const row = shopRows.find(item => Number(item.id) === id) || null;
return createFindOneResult(row);
},
async create(payload) {
calls.shopCreatePayload = payload;
return createFindOneResult({ id: 9001, ...payload });
},
},
PrintPlatform: {
async findOne(query) {
calls.printPlatformFindOneCalls.push(query);
const code = String(query && query.where && query.where.platform_code || '').toUpperCase();
const row = printPlatforms.find(item => String(item.platform_code || '').toUpperCase() === code) || null;
return row ? createFindOneResult(row) : null;
},
},
ExpressInterface: {
async findOne(query) {
calls.expressInterfaceFindOneCalls.push(query);
if (typeof options.expressInterfaceFindOne === 'function') {
return await options.expressInterfaceFindOne(query);
}
return null;
},
},
},
};
const service = new ShopsService(ctx);
return {
service,
calls,
ctx,
};
}
describe('test/app/service/systems/shops.test.js', () => {
it('list 应带上仓库与软删除过滤并返回分页', async () => {
const { service, calls } = createHarness({
shopRows: [
{
id: 1,
warehouse_id: 100000,
platform_code: 'PDD',
shop_name: '店铺A',
custom_name: '自定义A',
status: 1,
created_at: '2026-05-01 00:00:00',
updated_at: '2026-05-02 00:00:00',
printPlatform: {
platform_code: 'PDD',
platform_name: '拼多多',
},
},
],
});
const result = await service.list({
page: 1,
pageSize: 20,
});
assert.equal(Array.isArray(result.list), true);
assert.equal(result.list.length, 1);
assert.equal(result.pagination.total, 1);
assert.equal(Boolean(calls.shopFindAndCountAll.where), true);
});
it('add 应校验平台并创建 status=0 店铺', async () => {
const { service, calls } = createHarness({
shopRows: [],
});
const result = await service.add({
custom_name: '测试店铺',
platform_code: 'pdd',
});
assert.equal(result.id, 9001);
assert.equal(calls.shopCreatePayload.platform_code, 'PDD');
assert.equal(calls.shopCreatePayload.custom_name, '测试店铺');
assert.equal(calls.shopCreatePayload.status, 0);
});
it('del 遇到快递接口引用时应拒绝删除', async () => {
const { service } = createHarness({
shopRows: [
{
id: 5,
warehouse_id: 100000,
platform_code: 'PDD',
shop_name: '店铺X',
custom_name: '店铺X',
status: 1,
},
],
expressInterfaceFindOne: async () => ({ id: 1 }),
});
await assert.rejects(async () => {
await service.del({ id: 5 });
}, /店铺存在快递接口引用/);
});
it('edit 仅修改 custom_name/platform_code', async () => {
const { service } = createHarness({
shopRows: [
{
id: 7,
warehouse_id: 100000,
platform_code: 'PDD',
shop_name: '店铺Y',
custom_name: '旧名',
status: 1,
},
],
});
const result = await service.edit({
id: 7,
custom_name: '新名',
platform_code: 'PDD',
});
assert.equal(result.updated, true);
assert.equal(result.id, 7);
});
it('getAuthorizeSessionKey 对未实现平台应返回 501 错误', async () => {
const { service } = createHarness({
shopRows: [
{
id: 9,
warehouse_id: 100000,
platform_code: 'DY',
shop_name: '店铺Z',
custom_name: '店铺Z',
status: 1,
},
],
printPlatforms: [
{
platform_code: 'DY',
platform_name: '抖音',
auth_base_url: '',
deleted: 0,
status: 'ACTIVE',
},
],
});
await assert.rejects(async () => {
await service.getAuthorizeSessionKey({
id: 9,
callbackurl: 'https://callback.example.com',
});
}, /暂未实现授权会话换取能力/);
});
});

View File

@ -129,4 +129,4 @@ describe('test/app/service/systems/store_warehouse.listApiConfig.test.js', () =>
app_key: [ 'qm-app-key-1' ],
});
});
});
});