From dc4894cb6dc1ea9fa7861ae63357780b6ac810c9 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 25 May 2026 17:08:56 +0800 Subject: [PATCH] 1 --- app/controller/home.js | 561 +++++- app/lib/pdd_client.js | 2 +- app/lib/pdd_sign.js | 5 +- app/lib/polo_api_client.js | 26 +- app/lib/printer_data_builder.js | 544 +++++- app/lib/qimen_client.js | 33 +- app/lib/shop_soft_delete.js | 53 + app/model/express.js | 11 + app/model/express_interface.js | 48 +- app/model/order_express.js | 5 + app/model/platform.js | 8 +- app/model/print_platform.js | 86 + app/model/shop.js | 21 +- app/model/system_log.js | 2 +- app/router.js | 2 + app/service/systemMethods/index.js | 908 +++++++++- app/service/systemMethods/order/wave.js | 186 +- app/service/systemMethods/print.js | 12 +- .../systemMethods/setting/expressInterface.js | 10 + app/service/systemMethods/shops.js | 160 ++ app/service/systems/express.js | 605 ++++++- app/service/systems/express_platform.js | 732 +++++++- app/service/systems/order_print.js | 248 ++- app/service/systems/platform.js | 524 +++++- .../systems/setting/expressInterface.js | 332 +++- app/service/systems/shops.js | 692 ++++++++ check_brackets.js | 55 +- .../migrations/20260522103000-create-shops.js | 2 +- ...10000-add-auth-base-url-to-wms_platform.js | 2 +- ...000-add-auth-result-fields-to-wms-shops.js | 2 +- ...0522133000-add-custom-name-to-wms-shops.js | 2 +- ...00-add-shop-id-to-wms-express-interface.js | 46 + ...-expand-device-length-on-wms-system-log.js | 61 + ...260523130000-add-cainiao-to-wms-express.js | 46 + ...-is-hide-goods-to-wms-express-interface.js | 47 + ...0260524110000-create-wms-print-platform.js | 142 ++ ...0-add-print-platform-id-to-wms-platform.js | 46 + ...p-unused-fields-from-wms-print-platform.js | 117 ++ ...interface-platform-fk-to-print-platform.js | 248 +++ ...itch-shop-platform-fk-to-print-platform.js | 242 +++ ...ate-auth-base-url-to-wms-print-platform.js | 93 + ...d-template-url-to-wms-express-interface.js | 46 + ...0524190000-add-ver-to-wms-order-express.js | 46 + ...103000-add-platid-to-wms-print-platform.js | 68 + final_sf.json | Bin 0 -> 112110 bytes methods/changes/system.json | 259 +++ methods/system.json | 1439 +++++++++------ package.json | 1 + raw_redis.json | Bin 0 -> 111412 bytes redis_output.txt | Bin 0 -> 111412 bytes result_sf.json | Bin 0 -> 112110 bytes run-target-migration.js | 44 + script/run-single-migration.cjs | 8 +- temp.json | Bin 0 -> 111412 bytes test/app/controller/home.test.js | 230 +++ test/app/lib/pdd_client.test.js | 2 +- test/app/lib/pdd_sign.test.js | 2 +- test/app/lib/polo_api_client.test.js | 67 + test/app/lib/qimen_client.test.js | 76 + test/app/service/systemMethods/index.test.js | 1544 ++++++++++++++++- .../wave.batchList.assignmentStatus.test.js | 12 + .../setting/expressInterface.test.js | 4 + test/app/service/systemMethods/shops.test.js | 167 ++ .../systems/express.async_dispatch.test.js | 43 + .../express.createWaybillCode.balance.test.js | 24 + ...CodePipeline.matchExpressInterface.test.js | 254 +++ test/app/service/systems/express.test.js | 259 ++- .../systems/express_platform.cainiao.test.js | 338 ++++ .../express_platform.pdd.ext_data.test.js | 207 +++ ...der_print.getWavePlatformPrintData.test.js | 553 ++++++ test/app/service/systems/platform.test.js | 109 +- .../systems/setting/expressInterface.test.js | 369 +++- test/app/service/systems/shops.test.js | 236 +++ .../store_warehouse.listApiConfig.test.js | 2 +- 74 files changed, 12644 insertions(+), 732 deletions(-) create mode 100644 app/lib/shop_soft_delete.js create mode 100644 app/model/print_platform.js create mode 100644 app/service/systemMethods/shops.js create mode 100644 app/service/systems/shops.js create mode 100644 database/migrations/20260522143000-add-shop-id-to-wms-express-interface.js create mode 100644 database/migrations/20260523120000-expand-device-length-on-wms-system-log.js create mode 100644 database/migrations/20260523130000-add-cainiao-to-wms-express.js create mode 100644 database/migrations/20260524093000-add-is-hide-goods-to-wms-express-interface.js create mode 100644 database/migrations/20260524110000-create-wms-print-platform.js create mode 100644 database/migrations/20260524113000-add-print-platform-id-to-wms-platform.js create mode 100644 database/migrations/20260524120000-drop-unused-fields-from-wms-print-platform.js create mode 100644 database/migrations/20260524130000-switch-express-interface-platform-fk-to-print-platform.js create mode 100644 database/migrations/20260524153000-switch-shop-platform-fk-to-print-platform.js create mode 100644 database/migrations/20260524170000-migrate-auth-base-url-to-wms-print-platform.js create mode 100644 database/migrations/20260524173000-add-template-url-to-wms-express-interface.js create mode 100644 database/migrations/20260524190000-add-ver-to-wms-order-express.js create mode 100644 database/migrations/20260525103000-add-platid-to-wms-print-platform.js create mode 100644 final_sf.json create mode 100644 raw_redis.json create mode 100644 redis_output.txt create mode 100644 result_sf.json create mode 100644 run-target-migration.js create mode 100644 temp.json create mode 100644 test/app/lib/polo_api_client.test.js create mode 100644 test/app/service/systemMethods/shops.test.js create mode 100644 test/app/service/systems/express.createWaybillCodePipeline.matchExpressInterface.test.js create mode 100644 test/app/service/systems/express_platform.cainiao.test.js create mode 100644 test/app/service/systems/express_platform.pdd.ext_data.test.js create mode 100644 test/app/service/systems/shops.test.js diff --git a/app/controller/home.js b/app/controller/home.js index 9cd7953..5372174 100644 --- a/app/controller/home.js +++ b/app/controller/home.js @@ -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} 无返回值。 + */ + async renderPlatformOauthBindResultPage(isSuccess) { + const title = isSuccess ? '绑定成功' : '绑定失败'; + const message = isSuccess ? '绑定成功' : '绑定失败,请重新授权'; + const color = isSuccess ? '#2f7d32' : '#c62828'; + const html = ` + + + + + ${title} + + + +
+

${title}

+

${message}

+
+ +`; + + 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} 命中的已授权店铺记录。 */ - 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} 命中的已授权店铺记录。 + */ + 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} 已保存的店铺模型实例。 + */ + 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} 无返回值。 @@ -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} 无返回值。 + */ + 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} 无返回值。 + */ + 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} 无返回值。 diff --git a/app/lib/pdd_client.js b/app/lib/pdd_client.js index 8f97fae..3f354e4 100644 --- a/app/lib/pdd_client.js +++ b/app/lib/pdd_client.js @@ -147,4 +147,4 @@ class PddClient { } } -module.exports = PddClient; \ No newline at end of file +module.exports = PddClient; diff --git a/app/lib/pdd_sign.js b/app/lib/pdd_sign.js index 622e5da..e3c32c2 100644 --- a/app/lib/pdd_sign.js +++ b/app/lib/pdd_sign.js @@ -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, -}; \ No newline at end of file +}; diff --git a/app/lib/polo_api_client.js b/app/lib/polo_api_client.js index b7c45ec..651af3d 100644 --- a/app/lib/polo_api_client.js +++ b/app/lib/polo_api_client.js @@ -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(); } /** diff --git a/app/lib/printer_data_builder.js b/app/lib/printer_data_builder.js index b7487a6..c91c5ff 100644 --- a/app/lib/printer_data_builder.js +++ b/app/lib/printer_data_builder.js @@ -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} 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} 自定义区文本行数组。 */ 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} 候选值列表。 + */ +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, diff --git a/app/lib/qimen_client.js b/app/lib/qimen_client.js index b4af2f7..e65a0b9 100644 --- a/app/lib/qimen_client.js +++ b/app/lib/qimen_client.js @@ -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 }; } diff --git a/app/lib/shop_soft_delete.js b/app/lib/shop_soft_delete.js new file mode 100644 index 0000000..9112b08 --- /dev/null +++ b/app/lib/shop_soft_delete.js @@ -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, +}; diff --git a/app/model/express.js b/app/model/express.js index 2fc3577..62523e4 100644 --- a/app/model/express.js +++ b/app/model/express.js @@ -1,5 +1,10 @@ 'use strict'; +/** + * 定义快递基础信息模型。 + * @param {import('egg').Application} app Egg 应用实例 + * @return {import('sequelize').ModelCtor} 快递模型 + */ 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, diff --git a/app/model/express_interface.js b/app/model/express_interface.js index 11de16e..7d93bae 100644 --- a/app/model/express_interface.js +++ b/app/model/express_interface.js @@ -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; diff --git a/app/model/order_express.js b/app/model/order_express.js index f740971..9307653 100644 --- a/app/model/order_express.js +++ b/app/model/order_express.js @@ -102,6 +102,11 @@ module.exports = app => { allowNull: true, comment: '加密打印信息', }, + ver: { + type: STRING(50), + allowNull: true, + comment: '打印版本号', + }, encryptedtoken: { type: TEXT, allowNull: true, diff --git a/app/model/platform.js b/app/model/platform.js index 9901334..064448a 100644 --- a/app/model/platform.js +++ b/app/model/platform.js @@ -6,7 +6,7 @@ * @return {import('sequelize').ModelCtor} 平台模型 */ 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', diff --git a/app/model/print_platform.js b/app/model/print_platform.js new file mode 100644 index 0000000..c2d2a56 --- /dev/null +++ b/app/model/print_platform.js @@ -0,0 +1,86 @@ +'use strict'; + +/** + * 打印平台元数据模型。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} 打印平台元数据模型。 + */ +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; +}; diff --git a/app/model/shop.js b/app/model/shop.js index bb734ce..8e96fa0 100644 --- a/app/model/shop.js +++ b/app/model/shop.js @@ -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; -}; \ No newline at end of file +}; diff --git a/app/model/system_log.js b/app/model/system_log.js index 214c50c..fb2f31d 100644 --- a/app/model/system_log.js +++ b/app/model/system_log.js @@ -73,7 +73,7 @@ module.exports = app => { comment: '门店ID', }, device: { - type: STRING(10), + type: STRING(100), allowNull: true, comment: '设备', }, diff --git a/app/router.js b/app/router.js index f34f43d..c4f6a81 100644 --- a/app/router.js +++ b/app/router.js @@ -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); diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 2db0f2c..81e777d 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -3,9 +3,12 @@ const MainService = require('../main'); const crypto = require('crypto'); const PddClient = require('../../lib/pdd_client'); +const { buildNotDeletedShopWhere } = require('../../lib/shop_soft_delete'); const DEFAULT_PDD_ROUTER_URL = 'https://gw-api.pinduoduo.com/api/router'; -const SHOP_MASK_PLACEHOLDER = `***`; +const DEFAULT_TB_ROUTER_URL = 'https://eco.taobao.com/router/rest'; +const SHOP_MASK_PLACEHOLDER = '***'; +const TB_FILTERED_SERVICE_REGEXP = /\b(?:COD|RECEIVER[-_ ]?PAY)\b|代收货款|到付|拦截件|定时派送|上门取旧换新/i; /** * 脱敏通用敏感文本。 @@ -50,11 +53,15 @@ function maskShopListItem(shopItem) { const plainItem = shopItem && typeof shopItem.get === 'function' ? shopItem.get({ plain: true }) : shopItem || {}; + const printPlatform = plainItem.printPlatform && typeof plainItem.printPlatform === 'object' + ? plainItem.printPlatform + : null; return { id: plainItem.id, warehouse_id: plainItem.warehouse_id, platform_code: plainItem.platform_code, + platform_name: printPlatform ? printPlatform.platform_name || printPlatform.platform_code || '' : '', shop_name: plainItem.shop_name, custom_name: plainItem.custom_name, status: plainItem.status, @@ -85,6 +92,23 @@ function normalizeText(value) { return String(value); } +/** + * 判断淘宝菜鸟服务项是否属于代收货款、到付、拦截件、定时派送或上门取旧换新类服务。 + * + * @param {Object} serviceItem 淘宝菜鸟服务项 + * @return {boolean} 是否需要从统一返回结果中过滤 + */ +function shouldFilterTbService(serviceItem) { + const currentServiceItem = serviceItem && typeof serviceItem === 'object' ? serviceItem : {}; + const candidateTexts = [ + currentServiceItem.service_code, + currentServiceItem.service_name, + currentServiceItem.service_desc, + ].map(item => normalizeText(item).trim()).filter(Boolean); + + return candidateTexts.some(item => TB_FILTERED_SERVICE_REGEXP.test(item)); +} + /** * 将任意值标准化为数组。 * @@ -96,11 +120,104 @@ function normalizeArray(value) { } /** - * 根据平台编码构建平台侧快递编码到系统快递名称的映射。 + * 将对象包裹的集合字段标准化为数组。 + * + * @param {*} value 原始集合值 + * @param {Array} [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 ? [ value ] : []; +} + +/** + * 按候选来源顺序提取首个非空包裹集合。 + * + * @param {Array<*>} values 候选来源列表 + * @param {Array} [nestedKeys=[]] 对象包裹时的候选子字段名 + * @return {Array} 首个非空的标准化数组 + */ +function normalizeFirstWrappedArray(values, nestedKeys = []) { + for (const value of normalizeArray(values)) { + const normalized = normalizeWrappedArray(value, nestedKeys); + + if (normalized.length) { + return normalized; + } + } + + return []; +} + +/** + * 规范化菜鸟标准模板子项列表。 + * + * @param {*} standardTemplates 菜鸟标准模板字段 + * @return {Array} 标准模板子项列表 + */ +function normalizeCainiaoStandardTemplateList(standardTemplates) { + return normalizeWrappedArray(standardTemplates, [ 'standard_template_do' ]); +} + +/** + * 按原始结构回填菜鸟标准模板子项列表。 + * + * @param {*} standardTemplates 菜鸟标准模板字段 + * @param {Array} templateList 过滤后的标准模板子项列表 + * @return {*} 回填后的标准模板字段 + */ +function rebuildCainiaoStandardTemplates(standardTemplates, templateList) { + if (Array.isArray(standardTemplates)) { + return templateList; + } + + if (standardTemplates && typeof standardTemplates === 'object') { + if (Object.prototype.hasOwnProperty.call(standardTemplates, 'standard_template_do')) { + return { + ...standardTemplates, + standard_template_do: templateList, + }; + } + + return Object.keys(standardTemplates).length ? { + ...standardTemplates, + standard_template_do: templateList, + } : templateList; + } + + return templateList; +} + +/** + * 根据平台编码构建平台侧快递编码到系统快递信息的映射。 * * @param {Array} expressList 系统快递列表 * @param {string} platformCode 平台编码 - * @return {Object} 平台侧快递编码到系统快递名称的映射 + * @return {Object} 平台侧快递编码到系统快递信息的映射 */ function buildPlatformExpressNameMap(expressList, platformCode) { const normalizedPlatformCode = String(platformCode || '').trim().toUpperCase(); @@ -117,7 +234,10 @@ function buildPlatformExpressNameMap(expressList, platformCode) { return result; } - result[platformExpressCode] = normalizeText(currentExpressItem.name); + result[platformExpressCode] = { + name: normalizeText(currentExpressItem.name), + sys_express_code: normalizeText(currentExpressItem.code), + }; return result; }, {}); } @@ -126,7 +246,7 @@ function buildPlatformExpressNameMap(expressList, platformCode) { * 解析拼多多电子面单网点查询响应,收敛为前端易消费的结构。 * * @param {*} responseData 拼多多原始响应 - * @param {Object} [expressNameMap={}] 平台快递编码到系统快递名称的映射 + * @param {Object} [expressNameMap={}] 平台快递编码到系统快递信息的映射 * @return {Object} 解析后的电子面单网点结构 */ function formatPddWaybillSearchResponse(responseData, expressNameMap = {}) { @@ -139,6 +259,9 @@ function formatPddWaybillSearchResponse(responseData, expressNameMap = {}) { const subscriptionItem = subscription && typeof subscription === 'object' ? subscription : {}; const accounts = normalizeArray(subscriptionItem.branch_account_cols).map(account => { const accountItem = account && typeof account === 'object' ? account : {}; + const customerCodes = normalizeWrappedArray(accountItem.customer_code_list, [ 'string' ]) + .map(item => normalizeText(item)) + .filter(Boolean); const shipAddresses = normalizeArray(accountItem.shipp_address_cols).map(address => { const addressItem = address && typeof address === 'object' ? address : {}; @@ -180,14 +303,21 @@ function formatPddWaybillSearchResponse(responseData, expressNameMap = {}) { cancel_quantity: accountItem.cancel_quantity ?? 0, recycled_quantity: accountItem.recycled_quantity ?? 0, allocated_quantity: accountItem.allocated_quantity ?? 0, + customer_code_list: customerCodes, ship_addresses: shipAddresses, services, }; }); + const wpCode = normalizeText(subscriptionItem.wp_code); + const expressMapping = expressNameMap[wpCode] && typeof expressNameMap[wpCode] === 'object' + ? expressNameMap[wpCode] + : {}; + return { - wp_code: normalizeText(subscriptionItem.wp_code), - wp_name: normalizeText(expressNameMap[normalizeText(subscriptionItem.wp_code)]) || '', + wp_code: wpCode, + wp_name: normalizeText(expressMapping.name) || '', + sys_express_code: normalizeText(expressMapping.sys_express_code) || '', wp_type: normalizeText(subscriptionItem.wp_type), accounts, }; @@ -200,6 +330,179 @@ function formatPddWaybillSearchResponse(responseData, expressNameMap = {}) { }; } +/** + * 判断是否命中拼多多顺丰定时派送服务。 + * + * @param {Array} list 拼多多网点解析列表 + * @return {boolean} 是否命中同步条件 + */ +function hasPddSfTimedDeliveryService(list = []) { + const normalizedList = Array.isArray(list) ? list : []; + + return normalizedList.some(expressItem => { + const expressCode = String(expressItem && expressItem.sys_express_code || '').trim().toUpperCase(); + if (expressCode !== 'SF' && expressCode !== 'SHUNFENG') { + return false; + } + + const accounts = Array.isArray(expressItem && expressItem.accounts) ? expressItem.accounts : []; + return accounts.some(account => { + const services = Array.isArray(account && account.services) ? account.services : []; + return services.some(serviceItem => String(serviceItem && serviceItem.service_code || '').trim().toUpperCase() === 'TIMED-DELIVERY'); + }); + }); +} + +/** + * 归一化淘宝菜鸟服务属性的类型描述。 + * + * @param {*} typeDesc 原始类型描述 + * @return {string} 归一化后的类型描述字符串 + */ +function normalizeTbAttributeTypeDesc(typeDesc) { + const normalizedTypeDesc = normalizeText(typeDesc); + + if (!normalizedTypeDesc) { + return normalizedTypeDesc; + } + + try { + const parsedTypeDesc = JSON.parse(normalizedTypeDesc); + + if (parsedTypeDesc && typeof parsedTypeDesc === 'object' && Object.prototype.hasOwnProperty.call(parsedTypeDesc, 'desc')) { + const descText = JSON.stringify(parsedTypeDesc.desc); + + if (typeof descText === 'string') { + return descText; + } + } + } catch (error) { + // 非 JSON 字符串保持原样,兼容原有返回结构。 + } + + return normalizedTypeDesc; +} + +/** + * 提取淘宝菜鸟电子面单响应中的签约订阅列表。 + * + * @param {*} responseData 淘宝原始响应 + * @return {Array} 标准化后的签约订阅列表 + */ +function extractTbWaybillSubscriptions(responseData) { + const waybillResponse = responseData && typeof responseData === 'object' + ? responseData.cainiao_waybill_ii_search_response || {} + : {}; + const waybillModules = waybillResponse.modules && typeof waybillResponse.modules === 'object' + ? waybillResponse.modules + : {}; + + return normalizeFirstWrappedArray( + [ waybillModules.waybill_apply_subscription_cols, waybillResponse.waybill_apply_subscription_cols ], + [ 'waybill_apply_subscription_info' ] + ); +} + +/** + * 解析淘宝菜鸟电子面单网点查询响应,收敛为前端易消费的统一结构。 + * + * @param {*} responseData 淘宝原始响应 + * @param {Object} [expressNameMap={}] 平台快递编码到系统快递信息的映射 + * @return {Object} 解析后的电子面单网点结构 + */ +function formatTbWaybillSearchResponse(responseData, expressNameMap = {}) { + const waybillResponse = responseData && typeof responseData === 'object' + ? responseData.cainiao_waybill_ii_search_response || {} + : {}; + const subscriptions = extractTbWaybillSubscriptions(responseData); + + const list = subscriptions.map(subscription => { + const subscriptionItem = subscription && typeof subscription === 'object' ? subscription : {}; + const wpCode = normalizeText(subscriptionItem.cp_code || subscriptionItem.wp_code); + const expressMapping = expressNameMap[wpCode] && typeof expressNameMap[wpCode] === 'object' + ? expressNameMap[wpCode] + : {}; + const accounts = normalizeFirstWrappedArray( + [ subscriptionItem.branch_account_cols, subscriptionItem.waybill_branch_account ], + [ 'waybill_branch_account' ] + ).map(account => { + const accountItem = account && typeof account === 'object' ? account : {}; + const customerCodes = normalizeWrappedArray(accountItem.customer_code_list, [ 'string' ]) + .map(item => normalizeText(item)) + .filter(Boolean); + const shipAddresses = normalizeFirstWrappedArray( + [ accountItem.shipp_address_cols, accountItem.address_dto ], + [ 'address_dto', 'waybill_address', 'address' ] + ).map(address => { + const addressItem = address && typeof address === 'object' ? address : {}; + + return { + country: normalizeText(addressItem.country) || '中国', + province: normalizeText(addressItem.province), + city: normalizeText(addressItem.city), + district: normalizeText(addressItem.district || addressItem.area), + detail: normalizeText(addressItem.detail || addressItem.address_detail || addressItem.address), + full_address: normalizeText(addressItem.full_address), + }; + }); + const services = normalizeFirstWrappedArray( + [ accountItem.service_info_cols, accountItem.service_info_dto ], + [ 'service_info_dto', 'waybill_service_info' ] + ).map(service => { + const serviceItem = service && typeof service === 'object' ? service : {}; + const attributes = normalizeFirstWrappedArray( + [ serviceItem.service_attributes, serviceItem.service_attribute_dto ], + [ 'service_attribute_dto', 'waybill_service_attribute' ] + ).map(attribute => { + const attributeItem = attribute && typeof attribute === 'object' ? attribute : {}; + + return { + attribute_code: normalizeText(attributeItem.attribute_code), + attribute_name: normalizeText(attributeItem.attribute_name), + attribute_type: normalizeText(attributeItem.attribute_type), + type_desc: normalizeTbAttributeTypeDesc(attributeItem.type_desc || attributeItem.attribute_type_name), + }; + }); + + return { + service_code: normalizeText(serviceItem.service_code), + service_name: normalizeText(serviceItem.service_name), + service_desc: normalizeText(serviceItem.service_desc || serviceItem.description), + required: Boolean(serviceItem.required), + attributes, + }; + }).filter(serviceItem => !shouldFilterTbService(serviceItem) && serviceItem.attributes.length > 0); + + return { + branch_code: normalizeText(accountItem.branch_code) || normalizeText(customerCodes[0]), + branch_name: normalizeText(accountItem.branch_name), + quantity: accountItem.quantity ?? 0, + cancel_quantity: accountItem.cancel_quantity ?? 0, + recycled_quantity: accountItem.recycled_quantity ?? 0, + allocated_quantity: accountItem.allocated_quantity ?? 0, + customer_code_list: customerCodes, + ship_addresses: shipAddresses, + services, + }; + }); + + return { + wp_code: wpCode, + wp_name: normalizeText(expressMapping.name) || normalizeText(subscriptionItem.cp_name), + sys_express_code: normalizeText(expressMapping.sys_express_code), + wp_type: normalizeText(subscriptionItem.wp_type || subscriptionItem.waybill_type), + accounts, + }; + }); + const totalValue = Number(waybillResponse.total); + + return { + request_id: normalizeText(waybillResponse.request_id), + total: Number.isFinite(totalValue) ? totalValue : subscriptions.length, + list, + }; +} + class indexService extends MainService { /** * 初始化基础方法的免登录、免权限、免鉴权和免日志配置。 @@ -208,10 +511,10 @@ class indexService extends MainService { */ constructor(ctx) { super(ctx); - const _noNeedLogin = 'getI18nMessage,putI18nCollect,test'; - const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPlatformOauthLink,recognizeLicensePlate'; + const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl'; + const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl'; const _noNeedLog = '*'; - const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPlatformOauthLink,recognizeLicensePlate,test'; + const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } async fastWhereTree(data) { @@ -315,7 +618,7 @@ class indexService extends MainService { baseUrl = DEFAULT_PDD_ROUTER_URL, headers = {}, timeout, - bizParams, + bizParams, biz_params: bizParamsSnake, request, ...rest @@ -829,13 +1132,18 @@ class indexService extends MainService { * * @param {Object} data 请求参数 * @param {boolean} [data.systemOnly] 是否仅返回系统基础快递列表 + * @param {string} [data.express_code] 快递公司编码 * @return {Promise} 返回结果 */ async getExpressList(data) { const { service } = this; - const { systemOnly } = data || {}; + const { + systemOnly, + express_code: expressCode = '', + } = data || {}; const isSystemOnly = [ true, 1, '1', 'true' ].includes(systemOnly); - const result = await service.systems.express.getExpressList(isSystemOnly); + const normalizedExpressCode = String(expressCode || '').trim(); + const result = await service.systems.express.getExpressList(isSystemOnly, normalizedExpressCode); return this.success('ok', { data: result, code: 200 }); } @@ -857,37 +1165,128 @@ class indexService extends MainService { * 获取平台列表。 * * @param {Object} data 请求参数 + * @param {number|string|boolean} [data.is_system=0] 是否仅返回系统基础平台列表,1 表示仅返回系统平台 * @param {boolean} [data.systemOnly] 是否仅返回系统基础平台列表 * @param {boolean} [data.full] 是否返回全量字段 * @return {Promise} 返回结果 */ async getPlatformList(data) { const { service } = this; - const { systemOnly, full } = data || {}; - const isSystemOnly = [ true, 1, '1', 'true' ].includes(systemOnly); + const payload = data || {}; + const { is_system: isSystem = 0, systemOnly, full } = payload; + const systemFilter = Object.prototype.hasOwnProperty.call(payload, 'is_system') ? isSystem : systemOnly; + const isSystemOnly = [ true, 1, '1', 'true' ].includes(systemFilter); const isFull = [ true, 1, '1', 'true' ].includes(full); const result = await service.systems.platform.getPlatformList(isSystemOnly, isFull); return this.success('ok', { data: result, code: 200 }); } + /** + * 获取打印平台全量列表。 + * + * 供前端新增、修改快递接口时下拉选择使用,不返回分页结构。 + * + * @return {Promise} 返回结果 + */ + async getPrintPlatformList() { + const { service } = this; + const result = await service.systems.setting.expressInterface.getPrintPlatformList(); + return this.success('ok', { data: result, code: 200 }); + } + + /** + * 校验店铺打印平台编码是否存在。 + * + * 运行环境未注册 `PrintPlatform` 模型时,仅做大写标准化,避免单测桩环境报错; + * 已注册模型时,强制以 `wms_print_platform.platform_code` 为准。 + * + * @param {string} platformCode 打印平台编码 + * @return {Promise} 标准化后的打印平台编码 + */ + async ensureShopPrintPlatformExists(platformCode) { + const normalizedPlatformCode = String(platformCode || '').trim().toUpperCase(); + const printPlatformModel = this.ctx && this.ctx.model && this.ctx.model.PrintPlatform; + + if (!normalizedPlatformCode) { + throw new Error('平台编码不能为空'); + } + + if (!printPlatformModel || typeof printPlatformModel.findOne !== 'function') { + return normalizedPlatformCode; + } + + const printPlatform = await printPlatformModel.findOne({ + where: { + platform_code: normalizedPlatformCode, + deleted: 0, + status: 'ACTIVE', + }, + attributes: [ 'platform_code' ], + }); + + if (!printPlatform) { + throw new Error('platform_code 未匹配到打印平台编码'); + } + + return normalizedPlatformCode; + } + + /** + * 构建店铺关联打印平台的 Sequelize include 配置。 + * + * @param {boolean} [required=false] 是否强制要求命中打印平台 + * @return {Array} include 配置列表 + */ + buildShopPrintPlatformInclude(required = false) { + const printPlatformModel = this.ctx && this.ctx.model && this.ctx.model.PrintPlatform; + + if (!printPlatformModel) { + return []; + } + + return [{ + model: printPlatformModel, + as: 'printPlatform', + required, + attributes: [ 'platform_code', 'platform_name', 'status' ], + where: { + deleted: 0, + status: 'ACTIVE', + }, + }]; + } + /** * 获取当前仓库下的店铺列表。 * + * @param {Object} [data={}] 请求参数 + * @param {string} [data.platform_code] 平台编码 + * @param {string} [data.platformCode] 平台编码,兼容驼峰字段 * @return {Promise} 返回店铺列表结果 */ - async getShopList() { + async getShopList(data = {}) { const { ctx } = this; + const { platform_code: platformCodeSnake = '', platformCode: platformCodeCamel = '' } = data || {}; const warehouseId = Number(ctx.user?.store_id); if (!warehouseId) { return this.fail('未识别到当前仓库', { code: 400 }); } + const platformCode = String(platformCodeSnake || platformCodeCamel || '').trim().toUpperCase(); + const where = { + warehouse_id: warehouseId, + status: 1, + ...buildNotDeletedShopWhere(this.app), + }; + + if (platformCode) { + where.platform_code = await this.ensureShopPrintPlatformExists(platformCode); + } + const list = await ctx.model.Shop.findAll({ - where: { - warehouse_id: warehouseId, - status: 1, - }, + where, + include: this.buildShopPrintPlatformInclude(false), order: [[ 'status', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], }); @@ -931,6 +1330,123 @@ class indexService extends MainService { return responseData; } + /** + * 实时请求淘宝菜鸟电子面单网点列表。 + * + * @param {Object} payload 请求载荷 + * @param {string} [payload.accessToken] 店铺授权令牌(session),为空时不下发 + * @param {string} [payload.cpCode] 快递公司编码 + * @return {Promise} 淘宝原始响应数据 + * @throws {Error} 淘宝返回错误结构或请求失败时抛出异常 + */ + async requestTbWaybillSearch(payload = {}) { + const { ctx } = this; + const { + accessToken, + cpCode = '', + } = payload || {}; + const appKey = String(this.app.config?.qimen?.appKey || '').trim(); + const appSecret = String(this.app.config?.qimen?.security || '').trim(); + + if (!appKey || !appSecret) { + throw new Error('淘宝接口配置缺失'); + } + + const signService = this.service.systems.sign; + if (!signService || typeof signService.signTopRequest !== 'function') { + throw new Error('签名服务不可用'); + } + + const requestParams = { + method: 'cainiao.waybill.ii.search', + app_key: appKey, + timestamp: this.app.formatDate(new Date()), + format: 'json', + v: '2.0', + sign_method: 'md5', + }; + const normalizedAccessToken = String(accessToken || '').trim(); + if (normalizedAccessToken) { + requestParams.session = normalizedAccessToken; + } + + const normalizedCpCode = String(cpCode || '').trim(); + if (normalizedCpCode) { + requestParams.cp_code = normalizedCpCode; + } + + const sign = signService.signTopRequest(requestParams, '', appSecret, 'md5'); + const response = await ctx.curl(DEFAULT_TB_ROUTER_URL, { + method: 'POST', + contentType: 'form', + dataType: 'json', + data: { + ...requestParams, + sign, + }, + }); + 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 || '淘宝菜鸟电子面单查询失败'); + } + + return responseData; + } + + /** + * 实时请求淘宝菜鸟公共标准面单模板列表。 + * + * @return {Promise} 淘宝原始响应数据 + * @throws {Error} 淘宝返回错误结构或请求失败时抛出异常 + */ + async requestTbCainiaoStdTemplates() { + const { ctx } = this; + const appKey = String(this.app.config?.qimen?.appKey || '').trim(); + const appSecret = String(this.app.config?.qimen?.security || '').trim(); + + if (!appKey || !appSecret) { + throw new Error('淘宝接口配置缺失'); + } + + const signService = this.service.systems.sign; + if (!signService || typeof signService.signTopRequest !== 'function') { + throw new Error('签名服务不可用'); + } + + const requestParams = { + method: 'cainiao.cloudprint.stdtemplates.get', + app_key: appKey, + timestamp: this.app.formatDate(new Date()), + format: 'json', + v: '2.0', + sign_method: 'md5', + }; + + const sign = signService.signTopRequest(requestParams, '', appSecret, 'md5'); + const response = await ctx.curl(DEFAULT_TB_ROUTER_URL, { + method: 'POST', + contentType: 'form', + dataType: 'json', + data: { + ...requestParams, + sign, + }, + }); + 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 || '淘宝菜鸟标准模板查询失败'); + } + + return responseData.cainiao_cloudprint_stdtemplates_get_response.result.datas.standard_template_result || []; + } + /** * 获取指定店铺的快递签约列表。 * @@ -941,7 +1457,12 @@ class indexService extends MainService { */ async getShopExpressList(data = {}) { const { ctx } = this; - const { shop_id: shopIdSnake, shopId: shopIdCamel } = data || {}; + const { + shop_id: shopIdSnake, + shopId: shopIdCamel, + cp_code: cpCodeSnake, + cpCode: cpCodeCamel, + } = data || {}; const shopId = [ shopIdSnake, shopIdCamel ].find(item => item !== undefined && item !== null && String(item).trim() !== ''); if (shopId === undefined) { @@ -958,7 +1479,9 @@ class indexService extends MainService { where: { id: shopId, warehouse_id: warehouseId, + ...buildNotDeletedShopWhere(this.app), }, + include: this.buildShopPrintPlatformInclude(true), }); if (!shop) { @@ -968,7 +1491,7 @@ class indexService extends MainService { const shopPlain = typeof shop.get === 'function' ? shop.get({ plain: true }) : shop; - const platformCode = String(shopPlain.platform_code || '').trim().toUpperCase(); + const platformCode = await this.ensureShopPrintPlatformExists(shopPlain.platform_code); let list = []; switch (platformCode) { @@ -984,6 +1507,41 @@ class indexService extends MainService { const responseData = await this.requestPddWaybillSearch(accessToken); const parsed = formatPddWaybillSearchResponse(responseData, expressNameMap); + if (hasPddSfTimedDeliveryService(parsed.list)) { + await this.service.systems.express.syncPddSfTimedDeliveryExpressProductTypes({ + shopExpressList: parsed.list, + }); + } + + list = parsed.list; + break; + } + case 'CAINIAO': { + const accessToken = String(shopPlain.access_token || '').trim(); + + if (!accessToken) { + return this.fail('店铺未授权', { code: 400 }); + } + + const cpCode = String(cpCodeSnake || cpCodeCamel || '').trim(); + const expressList = await this.service.systems.express.getExpressList(true); + const expressNameMap = buildPlatformExpressNameMap(expressList, 'CAINIAO'); + const responseData = await this.requestTbWaybillSearch({ + accessToken, + cpCode, + }); + const parsed = formatTbWaybillSearchResponse(responseData, expressNameMap); + ctx.logger.info('[SystemMethods.getShopExpressList] cainiao.waybill.ii.search 响应', JSON.stringify({ + shop_id: shopPlain.id, + cp_code: cpCode, + response: responseData, + })); + ctx.logger.info('[SystemMethods.getShopExpressList] cainiao.waybill.ii.search 解析结果', JSON.stringify({ + shop_id: shopPlain.id, + cp_code: cpCode, + parsed, + })); + list = parsed.list; break; } @@ -1002,6 +1560,220 @@ class indexService extends MainService { }); } + /** + * 获取淘宝菜鸟 STF 模板列表。 + * + * @param {Object} [data={}] 请求参数 + * @param {string} data.express_code 快递公司编码 + * @return {Promise} 返回模板列表结果 + */ + async getCainiaoStfTemplates(data = {}) { + const { express_code: expressCode = '' } = data || {}; + + return await this.getPrintPlatformTemplateList({ + platform_code: 'CAINIAO', + express_code: expressCode, + }); + } + + /** + * 规范化打印模板查询的平台编码。 + * + * @param {Object} [data={}] 请求参数 + * @param {string} [data.platform_code] 平台编码(下划线) + * @param {string} [data.platformCode] 平台编码(驼峰) + * @return {string} 规范化后的平台编码 + */ + normalizeTemplatePlatformCode(data = {}) { + const normalizedPlatformCode = String( + data.platform_code !== undefined ? data.platform_code : data.platformCode + ).trim().toUpperCase(); + + return normalizedPlatformCode || 'CAINIAO'; + } + + /** + * 规范化打印模板查询的快递编码。 + * + * @param {Object} [data={}] 请求参数 + * @param {string} [data.express_code] 快递编码(下划线) + * @param {string} [data.expressCode] 快递编码(驼峰) + * @return {string} 规范化后的快递编码 + */ + normalizeTemplateExpressCode(data = {}) { + const expressCode = data.express_code !== undefined ? data.express_code : data.expressCode; + + if (expressCode === null || expressCode === undefined) { + return ''; + } + + return String(expressCode).trim().toUpperCase(); + } + + /** + * 获取 wms_express 中指定打印平台对应的字段名。 + * + * @param {string} platformCode 打印平台编码 + * @return {string} 平台对应字段名 + */ + getExpressPlatformFieldName(platformCode) { + const expressModel = this.ctx.model && this.ctx.model.Express; + const rawAttributes = expressModel && expressModel.rawAttributes + ? expressModel.rawAttributes + : {}; + + if (rawAttributes[platformCode]) { + return platformCode; + } + + const matchedAttributeName = Object.keys(rawAttributes).find(attributeName => { + const attribute = rawAttributes[attributeName] || {}; + const attributeField = String(attribute.field || attributeName || '').trim().toUpperCase(); + return attributeField === platformCode; + }); + + if (matchedAttributeName) { + return matchedAttributeName; + } + + throw new Error(`platform_code 未匹配到 wms_express 平台字段: ${platformCode}`); + } + + /** + * 按平台字段与快递编码解析模板可用的快递编码集合。 + * + * @param {string} platformCode 打印平台编码 + * @param {string} expressCode 入参快递编码 + * @return {Promise>} 可用于模板过滤的快递编码集合 + */ + async getTemplateAllowedExpressCodeSet(platformCode, expressCode) { + const fieldName = this.getExpressPlatformFieldName(platformCode); + const expressRows = await this.ctx.model.Express.findAll({ + attributes: [ 'code', fieldName ], + where: { + [fieldName]: expressCode, + }, + }); + + const allowedCodeSet = new Set(); + + for (const expressRow of Array.isArray(expressRows) ? expressRows : []) { + const plainRow = expressRow && typeof expressRow.get === 'function' + ? expressRow.get({ plain: true }) + : expressRow || {}; + const code = String(plainRow[fieldName] || '').trim().toUpperCase(); + + if (code) { + allowedCodeSet.add(code); + } + } + + return allowedCodeSet; + } + + /** + * 按快递编码过滤打印平台模板响应。 + * + * @param {Object} responseData 平台模板原始响应 + * @param {string} platformCode 打印平台编码 + * @param {string} expressCode 入参快递编码 + * @return {Promise} 过滤后的首个响应数据;未命中时返回 undefined + */ + async filterPrintPlatformTemplateResponseData(responseData, platformCode, expressCode) { + console.log('入参', platformCode, expressCode); + // 获取对应的wp_code + const allowedCodeSet = await this.getTemplateAllowedExpressCodeSet(platformCode, expressCode); + const normalizedResponseData = Array.isArray(responseData) + ? responseData + : []; + console.log('allowedCodeSet', allowedCodeSet); + console.log('normalizedResponseData', normalizedResponseData); + // normalizedResponseData数组中的cp_code字段与allowedCodeSet匹配的第一个对象 + return normalizedResponseData.find(item => { + const itemCpCode = String(item.cp_code || '').trim().toUpperCase(); + return allowedCodeSet.has(itemCpCode); + }); + } + + /** + * 获取打印平台模板缓存键。 + * + * @param {string} platformCode 平台编码 + * @return {string} 缓存键 + */ + getPrintPlatformTemplateCacheKey(platformCode) { + if (platformCode === 'CAINIAO') { + return 'index:cainiao:stfTemplates:responseData'; + } + + return `index:printPlatform:${platformCode}:templates:responseData`; + } + + /** + * 按平台编码请求模板列表。 + * + * 当前已实现 CAINIAO 平台,其它平台返回空对象,便于后续扩展。 + * + * @param {string} platformCode 平台编码 + * @return {Promise} 平台模板响应 + */ + async requestPrintPlatformTemplateList(platformCode) { + const platformRequesters = { + CAINIAO: async () => await this.requestTbCainiaoStdTemplates(), + }; + const requester = platformRequesters[platformCode]; + + if (!requester) { + return {}; + } + + return await requester(); + } + + /** + * 获取打印平台模板列表。 + * + * 入参传入哪个平台编码,就返回该平台对应的模板数据。 + * + * @param {Object} [data={}] 请求参数 + * @param {string} [data.platform_code] 平台编码(下划线) + * @param {string} [data.platformCode] 平台编码(驼峰) + * @param {string} data.express_code 快递编码(下划线) + * @param {string} [data.expressCode] 快递编码(驼峰) + * @return {Promise} 返回模板列表结果 + */ + async getPrintPlatformTemplateList(data = {}) { + const platformCode = this.normalizeTemplatePlatformCode(data); + const expressCode = this.normalizeTemplateExpressCode(data); + + if (!expressCode) { + return this.fail('express_code 不能为空', { code: 400 }); + } + + const cacheKey = this.getPrintPlatformTemplateCacheKey(platformCode); + const cached = await this.app.getCacheAsync(cacheKey); + + const responseDataFromSource = cached !== null && cached !== undefined + ? cached + : await this.requestPrintPlatformTemplateList(platformCode); + // console.log('打印平台模板查询原始响应:', JSON.stringify(responseDataFromSource)); + + if (cached === null || cached === undefined) { + // await this.app.setCacheAsync(cacheKey, responseDataFromSource, 3600); + } + + const responseData = await this.filterPrintPlatformTemplateResponseData( + responseDataFromSource, + platformCode, + expressCode + ); + console.log('打印平台模板查询过滤后响应:', JSON.stringify(responseData)); + return this.success('ok', { + data: responseData || {}, + code: 200, + }); + } + /** * 判断是否为店铺预占记录的唯一约束冲突。 * @@ -1083,14 +1855,16 @@ class indexService extends MainService { async createPlatformOauthReservation(data) { const { ctx } = this; const { warehouseId, platformCode } = data; + const normalizedPlatformCode = await this.ensureShopPrintPlatformExists(platformCode); const maxRetryCount = 5; const prefix = this.getPlatformOauthReservationCodePrefix(); const shop = await ctx.model.Shop.findOne({ where: { warehouse_id: warehouseId, - platform_code: platformCode, + platform_code: normalizedPlatformCode, status: 0, + ...buildNotDeletedShopWhere(this.app), }, order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], }); @@ -1128,7 +1902,7 @@ class indexService extends MainService { const createdShop = await ctx.model.Shop.create({ warehouse_id: warehouseId, - platform_code: platformCode, + platform_code: normalizedPlatformCode, shop_name: `PENDING_${authRandomCode}`, status: 0, auth_expire_at: null, @@ -1162,7 +1936,7 @@ class indexService extends MainService { * @param {string} [data.code] 平台编码 * @param {string} [data.platform_code] 平台编码 * @param {string} [data.platformCode] 平台编码 - * @return {Promise} 返回授权链接结果 + * @return {Promise} 返回包含平台编码、授权链接和独立授权码的结果 */ async getPlatformOauthLink(data) { const { ctx } = this; @@ -1171,10 +1945,10 @@ class indexService extends MainService { platform_code: platformCodeSnake = '', platformCode = '', } = data || {}; - const platform_code = String(code || platformCodeSnake || platformCode || '').trim().toUpperCase(); + const rawPlatformCode = String(code || platformCodeSnake || platformCode || '').trim().toUpperCase(); const warehouseId = String(ctx.user?.store_id ?? '').trim(); - if (!platform_code) { + if (!rawPlatformCode) { return this.fail('平台编码不能为空', { code: 400 }); } @@ -1182,17 +1956,27 @@ class indexService extends MainService { return this.fail('未识别到当前仓库', { code: 400 }); } - const platform = await ctx.model.Platform.findOne({ + let platform_code = ''; + try { + platform_code = await this.ensureShopPrintPlatformExists(rawPlatformCode); + } catch (error) { + return this.fail(error.message || '平台不存在', { code: 400 }); + } + + const printPlatform = await ctx.model.PrintPlatform.findOne({ where: { - code: platform_code, + platform_code, + deleted: 0, + status: 'ACTIVE', }, + attributes: [ 'platform_code', 'auth_base_url' ], }); - if (!platform) { + if (!printPlatform) { return this.fail('平台不存在', { code: 400 }); } - const authBaseUrl = String(platform.auth_base_url || '').trim(); + const authBaseUrl = String(printPlatform.auth_base_url || '').trim(); if (!authBaseUrl) { return this.fail('平台授权基础地址未配置', { code: 400 }); } @@ -1210,12 +1994,48 @@ class indexService extends MainService { return this.success('ok', { data: { + code: reservation.authRandomCode, platform_code, oauth_link: oauthLink, }, code: 200, }); } + + /** + * 监听平台授权绑定结果。 + * + * @param {Object} data 请求参数 + * @param {string} [data.code] 业务编码 + * @param {string} [data.businessCode] 业务编码 + * @param {boolean} [data.longPoll] 是否启用长轮询 + * @return {Promise} 监听结果 + */ + async listenPlatformOauthBind(data = {}) { + const { service } = this; + const { + code = '', + businessCode = '', + business_code: businessCodeSnake = '', + longPoll = false, + long_poll: longPollSnake = false, + wait = false, + timeoutMs, + timeout_ms: timeoutMsSnake, + } = data || {}; + const result = await service.systems.platform.listenPlatformOauthBind({ + code: code || businessCode || businessCodeSnake, + longPoll: longPoll || longPollSnake || wait, + timeoutMs: timeoutMs || timeoutMsSnake, + }); + + if (result.code) { + return this.success('获取平台授权绑定状态成功', result); + } + + return this.fail(`获取平台授权绑定状态失败:${result.message}`, result); + } + /** * 前端请求生成唯一的登录码,后续可以通过这个登录码在IM系统中完成登录状态的绑定。登录码只写入到缓存中,不存储在数据库,具有较短的过期时间(如5分钟),并且只能使用一次。 * @@ -1267,5 +2087,31 @@ class indexService extends MainService { code: 200, }); } + + async polyapiAuthorizeUrl() { + const { service } = this; + const respone = await service.systems.poloApi.request('Differ.JH.BuildeAuthorizeUrl', { + appkey: this.app.config.poloApi.appKey, + appsecret: this.app.config.poloApi.appSecret, + callbackurl: 'http://39.100.57.68/', + state: '1223456', + itemcode: 'JH_001', + }, { + interface_url: 'http://aliyun.polyapi.com/OpenAPI/do', + appkey: this.app.config.poloApi.appKey, + app_secret: this.app.config.poloApi.appSecret, + platid: '544', + version: '1.5', + token: 'db820eeeb6c8425eb3f1cc25a28fb2f8', + shoptype: 'JH_001', + ordersource: 'KUAI_SHOU', + }); + return this.success('ok', { + data: { + respone, + }, + code: 200, + }); + } } module.exports = indexService; diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 27e3354..65a8006 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -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, }, }), ]); diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index ef0bc49..1cf549f 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -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) { diff --git a/app/service/systemMethods/setting/expressInterface.js b/app/service/systemMethods/setting/expressInterface.js index 81b7c1c..7ffa20e 100644 --- a/app/service/systemMethods/setting/expressInterface.js +++ b/app/service/systemMethods/setting/expressInterface.js @@ -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; } diff --git a/app/service/systemMethods/shops.js b/app/service/systemMethods/shops.js new file mode 100644 index 0000000..fd9124c --- /dev/null +++ b/app/service/systemMethods/shops.js @@ -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} 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} 查询结果 + */ + 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} 新增结果 + */ + 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} 删除结果 + */ + 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} 编辑结果 + */ + 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} 会话结果 + */ + 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; diff --git a/app/service/systems/express.js b/app/service/systems/express.js index 01219b3..c9577c5 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -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} 快递设置列表 */ - 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} expressList 系统快递列表 + * @param {Array} expressSettingList 快递设置列表 + * @return {Array} 自定义编码列表 + */ + 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} 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} 无返回值 + */ + 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} 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} 快递列表 */ - 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} 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} 无返回值。 */ 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; diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index e851193..a14e6d1 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -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} [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} [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} 当前暂未实现,直接抛出异常。 + * @return {Promise} 处理结果。 */ 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} 订单元数据映射。 + */ + 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} orderMetaMap 订单元数据映射。 + * @return {Map} 聚合结果。 + */ + 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} 无返回值。 + */ + 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, diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index 154ac47..8df9257 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -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} 去重后的快递编码候选列表。 + */ + 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} expressCodes 快递编码列表。 + * @return {Promise>} 快递编码到菜鸟编码的映射。 + */ + 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>} 接口配置列表。 + */ + 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} 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} orderRows 订单列表。 + * @param {Array} orderExpressRows 快递单列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 补齐后的快递单列表。 + */ + 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) { diff --git a/app/service/systems/platform.js b/app/service/systems/platform.js index 7ef551c..81a7f1d 100644 --- a/app/service/systems/platform.js +++ b/app/service/systems/platform.js @@ -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} 当前绑定状态 + */ + 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} 无返回值 + */ + 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} 等待结果 + */ + 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} 监听结果 + */ + 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} platformRows 平台记录列表。 + * @return {Promise>} 打印平台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} [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} [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} [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} platformList 系统平台列表。 * @param {Array} platformSettingList 平台设置列表。 - * @param full + * @param {boolean} [full=false] 是否合并全量字段。 * @return {Array} 合并后的平台列表。 */ 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, }; diff --git a/app/service/systems/setting/expressInterface.js b/app/service/systems/setting/expressInterface.js index 0c60b34..d457277 100644 --- a/app/service/systems/setting/expressInterface.js +++ b/app/service/systems/setting/expressInterface.js @@ -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} Sequelize 关联配置,仅保留系统快递关联。 + * @param {Object} [options={}] 查询选项 + * @return {Array} 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} 同步后的店铺绑定信息 + */ + 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} 规范化后的打印平台编码。 + */ + 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>} 打印平台列表。 + */ + 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} 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} 是否可用 */ @@ -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); } diff --git a/app/service/systems/shops.js b/app/service/systems/shops.js new file mode 100644 index 0000000..50c97f7 --- /dev/null +++ b/app/service/systems/shops.js @@ -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} 标准化平台编码 + */ + 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} 查询 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} 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} 列表结果 + */ + 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} 无返回 + */ + 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} 新增结果 + */ + 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} 店铺模型实例 + */ + 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} 删除结果 + */ + 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} 编辑结果 + */ + 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} 会话信息 + */ + 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; diff --git a/check_brackets.js b/check_brackets.js index 9e77f37..f739e4f 100644 --- a/check_brackets.js +++ b/check_brackets.js @@ -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.'); diff --git a/database/migrations/20260522103000-create-shops.js b/database/migrations/20260522103000-create-shops.js index 02c9bc6..c47ad1d 100644 --- a/database/migrations/20260522103000-create-shops.js +++ b/database/migrations/20260522103000-create-shops.js @@ -125,4 +125,4 @@ module.exports = { await queryInterface.dropTable(TABLE_NAME); } }, -}; \ No newline at end of file +}; diff --git a/database/migrations/20260522110000-add-auth-base-url-to-wms_platform.js b/database/migrations/20260522110000-add-auth-base-url-to-wms_platform.js index 48c2d7b..2e47399 100644 --- a/database/migrations/20260522110000-add-auth-base-url-to-wms_platform.js +++ b/database/migrations/20260522110000-add-auth-base-url-to-wms_platform.js @@ -43,4 +43,4 @@ module.exports = { await queryInterface.removeColumn(tableName, 'auth_base_url'); }, -}; \ No newline at end of file +}; diff --git a/database/migrations/20260522123000-add-auth-result-fields-to-wms-shops.js b/database/migrations/20260522123000-add-auth-result-fields-to-wms-shops.js index 6d45470..67f9722 100644 --- a/database/migrations/20260522123000-add-auth-result-fields-to-wms-shops.js +++ b/database/migrations/20260522123000-add-auth-result-fields-to-wms-shops.js @@ -99,4 +99,4 @@ module.exports = { await queryInterface.removeColumn(tableName, 'owner_id'); } }, -}; \ No newline at end of file +}; diff --git a/database/migrations/20260522133000-add-custom-name-to-wms-shops.js b/database/migrations/20260522133000-add-custom-name-to-wms-shops.js index cb22eac..1621a4a 100644 --- a/database/migrations/20260522133000-add-custom-name-to-wms-shops.js +++ b/database/migrations/20260522133000-add-custom-name-to-wms-shops.js @@ -39,4 +39,4 @@ module.exports = { await queryInterface.removeColumn(tableName, 'custom_name'); } }, -}; \ No newline at end of file +}; diff --git a/database/migrations/20260522143000-add-shop-id-to-wms-express-interface.js b/database/migrations/20260522143000-add-shop-id-to-wms-express-interface.js new file mode 100644 index 0000000..0a33f7c --- /dev/null +++ b/database/migrations/20260522143000-add-shop-id-to-wms-express-interface.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递接口配置表新增店铺 ID 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增店铺 ID 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + 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} 无返回值 + */ + 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'); + }, +}; diff --git a/database/migrations/20260523120000-expand-device-length-on-wms-system-log.js b/database/migrations/20260523120000-expand-device-length-on-wms-system-log.js new file mode 100644 index 0000000..e1f6d5a --- /dev/null +++ b/database/migrations/20260523120000-expand-device-length-on-wms-system-log.js @@ -0,0 +1,61 @@ +'use strict'; + +/** + * 扩容系统日志表 device 字段长度到 100。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:将 wms_system_log.device 调整为 VARCHAR(100)(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + 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} 无返回值 + */ + 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: '设备', + }); + }, +}; diff --git a/database/migrations/20260523130000-add-cainiao-to-wms-express.js b/database/migrations/20260523130000-add-cainiao-to-wms-express.js new file mode 100644 index 0000000..f7e1114 --- /dev/null +++ b/database/migrations/20260523130000-add-cainiao-to-wms-express.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递基础信息表新增菜鸟编码字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 CAINIAO 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + 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} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.CAINIAO) { + return; + } + + await queryInterface.removeColumn(tableName, 'CAINIAO'); + }, +}; diff --git a/database/migrations/20260524093000-add-is-hide-goods-to-wms-express-interface.js b/database/migrations/20260524093000-add-is-hide-goods-to-wms-express-interface.js new file mode 100644 index 0000000..21f6f24 --- /dev/null +++ b/database/migrations/20260524093000-add-is-hide-goods-to-wms-express-interface.js @@ -0,0 +1,47 @@ +'use strict'; + +/** + * 为快递接口配置表新增是否隐藏物品信息字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 is_hide_goods 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + 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} 无返回值 + */ + 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'); + }, +}; diff --git a/database/migrations/20260524110000-create-wms-print-platform.js b/database/migrations/20260524110000-create-wms-print-platform.js new file mode 100644 index 0000000..cb876b9 --- /dev/null +++ b/database/migrations/20260524110000-create-wms-print-platform.js @@ -0,0 +1,142 @@ +'use strict'; + +const TABLE_NAME = 'wms_print_platform'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +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>} 索引名集合。 + */ +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} 无返回值。 + */ +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} 无返回值。 + */ +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} 无返回值。 + */ + 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} 无返回值。 + */ + async down(queryInterface, Sequelize) { + void Sequelize; + + const existingTables = await getExistingTableSet(queryInterface); + if (existingTables.has(TABLE_NAME)) { + await queryInterface.dropTable(TABLE_NAME); + } + }, +}; diff --git a/database/migrations/20260524113000-add-print-platform-id-to-wms-platform.js b/database/migrations/20260524113000-add-print-platform-id-to-wms-platform.js new file mode 100644 index 0000000..e0f2295 --- /dev/null +++ b/database/migrations/20260524113000-add-print-platform-id-to-wms-platform.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为 wms_platform 新增 print_platform_id 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 print_platform_id 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + 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} 无返回值 + */ + 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'); + }, +}; diff --git a/database/migrations/20260524120000-drop-unused-fields-from-wms-print-platform.js b/database/migrations/20260524120000-drop-unused-fields-from-wms-print-platform.js new file mode 100644 index 0000000..56980f5 --- /dev/null +++ b/database/migrations/20260524120000-drop-unused-fields-from-wms-print-platform.js @@ -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>} 表名集合。 + */ +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>} 字段定义映射。 + */ +const getTableColumns = async (queryInterface, tableName) => { + return queryInterface.describeTable(tableName); +}; + +/** + * 获取指定表的索引名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise>} 索引名集合。 + */ +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} 无返回值。 + */ + 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} 无返回值。 + */ + 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, + }); + } + }, +}; diff --git a/database/migrations/20260524130000-switch-express-interface-platform-fk-to-print-platform.js b/database/migrations/20260524130000-switch-express-interface-platform-fk-to-print-platform.js new file mode 100644 index 0000000..591e0bc --- /dev/null +++ b/database/migrations/20260524130000-switch-express-interface-platform-fk-to-print-platform.js @@ -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>} 表名集合。 + */ +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} existingTableSet 已存在表名集合。 + * @param {string} tableName 表名。 + * @return {Promise} 字段定义;表不存在时返回 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>} 外键信息列表。 + */ +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} 无返回值。 + */ +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} 是否已存在。 + */ +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} 无返回值。 + */ +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} 无返回值。 + */ + 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} 无返回值。 + */ + 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' + ); + } + }, +}; diff --git a/database/migrations/20260524153000-switch-shop-platform-fk-to-print-platform.js b/database/migrations/20260524153000-switch-shop-platform-fk-to-print-platform.js new file mode 100644 index 0000000..2f05641 --- /dev/null +++ b/database/migrations/20260524153000-switch-shop-platform-fk-to-print-platform.js @@ -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>} 表名集合。 + */ +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} existingTableSet 已存在表名集合。 + * @param {string} tableName 表名。 + * @return {Promise} 字段定义;表不存在时返回 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>} 外键信息列表。 + */ +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} 无返回值。 + */ +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} 是否已存在。 + */ +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} 无返回值。 + */ +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} 无返回值。 + */ + 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} 无返回值。 + */ + 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' + ); + } + }, +}; diff --git a/database/migrations/20260524170000-migrate-auth-base-url-to-wms-print-platform.js b/database/migrations/20260524170000-migrate-auth-base-url-to-wms-print-platform.js new file mode 100644 index 0000000..2b246c2 --- /dev/null +++ b/database/migrations/20260524170000-migrate-auth-base-url-to-wms-print-platform.js @@ -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>} 表名集合。 + */ +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} existingTableSet 已存在表名集合。 + * @param {string} tableName 表名。 + * @return {Promise} 字段定义;表不存在时返回 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} 无返回值。 + */ + 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} 无返回值。 + */ + 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); + } + }, +}; diff --git a/database/migrations/20260524173000-add-template-url-to-wms-express-interface.js b/database/migrations/20260524173000-add-template-url-to-wms-express-interface.js new file mode 100644 index 0000000..4e53333 --- /dev/null +++ b/database/migrations/20260524173000-add-template-url-to-wms-express-interface.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递接口配置表新增模板链接字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 template_url 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + 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} 无返回值 + */ + 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'); + }, +}; diff --git a/database/migrations/20260524190000-add-ver-to-wms-order-express.js b/database/migrations/20260524190000-add-ver-to-wms-order-express.js new file mode 100644 index 0000000..67c1996 --- /dev/null +++ b/database/migrations/20260524190000-add-ver-to-wms-order-express.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为订单快递表新增打印版本号字段 ver。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 ver 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + 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} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_order_express'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.ver) { + return; + } + + await queryInterface.removeColumn(tableName, 'ver'); + }, +}; diff --git a/database/migrations/20260525103000-add-platid-to-wms-print-platform.js b/database/migrations/20260525103000-add-platid-to-wms-print-platform.js new file mode 100644 index 0000000..ddbba30 --- /dev/null +++ b/database/migrations/20260525103000-add-platid-to-wms-print-platform.js @@ -0,0 +1,68 @@ +'use strict'; + +const TABLE_NAME = 'wms_print_platform'; +const COLUMN_NAME = 'platid'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +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} 无返回值。 + */ + 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} 无返回值。 + */ + 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); + }, +}; diff --git a/final_sf.json b/final_sf.json new file mode 100644 index 0000000000000000000000000000000000000000..f1abf530cc9b25fc005ebd219f96d1b08918a5c6 GIT binary patch literal 112110 zcmds=dyE~|ecwm5g%mETrs^NEq%>TuBwMsZ@wI%qi7ip0WLxBtT2g$AA(u;v(k}PG zB_)av8xn-t1t{CNyR{IY0^&#k3bMBAz)o#BcB&|dR5$%2Y7nCaY7&VYNQGk;2&$q% zt)9>Q@$j6PIdkUBoVjyX#e(F%c<*<9@7MXA_kMYQ^04|CR)5wf8}WEcjH$2ItFNcj&!1FZ%_PT@$JD>$>SG{TlH8v>rM?Z_UVyB$^EU825!K>gvJ z?p8lNo-FVF?|anu^!p4XN7PSeyWfBK>i^u(eeW@agP)jJ;k`ejehW-TyU#eLkgxCl z245dl?>DKwKCb@X;bfco%?b6sht63C!jm7zQ;2jSD)Y4{n>%!A15E`Qtw!D zQhj$u{r*PvH`H8`d|Le`zdz8W;iCDM#@; z6N&vBXH#DdBzGu^EK7!xRmtM+YoAUA)w4i%dG)D&FImk{cw6cb@7Zgx*kmM*S@N8*pq&{eL(yqW+9_ zX?sY~nBQF1eHGynuR7cP?q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gHy(kI%dBxOL|YCNOf_k?=ZG4-yqY6rkm z>bnLZG65Hks`or*eSe@!*^OPAjw@boRi7PDafLy1zj|enz)vY`f_y~%Cep+1w!5A0 zoqoT&l1=Irk%h@F9}cVkdv~%$ef6YzjTuD)Bw<{A+}(X%8~KEK59yR0zw*;#NtVBw PyKvw9zC1mD^XLBoaxox1 literal 0 HcmV?d00001 diff --git a/methods/changes/system.json b/methods/changes/system.json index 4cdc45c..da3a8d2 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -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" } ] diff --git a/methods/system.json b/methods/system.json index 8df1aac..29a4cb8 100644 --- a/methods/system.json +++ b/methods/system.json @@ -2,7 +2,7 @@ "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", "version": "0.0.1", - "updatedAt": "2026-05-22", + "updatedAt": "2026-05-25", "headers": [ { "name": "platform", @@ -947,7 +947,7 @@ }, { "method": "index.getShopList", - "description": "获取当前登录仓库下的店铺列表。仓库上下文来自 ctx.user.store_id,不接受额外业务入参;服务端按 status DESC、updated_at DESC、id DESC 排序查询 wms_shops,并对敏感字段完成脱敏后返回 data.list。", + "description": "获取当前登录仓库下的已授权店铺列表,支持按平台编码可选过滤。仓库上下文来自 ctx.user.store_id;服务端兼容读取 body.platform_code 与 body.platformCode,按该顺序取首个 trim 后非空值作为平台过滤条件。未传平台参数时返回当前登录仓库下全部已授权店铺;传入非空平台编码时仅返回该平台的已授权店铺。结果按 status DESC、updated_at DESC、id DESC 排序,并对敏感字段完成脱敏后返回 data.list。", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -958,7 +958,15 @@ "description": "Bearer token" } ], - "params": [], + "params": [ + { + "name": "platform_code", + "type": "string", + "required": false, + "source": "body", + "description": "平台编码过滤条件;兼容 platformCode。服务端按 platform_code、platformCode 的顺序读取首个值,trim 后非空时仅返回该平台的已授权店铺;未传或为空时返回当前登录仓库下全部已授权店铺。" + } + ], "response": [ { "name": "code", @@ -976,7 +984,7 @@ "name": "data.list", "type": "array", "required": true, - "description": "当前登录仓库下的店铺列表数组;结果按 status DESC、updated_at DESC、id DESC 排序,且 owner_id、access_token、refresh_token、auth_random_code 已按实现规则脱敏。", + "description": "当前登录仓库下按条件过滤后的已授权店铺列表数组;未传平台参数时返回当前仓库全部已授权店铺,传入非空 platform_code/platformCode 时仅返回对应平台店铺。结果按 status DESC、updated_at DESC、id DESC 排序,且 owner_id、access_token、refresh_token、auth_random_code 已按实现规则脱敏。", "children": [ { "name": "id", @@ -1134,6 +1142,18 @@ "required": true, "description": "快递/面单服务编码。" }, + { + "name": "wp_name", + "type": "string", + "required": true, + "description": "系统快递名称;由系统快递基础表根据平台快递编码 wp_code 映射得到,未匹配到时返回空字符串。" + }, + { + "name": "sys_express_code", + "type": "string", + "required": true, + "description": "系统快递编码;由平台快递编码 wp_code 映射得到,未匹配到时返回空字符串。" + }, { "name": "wp_type", "type": "string", @@ -1313,6 +1333,186 @@ "message": "店铺未授权" } ] + }, + { + "method": "index.getCainiaoStfTemplates", + "description": "公共无参查询淘宝菜鸟标准模板列表;服务端调用淘宝开放平台 cainiao.cloudprint.stdtemplates.get,请求地址为 https://eco.taobao.com/router/rest,使用 TOP 公共签名参数。不需要用户授权,不下发 session,不依赖登录态、当前仓库或店铺授权。成功返回 data.platform_code='TB' 与标准模板数组,模板项统一字段为 template_id/template_name/template_url/cp_code/wp_code。", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功时返回 200。" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息,成功时返回 ok。" + }, + { + "name": "data.platform_code", + "type": "string", + "required": true, + "description": "平台编码,固定返回 TB。" + }, + { + "name": "data.list", + "type": "array", + "required": true, + "description": "菜鸟标准模板列表;来源于 cainiao_cloudprint_stdtemplates_get_response.result.datas[*].standard_templates[*] 的宽松兼容解析结果,按统一字段 template_id/template_name/template_url/cp_code/wp_code 返回。", + "children": [ + { + "name": "template_id", + "type": "string", + "required": true, + "description": "模板唯一标识;缺失时返回空字符串。" + }, + { + "name": "template_name", + "type": "string", + "required": true, + "description": "模板名称;缺失时返回空字符串。" + }, + { + "name": "template_url", + "type": "string", + "required": true, + "description": "模板预览或打印地址;缺失时返回空字符串。" + }, + { + "name": "cp_code", + "type": "string", + "required": true, + "description": "快递公司编码;结合 datas 节点与模板项宽松提取,缺失时返回空字符串。" + }, + { + "name": "wp_code", + "type": "string", + "required": true, + "description": "快递面单服务编码;结合 datas 节点的 brand_code/cp_code 与模板项宽松提取,缺失时返回空字符串。" + } + ] + } + ], + "errors": [ + { + "code": 500, + "message": "淘宝菜鸟标准模板查询失败" + } + ] + }, + { + "method": "index.getPrintPlatformTemplateList", + "description": "按打印平台与快递编码查询模板列表。express_code 为必填;接口会先按 platform_code(默认 CAINIAO)定位 wms_express 对应打印平台字段,再以 express_code 过滤可用模板后返回。", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "platform_code", + "type": "string", + "required": false, + "source": "body", + "description": "打印平台编码(如 CAINIAO);不传默认 CAINIAO,服务端会转为大写。" + }, + { + "name": "express_code", + "type": "string", + "required": true, + "source": "body", + "description": "快递编码(必填);服务端会转为大写,并用于按 wms_express 中对应打印平台字段筛选模板。" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "全局结果标识;成功为 success,失败为 failure。" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码;成功时为 200。" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息;成功时为 ok。" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "返回数据对象。", + "children": [ + { + "name": "platform_code", + "type": "string", + "required": true, + "description": "规范化后的平台编码(大写);未传时默认 CAINIAO。" + }, + { + "name": "express_code", + "type": "string", + "required": true, + "description": "规范化后的快递编码(大写)。" + }, + { + "name": "responseData", + "type": "object", + "required": true, + "description": "平台模板响应数据;CAINIAO 场景下会按 platform_code 对应字段 + express_code 过滤 cainiao_cloudprint_stdtemplates_get_response.result.datas 后返回,未实现平台返回空对象。" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "express_code 不能为空" + }, + { + "code": 500, + "message": "获取打印平台模板列表失败" + } + ] + }, + { + "method": "index.polyapiAuthorizeUrl", + "description": "生成菠萝派授权链接。该接口不接收请求参数,服务端会固定调用 Differ.JH.BuildeAuthorizeUrl,并以内置配置 this.app.config.poloApi.appKey / this.app.config.poloApi.secret 以及当前代码中写死的 callbackUrl=http://39.100.57.68/、state=123456、itemcode=test001 作为上游请求参数,最终将菠萝派接口原始响应包裹后返回。", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功时返回 200。" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息,成功时返回 ok。" + }, + { + "name": "data.respone", + "type": "object", + "required": true, + "description": "菠萝派接口 Differ.JH.BuildeAuthorizeUrl 的原始响应对象。字段名按当前实现保持为 respone。" + } + ], + "errors": [] } ] }, @@ -9467,12 +9667,100 @@ "list": [ { "method": "index.getExpressList", - "description": "合并后的快递列表", + "description": "获取快递列表。默认返回系统基础快递与当前登录仓库自定义快递编码的合并结果:系统快递在前,仓库自定义编码在后,同一 `code` 仅保留首条(系统同码优先保留系统记录)。当 `systemOnly` 为真值(支持 `true`、`1`、`'1'`、`'true'`)时,仅返回系统基础快递列表。仅接受 `express_code` 入参,服务端会先 trim 再转为大写:`systemOnly=true` 时按系统快递编码过滤系统基础快递列表;`systemOnly=false` 时按自定义编码映射记录中的系统快递编码字段 `express_code` 过滤,仅返回当前登录仓库下匹配该系统快递编码的自定义编码列表,不再回传系统基础项。仓库范围来自当前登录用户 `ctx.user.store_id`;未识别到仓库时,自定义编码列表为空。接口优先读取缓存,未命中时回源 `wms_express` 与 `wms_express_setting`。", "isNeedAuth": false, "isNeedLogin": true, - "params": [], - "response": [], - "errors": [] + "headers": [], + "params": [ + { + "name": "systemOnly", + "type": "boolean|number|string", + "required": false, + "source": "body", + "description": "是否仅返回系统基础快递列表;仅 `true`、`1`、`'1'`、`'true'` 会被识别为 true,其余值按 false 处理" + }, + { + "name": "express_code", + "type": "string", + "required": false, + "source": "body", + "description": "系统快递编码;服务端会去首尾空格并转为大写。`systemOnly=true` 时按该系统快递编码过滤系统基础快递列表;`systemOnly=false` 时按自定义映射记录中的系统快递编码字段 `express_code` 过滤当前仓库的自定义编码列表,而不是按自定义 `code` 过滤" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "全局调用结果标识,成功时为 `success`" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功时返回 200" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "返回消息,成功时通常为 `ok`" + }, + { + "name": "data", + "type": "array", + "required": true, + "description": "快递列表数组。默认模式下先返回系统基础快递,再追加当前仓库自定义编码;当传入 `express_code` 且 `systemOnly=false` 时,仅返回当前仓库下系统快递编码等于该 `express_code` 的自定义映射记录,不返回系统基础项。每项字段如下:", + "children": [ + { + "name": "code", + "type": "string", + "description": "返回项编码。系统项为系统快递编码;仓库自定义项为自定义快递编码" + }, + { + "name": "name", + "type": "string", + "description": "展示名称。系统项为快递名称;仓库自定义项格式通常为 `<自定义编码> (<系统快递名>)`,若未匹配到系统快递名则退化为自定义编码" + }, + { + "name": "value", + "type": "string", + "description": "与 `code` 相同,供前端选项组件直接使用" + }, + { + "name": "label", + "type": "string", + "description": "与 `name` 相同,供前端选项组件直接使用" + }, + { + "name": "is_system_setting", + "type": "boolean", + "description": "是否为仓库自定义快递编码;`false` 表示系统基础快递,`true` 表示来自当前仓库 `wms_express_setting` 的自定义编码" + }, + { + "name": "id", + "type": "number|null", + "description": "仓库自定义快递设置记录 ID;系统基础快递固定为 `null`" + }, + { + "name": "alias", + "type": "string|null", + "description": "仓库自定义快递设置表中的原始名称(`wms_express_setting.name`);系统基础快递固定为 `null`" + }, + { + "name": "express_code", + "type": "string", + "description": "仅仓库自定义快递编码项返回其关联的系统快递编码;当 `systemOnly=false` 且传入筛选值时,即按该字段匹配自定义映射记录。系统基础快递项通常不返回该字段" + } + ] + } + ], + "errors": [ + { + "code": 500, + "message": "获取快递列表失败(数据库或缓存访问异常)" + } + ] }, { "method": "setting.express.list", @@ -9771,7 +10059,7 @@ "list": [ { "method": "setting.expressInterface.list", - "description": "查询当前仓库范围的快递接口列表,支持 where + pagination;返回 data:{ list, total, page, page_size }。每条记录字段见 children。", + "description": "查询当前仓库范围的快递接口列表,支持 where + pagination;返回 data:{ list, total, page, page_size }。按 weight 升序、id 降序排序,优先按权重排序。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -9788,14 +10076,14 @@ "type": "object", "required": false, "source": "body", - "description": "分页参数,支持 page / pageSize,兼容 currentPage / page_size / size" + "description": "pagination" }, { "name": "where", "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;支持字段:id、name、express_code、platform_code、express_platform_id、sender_name、sender_tel、viewer、client_id、share_id、site_code、product_type、shop_name。支持 quickWhere 快速关键词。" + "description": "支持按 shop_id 过滤" } ], "response": [ @@ -9803,146 +10091,54 @@ "name": "list", "type": "array", "required": true, - "description": "快递接口记录数组(每项字段如下)", "children": [ { "name": "id", "type": "number", - "description": "记录ID" + "description": "id", + "required": true }, { "name": "name", "type": "string", - "description": "接口名称" + "description": "name", + "required": true }, { - "name": "express_code", - "type": "string", - "description": "快递编码" - }, - { - "name": "warehouse_id", + "name": "shop_id", "type": "number", - "description": "所属仓库ID(文档中的仓库范围由系统强制校验)" + "description": "店铺 ID,未绑定时返回 null", + "required": false }, { - "name": "platform_code", - "type": "string", - "description": "平台代码" - }, - { - "name": "express_platform_id", + "name": "is_system_express_code", "type": "number", - "description": "平台接口ID" - }, - { - "name": "sender_name", - "type": "string", - "description": "发件人姓名" - }, - { - "name": "sender_tel", - "type": "string", - "description": "发件人电话" - }, - { - "name": "weight", - "type": "number", - "description": "默认重量" - }, - { - "name": "token", - "type": "string", - "description": "接口密钥或 token(部分记录可能为空)" - }, - { - "name": "viewer", - "type": "string", - "description": "查看者标识" - }, - { - "name": "client_id", - "type": "string", - "description": "客户端 ID" - }, - { - "name": "is_share", - "type": "number", - "description": "是否共享(0/1)" - }, - { - "name": "share_id", - "type": "number", - "description": "共享记录ID" - }, - { - "name": "can_use_count", - "type": "number", - "description": "可用次数或配额" - }, - { - "name": "province_name", - "type": "string", - "description": "省" - }, - { - "name": "city_name", - "type": "string", - "description": "市" - }, - { - "name": "district_name", - "type": "string", - "description": "区/县" - }, - { - "name": "site_code", - "type": "string", - "description": "站点编码" - }, - { - "name": "product_type", - "type": "string", - "description": "快递产品类型" - }, - { - "name": "shop_name", - "type": "string", - "description": "店铺名称/分组标识" - }, - { - "name": "ext_data", - "type": "object", - "description": "扩展信息 JSON(支持任意键值对象)" + "description": "该行 express_code 是否为系统快递编码;若不是系统快递编码返回 0,否则返回 1", + "required": true } - ] + ], + "description": "list,按 weight 升序、id 降序排序;优先按权重排序,权重相同再按 id 倒序" }, { "name": "total", "type": "number", - "description": "匹配的总记录数" + "description": "total", + "required": true }, { "name": "page", "type": "number", - "description": "当前页" + "description": "page", + "required": true }, { "name": "page_size", "type": "number", - "description": "每页数量" + "description": "page_size", + "required": true } ], - "errors": [ - { - "code": "400", - "description": "缺少仓库上下文或 where 参数解析失败" - }, - { - "code": "500", - "description": "查询失败" - } - ] + "errors": [] }, { "method": "setting.expressInterface.listByWarehousePlatformCode", @@ -10133,7 +10329,7 @@ }, { "method": "setting.expressInterface.create", - "description": "在当前仓库范围内创建快递接口。支持 snake_case 与 camelCase 别名入参;sys_express_code 可选显式传入,不传时服务端按 express_code + platform_code 自动解析系统快递编码;同仓快递编码或平台重复不再直接返回 409。", + "description": "在当前仓库范围内创建快递接口,支持 shop_id/shopId 入参。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -10150,175 +10346,28 @@ "type": "string", "required": true, "source": "body", - "description": "接口名称" + "description": "name" }, { "name": "express_code", "type": "string", "required": true, "source": "body", - "description": "外部快递 code(支持 expressCode),不区分大小写,服务端会转为大写" + "description": "express_code" }, { "name": "platform_code", "type": "string", "required": true, "source": "body", - "description": "平台代码(支持 platformCode),不区分大小写,服务端会转为大写" + "description": "platform_code" }, { - "name": "sys_express_code", - "type": "string", - "required": false, - "source": "body", - "description": "系统快递编码(支持 sysExpressCode)可选显式传入;未传时服务端按 express_code + platform_code 自动解析" - }, - { - "name": "sender_name", - "type": "string", - "required": false, - "source": "body", - "description": "发件人姓名(支持 senderName,可选,最长 50 字符)" - }, - { - "name": "sender_tel", - "type": "string", - "required": false, - "source": "body", - "description": "发件人电话(支持 senderTel,可选,最长 11 字符)" - }, - { - "name": "weight", + "name": "shop_id", "type": "number", "required": false, "source": "body", - "description": "默认重量(可选,整数)" - }, - { - "name": "weight_type", - "type": "number", - "required": false, - "source": "body", - "description": "重量类型(支持 weightType,可选,整数)" - }, - { - "name": "token", - "type": "string", - "required": false, - "source": "body", - "description": "接口密钥或 token(可选,最长 500 字符)" - }, - { - "name": "viewer", - "type": "string", - "required": false, - "source": "body", - "description": "查看者标识(可选,最长 50 字符)" - }, - { - "name": "client_id", - "type": "string", - "required": false, - "source": "body", - "description": "客户端 ID(支持 clientId,可选,最长 50 字符)" - }, - { - "name": "is_share", - "type": "number", - "required": false, - "source": "body", - "description": "是否共享(支持 isShare;0/1,可选,默认 0)" - }, - { - "name": "share_id", - "type": "number", - "required": false, - "source": "body", - "description": "共享记录 ID(支持 shareId,可选,整数)" - }, - { - "name": "ispickup", - "type": "number", - "required": false, - "source": "body", - "description": "是否上门取件(支持 isPickup;0/1,可选,默认 0)" - }, - { - "name": "shipperno", - "type": "string", - "required": false, - "source": "body", - "description": "电子面单客户号(支持 shipperNo,可选,最长 255 字符)" - }, - { - "name": "can_use_count", - "type": "number", - "required": false, - "source": "body", - "description": "可用次数/配额(支持 canUseCount,可选,整数,最小 0)" - }, - { - "name": "province_name", - "type": "string", - "required": false, - "source": "body", - "description": "省(支持 provinceName,可选,最长 255 字符)" - }, - { - "name": "city_name", - "type": "string", - "required": false, - "source": "body", - "description": "市(支持 cityName,可选,最长 255 字符)" - }, - { - "name": "district_name", - "type": "string", - "required": false, - "source": "body", - "description": "区/县(支持 districtName,可选,最长 255 字符)" - }, - { - "name": "address", - "type": "string", - "required": false, - "source": "body", - "description": "详细地址(可选,最长 255 字符)" - }, - { - "name": "town_name", - "type": "string", - "required": false, - "source": "body", - "description": "乡镇/街道(支持 townName,可选,最长 255 字符)" - }, - { - "name": "site_code", - "type": "string", - "required": false, - "source": "body", - "description": "站点编码(支持 siteCode,可选,最长 255 字符)" - }, - { - "name": "product_type", - "type": "string", - "required": false, - "source": "body", - "description": "快递产品类型(支持 productType,可选,最长 50 字符)" - }, - { - "name": "shop_name", - "type": "string", - "required": false, - "source": "body", - "description": "店铺名称/分组标识(支持 shopName,可选,最长 255 字符)" - }, - { - "name": "ext_data", - "type": "object", - "required": false, - "source": "body", - "description": "扩展信息 JSON(支持 extData),可选,建议传对象" + "description": "店铺 ID(支持 shopId),正整数,可空;未传或空值按 null 处理" } ], "response": [ @@ -10329,24 +10378,11 @@ "description": "新建记录 ID" } ], - "errors": [ - { - "code": 400, - "message": "必填参数缺失或参数格式错误" - }, - { - "code": 400, - "message": "express_code 未匹配到系统快递编码" - }, - { - "code": 400, - "message": "sys_express_code 未匹配到系统快递编码" - } - ] + "errors": [] }, { "method": "setting.expressInterface.update", - "description": "更新快递接口,支持局部字段更新与 snake_case/camelCase 别名;支持 id 别名 interface_id / interfaceId;当 express_code/platform_code/sys_express_code 变更时会重算系统快递编码;同仓快递编码或平台重复不再直接返回 409。", + "description": "更新快递接口,支持 shop_id/shopId 入参(可空)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -10363,220 +10399,25 @@ "type": "number", "required": true, "source": "body", - "description": "快递接口 ID;兼容 interface_id / interfaceId" + "description": "id" }, { - "name": "name", - "type": "string", - "required": false, - "source": "body", - "description": "接口名称" - }, - { - "name": "express_code", - "type": "string", - "required": false, - "source": "body", - "description": "外部快递 code(支持 expressCode),更新时会转为大写" - }, - { - "name": "platform_code", - "type": "string", - "required": false, - "source": "body", - "description": "平台代码(支持 platformCode),更新时会转为大写" - }, - { - "name": "sys_express_code", - "type": "string", - "required": false, - "source": "body", - "description": "系统快递编码(支持 sysExpressCode)可选显式传入;不传时服务端按 express_code + platform_code 自动解析" - }, - { - "name": "sender_name", - "type": "string", - "required": false, - "source": "body", - "description": "发件人姓名(支持 senderName)" - }, - { - "name": "sender_tel", - "type": "string", - "required": false, - "source": "body", - "description": "发件人电话(支持 senderTel)" - }, - { - "name": "weight", + "name": "shop_id", "type": "number", "required": false, "source": "body", - "description": "默认重量" - }, - { - "name": "weight_type", - "type": "number", - "required": false, - "source": "body", - "description": "重量类型(支持 weightType)" - }, - { - "name": "token", - "type": "string", - "required": false, - "source": "body", - "description": "接口密钥或 token" - }, - { - "name": "viewer", - "type": "string", - "required": false, - "source": "body", - "description": "查看者标识" - }, - { - "name": "client_id", - "type": "string", - "required": false, - "source": "body", - "description": "客户端 ID(支持 clientId)" - }, - { - "name": "is_share", - "type": "number", - "required": false, - "source": "body", - "description": "是否共享(支持 isShare;0/1)" - }, - { - "name": "share_id", - "type": "number", - "required": false, - "source": "body", - "description": "共享记录 ID(支持 shareId)" - }, - { - "name": "ispickup", - "type": "number", - "required": false, - "source": "body", - "description": "是否上门取件(支持 isPickup;0/1)" - }, - { - "name": "shipperno", - "type": "string", - "required": false, - "source": "body", - "description": "电子面单客户号(支持 shipperNo)" - }, - { - "name": "can_use_count", - "type": "number", - "required": false, - "source": "body", - "description": "可用次数/配额(支持 canUseCount)" - }, - { - "name": "province_name", - "type": "string", - "required": false, - "source": "body", - "description": "省(支持 provinceName)" - }, - { - "name": "city_name", - "type": "string", - "required": false, - "source": "body", - "description": "市(支持 cityName)" - }, - { - "name": "district_name", - "type": "string", - "required": false, - "source": "body", - "description": "区/县(支持 districtName)" - }, - { - "name": "address", - "type": "string", - "required": false, - "source": "body", - "description": "详细地址" - }, - { - "name": "town_name", - "type": "string", - "required": false, - "source": "body", - "description": "乡镇/街道(支持 townName)" - }, - { - "name": "site_code", - "type": "string", - "required": false, - "source": "body", - "description": "站点编码(支持 siteCode)" - }, - { - "name": "product_type", - "type": "string", - "required": false, - "source": "body", - "description": "快递产品类型(支持 productType)" - }, - { - "name": "shop_name", - "type": "string", - "required": false, - "source": "body", - "description": "店铺名称/分组标识(支持 shopName)" - }, - { - "name": "ext_data", - "type": "object", - "required": false, - "source": "body", - "description": "扩展信息 JSON(支持 extData)" + "description": "shop_id" } ], "response": [ { "name": "id", "type": "number", - "required": true, - "description": "首条更新记录 ID" - }, - { - "name": "name", - "type": "string", - "required": false, - "description": "更新后的接口名称" + "description": "id", + "required": true } ], - "errors": [ - { - "code": 400, - "message": "id 参数不能为空" - }, - { - "code": 400, - "message": "至少需要提供一个可更新字段" - }, - { - "code": 400, - "message": "express_code 未匹配到系统快递编码" - }, - { - "code": 400, - "message": "sys_express_code 未匹配到系统快递编码" - }, - { - "code": 404, - "message": "快递接口不存在或无权限操作" - } - ] + "errors": [] }, { "method": "setting.expressInterface.delete", @@ -10627,6 +10468,93 @@ "description": "快递接口不存在或无权限操作" } ] + }, + { + "method": "index.getPrintPlatformList", + "description": "获取打印平台全量列表。供前端新增、修改快递接口时下拉选择使用;仅返回未删除且状态为 `ACTIVE` 的打印平台,不分页,按 `platform_name` 升序、`id` 升序返回。接口不校验额外鉴权或权限点,但需要登录态。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "全局调用结果标识,成功时为 `success`" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功时返回 200" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "返回消息,成功时通常为 `ok`" + }, + { + "name": "data", + "type": "array", + "required": true, + "description": "打印平台列表数组,不分页,仅包含未删除且状态为 `ACTIVE` 的平台;按 `platform_name` 升序、`id` 升序返回。每项字段如下:", + "children": [ + { + "name": "id", + "type": "number|null", + "description": "打印平台主键 ID;原始值为空时返回 `null`" + }, + { + "name": "code", + "type": "string", + "description": "打印平台编码,等同于 `platform_code`,服务端会标准化为大写" + }, + { + "name": "name", + "type": "string", + "description": "打印平台展示名称;若原始 `platform_name` 为空,则回退为 `platform_code`" + }, + { + "name": "value", + "type": "string", + "description": "与 `code` 相同,供前端选项组件直接使用" + }, + { + "name": "label", + "type": "string", + "description": "与 `name` 相同,供前端选项组件直接使用" + }, + { + "name": "platform_code", + "type": "string", + "description": "打印平台编码,大写返回" + }, + { + "name": "platform_name", + "type": "string|null", + "description": "打印平台名称;为空时前端可使用 `name` 或 `label` 展示" + }, + { + "name": "status", + "type": "string", + "description": "平台状态;当前接口仅返回 `ACTIVE`,若原始值缺失会兜底为 `ACTIVE`" + }, + { + "name": "remark", + "type": "string|null", + "description": "打印平台备注;无备注时返回 `null`" + } + ] + } + ], + "errors": [ + { + "code": 500, + "message": "获取打印平台列表失败" + } + ] } ] }, @@ -17918,6 +17846,535 @@ ] } ] + }, + { + "groupName": "店铺模块", + "module": "shops", + "list": [ + { + "method": "shops.list", + "description": "分页查询店铺,支持 where 条件(支持字段:id, platform_code, custom_name, shop_name, status, quickWhere),兼容 snake_case 与 camelCase 入参;返回分页信息与标准化店铺列表。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,兼容 pagination.page/currentPage" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页大小,兼容 page_size/pagination.page_size,最大 200" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件,支持标准 where 结构或 quickWhere 简写,字段兼容 id/platform_code/custom_name/shop_name/status/quickWhere" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "调用结果标识,成功为 success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功为 200" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.list", + "type": "array", + "required": true, + "description": "店铺数组,元素结构见 children", + "children": [ + { + "name": "id", + "type": "number", + "description": "店铺 ID" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "仓库 ID" + }, + { + "name": "platform_code", + "type": "string", + "description": "平台编码,返回大写" + }, + { + "name": "platform_name", + "type": "string", + "description": "平台名称(来自关联 printPlatform)" + }, + { + "name": "shop_name", + "type": "string", + "description": "店铺原始名称" + }, + { + "name": "custom_name", + "type": "string|null", + "description": "店铺自定义名称" + }, + { + "name": "status", + "type": "number", + "description": "授权状态:0=未授权,1=已授权" + }, + { + "name": "created_at", + "type": "string", + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "description": "更新时间" + } + ] + }, + { + "name": "data.pagination", + "type": "object", + "required": true, + "description": "分页信息", + "children": [ + { + "name": "page", + "type": "number", + "description": "当前页" + }, + { + "name": "pageSize", + "type": "number", + "description": "每页大小" + }, + { + "name": "total", + "type": "number", + "description": "总记录数" + }, + { + "name": "totalPages", + "type": "number", + "description": "总页数" + }, + { + "name": "hasNext", + "type": "boolean", + "description": "是否有下一页" + }, + { + "name": "hasPrevious", + "type": "boolean", + "description": "是否有上一页" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库" + }, + { + "code": 400, + "message": "where 参数解析失败" + }, + { + "code": 500, + "message": "查询店铺列表失败" + } + ] + }, + { + "method": "shops.add", + "description": "新增店铺,校验 platform_code 必须匹配已配置且处于 ACTIVE 且未删除的打印平台;custom_name 必填且长度<=100;shop_name 可选,缺失时使用 custom_name。支持 snake_case 与 camelCase 入参兼容。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "platform_code", + "type": "string", + "required": true, + "source": "body", + "description": "平台编码,兼容 platformCode,服务端会标准化为大写并验证" + }, + { + "name": "custom_name", + "type": "string", + "required": true, + "source": "body", + "description": "店铺自定义名称,最大长度 100" + }, + { + "name": "shop_name", + "type": "string", + "required": false, + "source": "body", + "description": "店铺名称,若不传则以 custom_name 作为 shop_name" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "200 成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.id", + "type": "number", + "required": true, + "description": "新建店铺 ID" + } + ], + "errors": [ + { + "code": 400, + "message": "platform_code 未匹配到打印平台编码" + }, + { + "code": 400, + "message": "custom_name 不能为空" + }, + { + "code": 400, + "message": "custom_name 长度不能超过 100" + }, + { + "code": 409, + "message": "同仓同平台下 shop_name 已存在" + }, + { + "code": 500, + "message": "新增店铺失败" + } + ] + }, + { + "method": "shops.del", + "description": "软删除店铺:将 shop_name 修改为 DELETED_SHOP__ 并清空敏感字段;若存在 ExpressInterface 引用则返回 409;返回 deleted=true 与 id。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "店铺 ID,兼容 shop_id/shopId" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "200 成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.deleted", + "type": "boolean", + "required": true, + "description": "是否已删除" + }, + { + "name": "data.id", + "type": "number", + "required": true, + "description": "删除的店铺 ID" + } + ], + "errors": [ + { + "code": 400, + "message": "shop_id 参数不合法" + }, + { + "code": 404, + "message": "店铺不存在" + }, + { + "code": 409, + "message": "店铺存在快递接口引用,无法删除" + }, + { + "code": 500, + "message": "删除店铺失败" + } + ] + }, + { + "method": "shops.edit", + "description": "编辑店铺,仅允许修改 platform_code 或 custom_name;至少传入其中一个。platform_code 会校验平台存在且为 ACTIVE;custom_name 必填且长度<=100;服务端兼容 snake_case/camelCase。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "店铺 ID,兼容 shop_id/shopId" + }, + { + "name": "platform_code", + "type": "string", + "required": false, + "source": "body", + "description": "平台编码,兼容 platformCode,服务端会转为大写并校验" + }, + { + "name": "custom_name", + "type": "string", + "required": false, + "source": "body", + "description": "自定义名称,兼容 customName,若传入需非空且 <=100 字符" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "200 成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.updated", + "type": "boolean", + "required": true, + "description": "是否已更新" + }, + { + "name": "data.id", + "type": "number", + "required": true, + "description": "被更新的店铺 ID" + } + ], + "errors": [ + { + "code": 400, + "message": "仅允许修改 platform_code 或 custom_name" + }, + { + "code": 400, + "message": "platform_code 未匹配到打印平台编码" + }, + { + "code": 400, + "message": "custom_name 不能为空" + }, + { + "code": 409, + "message": "同仓同平台下 shop_name 已存在" + }, + { + "code": 500, + "message": "编辑店铺失败" + } + ] + }, + { + "method": "shop.GetAuthorizeSessionKey", + "description": "按店铺所属平台生成授权会话。入参兼容 id/shop_id/shopId 与 callbackurl/callback_url,callbackurl 必填。对已实现的平台(PDD/CAINIAO)返回 session_key/authorize_url/state,其他平台返回 501 未实现。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "店铺 ID,兼容 shop_id/shopId" + }, + { + "name": "callbackurl", + "type": "string", + "required": true, + "source": "body", + "description": "回调地址,兼容 callback_url" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "200 成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.shop_id", + "type": "number", + "required": true, + "description": "店铺 ID" + }, + { + "name": "data.platform_code", + "type": "string", + "required": true, + "description": "平台编码(大写)" + }, + { + "name": "data.callbackurl", + "type": "string", + "required": true, + "description": "回调地址" + }, + { + "name": "data.session_key", + "type": "string", + "required": true, + "description": "授权预占码(session)" + }, + { + "name": "data.authorize_url", + "type": "string", + "required": true, + "description": "平台授权跳转地址(含 state)" + }, + { + "name": "data.state", + "type": "string", + "required": true, + "description": "内部 state 值(platform + '_' + authRandomCode),用于回调解析" + } + ], + "errors": [ + { + "code": 400, + "message": "callbackurl 不能为空" + }, + { + "code": 400, + "message": "未识别到当前仓库" + }, + { + "code": 404, + "message": "店铺不存在" + }, + { + "code": 400, + "message": "平台授权基础地址未配置" + }, + { + "code": 501, + "message": "平台 %s 暂未实现授权会话换取能力" + }, + { + "code": 500, + "message": "生成唯一授权码失败,请稍后重试" + } + ] + } + ] } ] } diff --git a/package.json b/package.json index e2d159a..0f86b25 100644 --- a/package.json +++ b/package.json @@ -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" diff --git a/raw_redis.json b/raw_redis.json new file mode 100644 index 0000000000000000000000000000000000000000..e61205be447ce64a2296103ee81a32a70bc5a88b GIT binary patch literal 111412 zcmds=Ym6S(dEbYLjRtP3rYTU_l9H@eQmh-r+w$tBlthV=?T{;m_nS84a!FCzQnvB#)mNK2Il8$@1i5 z$(jClhLTOmP%<<+vEw(+{qKWE{`vKZCnx^iJM&L(+J48-rsU^`{_)W}hAyeUe`@7W za&NLKS(%I^Ym@u>zjYxQPR5hTlr;-`GVx>_D_Ih zM*TkTuv7gR@4v?}^=`b@%Kod!yYs4=1{ab;>icQ@W9t8t>bK7-95d?mc(S=Psr?Re?^wH>_hKfhjd-L7X>hoCcz4g1v6Ui$c zy!l?^3Oi3St$uUj=IerxpZb;LaU~(^lGRE=Rwiqb_3ATUf3W|#{C%tAJf?7@@f}sq zBu{6f1R?a|XTg13{fv3KP<&&GXUA^7-&*x_>y$3=yy3rpO1IqjXTE|En2><-@eXH)faCPC;*=?75Q;S2h^M5q)i-+&+bMbz~KPY-%B}&$n zJkX@=WHrgNsS+o7>k1@K5N3HQl84l-N;dT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-y4tnW|Ui^Neg2$zd| ze^_R{?3=peo+pqXeYej4^4==3Mi-I?w)FIuO^vu*F5aILZDbMp?T4VJ;~JNX=XuH9 zK)3eiah4tz4F^T)@!rU^(1HK?>wSJdP(QkMNjnJ3C##s|=Byres41OH-`53>?mA(` z)s>>kil!4D-O!@VTT<<+aY!vzBlK$|=;_DCZdP_{96fuinn!vEj_Iy z9Mv?5i?qY{f67TRc3iVb*Ph%4VK%SJ^K_6NJx{|tK6@^cUYhJWjk6xRdS*Ar$rJY< zp}qnZCNkN$^`&#YsRs|fxTlLfP44<0Xo~j;8^3T&xSnI@);IgtcHvhk}6hMQ(qqU&u6pqY#0sZEu**$G!a8-(tOKI6-XjQrPJZ z>6S~Hma?t=NcWLsr`mTvcrKco{sxk1hJae}*W6p$9;g7QpSsrrB)qAgVZD>J<#UDlbE2QD`F5-*ma>-p| z`s@>&49ybT@kefpVXOrRv1`@jO{S|kiybF%{64Y1+_-q({MU{x4xJwb(;zp2>8Z^0 zL?)<;CV*{v#8v*V9#Vthv&hbbs;r+@aoK5SCTw~DAcT`=)dcgnibBq)4|uyt;XbXt zI`Qr+o>u>!?SBQn+m?i%hbzyi6PkL9=yS>W#nc3~- z$;WQ~lzy!t^|NIkmlOX7uccoDd|TA>AQdP2{5h}g#W|%YH~sF<=%3|po^8AO-kgdi zX4LPDE1Dcvf1nQEyH|a_PyKzc^ob5D$rw`i2A@{%dsaQ`gnHLGbxQvQ^;Lrq8Gr*P z)qBcKE*cHUxAti|sd&3X{p*N|APkzv)hmm{eNGyju*`{6* zIhgMA;kf$Uhmxn%|DIQ`aaz#;DVS6r5A~ndMn0w9L#mu-ZhrSvlI5@FF5EXiFHg_s F{|9}VN*MqE literal 0 HcmV?d00001 diff --git a/redis_output.txt b/redis_output.txt new file mode 100644 index 0000000000000000000000000000000000000000..e61205be447ce64a2296103ee81a32a70bc5a88b GIT binary patch literal 111412 zcmds=Ym6S(dEbYLjRtP3rYTU_l9H@eQmh-r+w$tBlthV=?T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SBQn+m?i%hbzyi6PkL9=yS>W#nc3~- z$;WQ~lzy!t^|NIkmlOX7uccoDd|TA>AQdP2{5h}g#W|%YH~sF<=%3|po^8AO-kgdi zX4LPDE1Dcvf1nQEyH|a_PyKzc^ob5D$rw`i2A@{%dsaQ`gnHLGbxQvQ^;Lrq8Gr*P z)qBcKE*cHUxAti|sd&3X{p*N|APkzv)hmm{eNGyju*`{6* zIhgMA;kf$Uhmxn%|DIQ`aaz#;DVS6r5A~ndMn0w9L#mu-ZhrSvlI5@FF5EXiFHg_s F{|9}VN*MqE literal 0 HcmV?d00001 diff --git a/result_sf.json b/result_sf.json new file mode 100644 index 0000000000000000000000000000000000000000..f1abf530cc9b25fc005ebd219f96d1b08918a5c6 GIT binary patch literal 112110 zcmds=dyE~|ecwm5g%mETrs^NEq%>TuBwMsZ@wI%qi7ip0WLxBtT2g$AA(u;v(k}PG zB_)av8xn-t1t{CNyR{IY0^&#k3bMBAz)o#BcB&|dR5$%2Y7nCaY7&VYNQGk;2&$q% zt)9>Q@$j6PIdkUBoVjyX#e(F%c<*<9@7MXA_kMYQ^04|CR)5wf8}WEcjH$2ItFNcj&!1FZ%_PT@$JD>$>SG{TlH8v>rM?Z_UVyB$^EU825!K>gvJ z?p8lNo-FVF?|anu^!p4XN7PSeyWfBK>i^u(eeW@agP)jJ;k`ejehW-TyU#eLkgxCl z245dl?>DKwKCb@X;bfco%?b6sht63C!jm7zQ;2jSD)Y4{n>%!A15E`Qtw!D zQhj$u{r*PvH`H8`d|Le`zdz8W;iCDM#@; z6N&vBXH#DdBzGu^EK7!xRmtM+YoAUA)w4i%dG)D&FImk{cw6cb@7Zgx*kmM*S@N8*pq&{eL(yqW+9_ zX?sY~nBQF1eHGynuR7cP?qG6SNtRH;@OgiiR+H-852;r~0+E;f>Xl~IcXQxV^*UrATem8j{dBr_fpJ__{ z52$cRA(o$kkk1}cnz=k#ovct2vMgDdtWkgS{kytbuxquxQ)F_pmBUb275DE4Q{BEmd4MG+C-B zyww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D)Bw<{A+}(X%8~KEK59yR0zw*;#NtVBw PyKvw9zC1mD^XLBoaxox1 literal 0 HcmV?d00001 diff --git a/run-target-migration.js b/run-target-migration.js new file mode 100644 index 0000000..f51248e --- /dev/null +++ b/run-target-migration.js @@ -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(); diff --git a/script/run-single-migration.cjs b/script/run-single-migration.cjs index 1210b39..a72c070 100644 --- a/script/run-single-migration.cjs +++ b/script/run-single-migration.cjs @@ -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); diff --git a/temp.json b/temp.json new file mode 100644 index 0000000000000000000000000000000000000000..e61205be447ce64a2296103ee81a32a70bc5a88b GIT binary patch literal 111412 zcmds=Ym6S(dEbYLjRtP3rYTU_l9H@eQmh-r+w$tBlthV=?T{;m_nS84a!FCzQnvB#)mNK2Il8$@1i5 z$(jClhLTOmP%<<+vEw(+{qKWE{`vKZCnx^iJM&L(+J48-rsU^`{_)W}hAyeUe`@7W za&NLKS(%I^Ym@u>zjYxQPR5hTlr;-`GVx>_D_Ih zM*TkTuv7gR@4v?}^=`b@%Kod!yYs4=1{ab;>icQ@W9t8t>bK7-95d?mc(S=Psr?Re?^wH>_hKfhjd-L7X>hoCcz4g1v6Ui$c zy!l?^3Oi3St$uUj=IerxpZb;LaU~(^lGRE=Rwiqb_3ATUf3W|#{C%tAJf?7@@f}sq zBu{6f1R?a|XTg13{fv3KP<&&GXUA^7-&*x_>y$3=yy3rpO1IqjXTE|En2><-@eXH)faCPC;*=?75Q;S2h^M5q)i-+&+bMbz~KPY-%B}&$n zJkX@=WHrgNsS+o7>k1@K5N3HQl84l-N;dTW3{LVuh#gN`kJa8D_tL^uD`&ap=KGki9j2b)h$Y*XbR-AM9SX?2X>7m)o&iS;=xs6^POijw@QzG{9f3 zR56858~m1Ql@+JCBkyd~4Z^s{d;QHgZ=?|(3jaU_55K>A*@fBpKc0B6aMI8M3*nDI z{G41p08WxM5WTO9jA*|-Ju~;I*>5gP9YOctB@$hpZ^l@5xBivu9?uLy{oE_m)7RI( zqL?)w2}*9xyRKFr>y)hcqy>cexC1VT z=N~jo^Ke67R@XMjLz8v*^v+-tzViRU*ozS*edz02Rf};~R&2@hb1~dr>`=AhkE=Rr z7>#r#mY;T2Q$Sc$Yb>j%WHaw(swu0Kc97HR3ecV^(B>Zq-L>ry9yS#RcEw3U z3*tbxm2lg67bl4Y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sr`mTvcrKco{sxk1hJae}*W6p$9;g7QpSsrrB)qAgVZD>J<#UDlbE2QD`F5-*ma>-p| z`s@>&49ybT@kefpVXOrRv1`@jO{S|kiybF%{64Y1+_-q({MU{x4xJwb(;zp2>8Z^0 zL?)<;CV*{v#8v*V9#Vthv&hbbs;r+@aoK5SCTw~DAcT`=)dcgnibBq)4|uyt;XbXt zI`Qr+o>u>!?SBQn+m?i%hbzyi6PkL9=yS>W#nc3~- z$;WQ~lzy!t^|NIkmlOX7uccoDd|TA>AQdP2{5h}g#W|%YH~sF<=%3|po^8AO-kgdi zX4LPDE1Dcvf1nQEyH|a_PyKzc^ob5D$rw`i2A@{%dsaQ`gnHLGbxQvQ^;Lrq8Gr*P z)qBcKE*cHUxAti|sd&3X{p*N|APkzv)hmm{eNGyju*`{6* zIhgMA;kf$Uhmxn%|DIQ`aaz#;DVS6r5A~ndMn0w9L#mu-ZhrSvlI5@FF5EXiFHg_s F{|9}VN*MqE literal 0 HcmV?d00001 diff --git a/test/app/controller/home.test.js b/test/app/controller/home.test.js index ae4657a..42e57f4 100644 --- a/test/app/controller/home.test.js +++ b/test/app/controller/home.test.js @@ -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'); + }); }); diff --git a/test/app/lib/pdd_client.test.js b/test/app/lib/pdd_client.test.js index d25037b..783aa0e 100644 --- a/test/app/lib/pdd_client.test.js +++ b/test/app/lib/pdd_client.test.js @@ -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'); }); -}); \ No newline at end of file +}); diff --git a/test/app/lib/pdd_sign.test.js b/test/app/lib/pdd_sign.test.js index 9c60d5e..a10b1a3 100644 --- a/test/app/lib/pdd_sign.test.js +++ b/test/app/lib/pdd_sign.test.js @@ -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'); }); -}); \ No newline at end of file +}); diff --git a/test/app/lib/polo_api_client.test.js b/test/app/lib/polo_api_client.test.js new file mode 100644 index 0000000..3da4ba7 --- /dev/null +++ b/test/app/lib/polo_api_client.test.js @@ -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); + }); +}); diff --git a/test/app/lib/qimen_client.test.js b/test/app/lib/qimen_client.test.js index 6fb2471..0fbe9a9 100644 --- a/test/app/lib/qimen_client.test.js +++ b/test/app/lib/qimen_client.test.js @@ -115,4 +115,80 @@ describe('test/app/lib/qimen_client.test.js', () => { assert.match(sentXml, /\s*/); assert.doesNotMatch(sentXml, /\s*/); }); + + 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: 'success200ok', + }; + }; + + 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); + }); }); diff --git a/test/app/service/systemMethods/index.test.js b/test/app/service/systemMethods/index.test.js index 9fb5bd1..d8b7ada 100644 --- a/test/app/service/systemMethods/index.test.js +++ b/test/app/service/systemMethods/index.test.js @@ -3,22 +3,124 @@ const assert = require('node:assert/strict'); const IndexMethodService = require('../../../../app/service/systemMethods/index'); +/** + * 创建 systemMethods.index 的最小测试桩环境。 + * + * @return {{service: Object, ctx: Object, calls: Object}} 测试桩对象 + */ function createHarness() { const calls = { curl: 0, + getCacheAsync: 0, + syncPddSfTimedDeliveryExpressProductTypes: 0, + setCacheAsync: 0, + getExpressProductTypeList: 0, + getPrintPlatformList: 0, + printPlatformFindOne: 0, + printPlatformFindOneCalls: [], + expressFindAll: 0, + platformFindOne: 0, + shopCreate: 0, }; const ctx = { + user: { + store_id: 100000, + }, app: { + formatDate() { + return '2026-05-24 12:00:00'; + }, + async getCacheAsync(key) { + calls.getCacheAsync += 1; + calls.getCacheAsyncPayload = key; + return undefined; + }, + async setCacheAsync(key, value, ttl) { + calls.setCacheAsync += 1; + calls.setCacheAsyncPayload = { + key, + value, + ttl, + }; + }, config: { pdd: { client_id: '1', client_secret: 'testSecret', }, + qimen: { + appKey: 'tbAppKey', + security: 'tbAppSecret', + }, + }, + }, + model: { + PrintPlatform: { + async findOne(options) { + calls.printPlatformFindOne += 1; + calls.printPlatformFindOnePayload = options; + calls.printPlatformFindOneCalls.push(options); + const platformCode = options && options.where && options.where.platform_code; + + if (!platformCode) { + return null; + } + + return { + platform_code: platformCode, + auth_base_url: 'https://oauth.example.com/auth?state=', + }; + }, + }, + Platform: { + async findOne(options) { + calls.platformFindOne += 1; + calls.platformFindOnePayload = options; + const code = options && options.where && options.where.code; + + if (code === 'TB') { + return { + code: 'TB', + auth_base_url: 'https://oauth.example.com/auth?state=', + }; + } + + return null; + }, + }, + Express: { + rawAttributes: { + code: { field: 'code' }, + CAINIAO: { field: 'CAINIAO' }, + PDD: { field: 'PDD' }, + DYXD: { field: 'DYXD' }, + KS: { field: 'KS' }, + }, + async findAll(options) { + calls.expressFindAll += 1; + calls.expressFindAllPayload = options; + return []; + }, + }, + Shop: { + async findOne() { + return null; + }, + async findAll() { + return []; + }, + async create(payload) { + calls.shopCreate += 1; + calls.shopCreatePayload = payload; + return payload; + }, }, }, logger: { error() {}, + info() {}, + warn() {}, }, async curl(url, options) { calls.curl += 1; @@ -35,6 +137,54 @@ function createHarness() { const service = Object.create(IndexMethodService.prototype); service.ctx = ctx; service.app = ctx.app; + service.service = { + systems: { + express: { + async getExpressList() { + return []; + }, + async getExpressProductTypeList(expressCode) { + calls.getExpressProductTypeList += 1; + calls.getExpressProductTypeListPayload = expressCode; + return []; + }, + async syncPddSfTimedDeliveryExpressProductTypes(payload) { + calls.syncPddSfTimedDeliveryExpressProductTypes += 1; + calls.syncPayload = payload; + return { + createdCount: 0, + updatedCount: 0, + parsedCount: 0, + }; + }, + }, + setting: { + expressInterface: { + async getPrintPlatformList() { + calls.getPrintPlatformList += 1; + return [ + { + id: 1, + code: 'CAINIAO', + name: '菜鸟电子面单', + value: 'CAINIAO', + label: '菜鸟电子面单', + platform_code: 'CAINIAO', + platform_name: '菜鸟电子面单', + platid: '1001', + }, + ]; + }, + }, + }, + sign: { + signTopRequest(params) { + calls.tbSignParams = { ...params }; + return 'TB_SIGN'; + }, + }, + }, + }; return { service, @@ -100,4 +250,1396 @@ describe('test/app/service/systemMethods/index.test.js', () => { assert.equal(result.flag, 'success'); assert.equal(result.code, 200); }); -}); \ No newline at end of file + + it('getShopExpressList 在 PDD 下 SF 且无 TIMED-DELIVERY 时应补齐时效服务', async () => { + const { service, ctx, calls } = createHarness(); + + ctx.model.Shop.findOne = async () => ({ + get() { + return { + id: 12, + warehouse_id: 100000, + platform_code: 'PDD', + access_token: 'ACCESS_TOKEN', + }; + }, + }); + service.service.systems.express.getExpressList = async isEnabled => { + assert.equal(isEnabled, true); + return [ + { + code: 'SF', + name: '顺丰', + PDD: 'SF-PDD', + }, + ]; + }; + service.service.systems.express.getExpressProductTypeList = async expressCode => { + calls.getExpressProductTypeList += 1; + calls.getExpressProductTypeListPayload = expressCode; + return [ + { code: 'T6', name: '特快' }, + { code: 'T7', name: '标快' }, + ]; + }; + service.requestPddWaybillSearch = async accessToken => { + assert.equal(accessToken, 'ACCESS_TOKEN'); + return { + pdd_waybill_search_response: { + request_id: 'REQ-001', + waybill_apply_subscription_cols: [ + { + wp_code: 'SF-PDD', + wp_type: '1', + branch_account_cols: [ + { + branch_code: 'PDD-BRANCH-001', + branch_name: '拼多多直营网点', + }, + ], + }, + { + wp_code: 'UNKNOWN-PDD', + wp_type: '2', + branch_account_cols: [], + }, + ], + }, + }; + }; + + const result = await service.getShopExpressList({ + shop_id: 12, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(result.data.shop_id, 12); + assert.equal(result.data.platform_code, 'PDD'); + assert.equal(result.data.list[0].wp_name, '顺丰'); + assert.equal(result.data.list[0].sys_express_code, 'SF'); + assert.deepEqual(result.data.list[0].accounts[0].services, []); + assert.equal(result.data.list[1].wp_name, ''); + assert.equal(result.data.list[1].sys_express_code, ''); + assert.equal(calls.syncPddSfTimedDeliveryExpressProductTypes, 0); + assert.equal(calls.getExpressProductTypeList, 0); + }); + + it('getShopExpressList 在 TB 下 SF 且无 TIMED-DELIVERY 时也应补齐时效服务', async () => { + const { service, ctx, calls } = createHarness(); + + ctx.model.Shop.findOne = async () => ({ + get() { + return { + id: 23, + warehouse_id: 100000, + platform_code: 'CAINIAO', + access_token: 'TB_ACCESS_TOKEN', + printPlatform: { + platform_code: 'CAINIAO', + platform_name: '菜鸟电子面单', + }, + }; + }, + }); + service.service.systems.express.getExpressList = async isEnabled => { + assert.equal(isEnabled, true); + return [ + { + code: 'SF', + name: '顺丰', + CAINIAO: 'SF', + }, + ]; + }; + service.service.systems.express.getExpressProductTypeList = async expressCode => { + calls.getExpressProductTypeList += 1; + calls.getExpressProductTypeListPayload = expressCode; + return [ + { code: 'T6', name: '特快' }, + ]; + }; + service.requestTbWaybillSearch = async payload => { + assert.deepEqual(payload, { + accessToken: 'TB_ACCESS_TOKEN', + cpCode: 'SF', + }); + + return { + cainiao_waybill_ii_search_response: { + request_id: 'TB-REQ-023', + modules: { + waybill_apply_subscription_cols: { + waybill_apply_subscription_info: { + cp_code: 'SF', + cp_name: '顺丰', + waybill_type: 'STANDARD', + branch_account_cols: { + waybill_branch_account: { + branch_name: '顺丰直营网点', + customer_code_list: { + string: 'SF-TB-001', + }, + service_info_cols: { + service_info_dto: [ + { + service_code: 'SPECIAL', + service_name: '普通服务', + service_desc: '非定时服务', + required: false, + service_attributes: { + service_attribute_dto: { + attribute_code: 'SPECIAL_CODE', + attribute_name: '服务编码', + attribute_type: 'INPUT', + type_desc: '文本', + }, + }, + }, + ], + }, + }, + }, + }, + }, + }, + }, + }; + }; + + const result = await service.getShopExpressList({ + shop_id: 23, + cp_code: 'SF', + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(result.data.platform_code, 'CAINIAO'); + assert.deepEqual(result.data.list[0].accounts[0].services, [ + { + service_code: 'SPECIAL', + service_name: '普通服务', + service_desc: '非定时服务', + required: false, + attributes: [ + { + attribute_code: 'SPECIAL_CODE', + attribute_name: '服务编码', + attribute_type: 'INPUT', + type_desc: '文本', + }, + ], + }, + ]); + assert.equal(calls.getExpressProductTypeList, 0); + assert.equal(calls.syncPddSfTimedDeliveryExpressProductTypes, 0); + }); + + it('getShopExpressList 在 SF 且已有 TIMED-DELIVERY 时不应重复追加', async () => { + const { service, ctx, calls } = createHarness(); + + ctx.model.Shop.findOne = async () => ({ + get() { + return { + id: 21, + warehouse_id: 100000, + platform_code: 'PDD', + access_token: 'ACCESS_TOKEN', + }; + }, + }); + service.service.systems.express.getExpressList = async () => ([ + { + code: 'SF', + name: '顺丰', + PDD: 'SF-PDD', + }, + ]); + service.requestPddWaybillSearch = async () => ({ + pdd_waybill_search_response: { + request_id: 'REQ-021', + waybill_apply_subscription_cols: [ + { + wp_code: 'SF-PDD', + wp_type: '1', + branch_account_cols: [ + { + branch_code: 'PDD-BRANCH-021', + branch_name: '顺丰网点', + service_info_cols: [ + { + service_code: 'TIMED-DELIVERY', + service_name: '定时派送', + service_desc: '顺丰定时派送', + required: false, + service_attributes: [ + { + attribute_code: 'PRODUCT_TYPE', + attribute_name: '产品类型', + attribute_type: 'SELECT', + type_desc: '{"T6":"特快"}', + }, + ], + }, + ], + }, + ], + }, + ], + }, + }); + + const result = await service.getShopExpressList({ + shop_id: 21, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.data.list[0].accounts[0].services.length, 1); + assert.equal(result.data.list[0].accounts[0].services[0].service_code, 'TIMED-DELIVERY'); + assert.equal(calls.getExpressProductTypeList, 0); + }); + + it('getShopExpressList 在非 SF 快递时不应补齐 TIMED-DELIVERY', async () => { + const { service, ctx, calls } = createHarness(); + + ctx.model.Shop.findOne = async () => ({ + get() { + return { + id: 22, + warehouse_id: 100000, + platform_code: 'PDD', + access_token: 'ACCESS_TOKEN', + }; + }, + }); + service.service.systems.express.getExpressList = async () => ([ + { + code: 'YTO', + name: '圆通', + PDD: 'YTO-PDD', + }, + ]); + service.requestPddWaybillSearch = async () => ({ + pdd_waybill_search_response: { + request_id: 'REQ-022', + waybill_apply_subscription_cols: [ + { + wp_code: 'YTO-PDD', + wp_type: '1', + branch_account_cols: [ + { + branch_code: 'PDD-BRANCH-022', + branch_name: '圆通网点', + service_info_cols: [], + }, + ], + }, + ], + }, + }); + + const result = await service.getShopExpressList({ + shop_id: 22, + }); + + assert.equal(result.flag, 'success'); + assert.deepEqual(result.data.list[0].accounts[0].services, []); + assert.equal(calls.getExpressProductTypeList, 0); + }); + + it('getShopExpressList 应仅在拼多多顺丰定时派送场景触发产品类型同步', async () => { + const { service, ctx, calls } = createHarness(); + + ctx.model.Shop.findOne = async () => ({ + get() { + return { + id: 13, + warehouse_id: 100000, + platform_code: 'PDD', + access_token: 'ACCESS_TOKEN', + }; + }, + }); + service.service.systems.express.getExpressList = async () => ([ + { + code: 'SF', + name: '顺丰', + PDD: 'SF-PDD', + }, + ]); + service.requestPddWaybillSearch = async () => ({ + pdd_waybill_search_response: { + request_id: 'REQ-002', + waybill_apply_subscription_cols: [ + { + wp_code: 'SF-PDD', + wp_type: '1', + branch_account_cols: [ + { + branch_code: 'PDD-BRANCH-002', + branch_name: '顺丰网点', + service_info_cols: [ + { + service_code: 'TIMED-DELIVERY', + service_name: '定时派送', + service_desc: '顺丰定时派送', + required: false, + service_attributes: [ + { + attribute_code: 'PRODUCT_TYPE', + attribute_name: '产品类型', + attribute_type: 'SELECT', + type_desc: '{"T6":"特快","T7":"标快"}', + }, + ], + }, + ], + }, + ], + }, + ], + }, + }); + + const result = await service.getShopExpressList({ + shop_id: 13, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(calls.syncPddSfTimedDeliveryExpressProductTypes, 1); + assert.deepEqual(calls.syncPayload, { + shopExpressList: result.data.list, + }); + }); + + it('getShopExpressList 应将淘宝菜鸟响应转换为统一结构', async () => { + const { service, ctx } = createHarness(); + + ctx.model.Shop.findOne = async () => ({ + get() { + return { + id: 18, + warehouse_id: 100000, + platform_code: 'CAINIAO', + access_token: 'TB_ACCESS_TOKEN', + printPlatform: { + platform_code: 'CAINIAO', + platform_name: '菜鸟电子面单', + }, + }; + }, + }); + service.service.systems.express.getExpressList = async isEnabled => { + assert.equal(isEnabled, true); + return [ + { + code: 'YTO_SYS', + name: '圆通速递', + CAINIAO: 'YTO', + }, + ]; + }; + service.requestTbWaybillSearch = async payload => { + assert.deepEqual(payload, { + accessToken: 'TB_ACCESS_TOKEN', + cpCode: 'YTO', + }); + + return { + cainiao_waybill_ii_search_response: { + request_id: 'TB-REQ-001', + modules: { + waybill_apply_subscription_cols: { + waybill_apply_subscription_info: { + cp_code: 'YTO', + cp_name: '圆通', + waybill_type: 'STANDARD', + branch_account_cols: { + waybill_branch_account: { + branch_name: '杭州转运中心', + quantity: 20, + cancel_quantity: 2, + allocated_quantity: 6, + customer_code_list: { + string: 'CUST-001', + }, + address_dto: { + province: '浙江省', + city: '杭州市', + district: '余杭区', + detail: '文一西路1号', + }, + service_info_dto: { + service_code: 'SEND_TIME', + service_name: '派送时效', + service_desc: '预约派送', + required: true, + service_attribute_dto: { + attribute_code: 'TIME_RANGE', + attribute_name: '时段', + attribute_type: 'SELECT', + type_desc: '枚举', + }, + }, + }, + }, + }, + }, + }, + }, + }; + }; + + const result = await service.getShopExpressList({ + shop_id: 18, + cp_code: 'YTO', + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(result.data.shop_id, 18); + assert.equal(result.data.platform_code, 'CAINIAO'); + assert.deepEqual(result.data.list[0], { + wp_code: 'YTO', + wp_name: '圆通速递', + sys_express_code: 'YTO_SYS', + wp_type: 'STANDARD', + accounts: [ + { + branch_code: 'CUST-001', + branch_name: '杭州转运中心', + quantity: 20, + cancel_quantity: 2, + recycled_quantity: 0, + allocated_quantity: 6, + customer_code_list: [ 'CUST-001' ], + ship_addresses: [ + { + country: '中国', + province: '浙江省', + city: '杭州市', + district: '余杭区', + detail: '文一西路1号', + full_address: '', + }, + ], + services: [ + { + service_code: 'SEND_TIME', + service_name: '派送时效', + service_desc: '预约派送', + required: true, + attributes: [ + { + attribute_code: 'TIME_RANGE', + attribute_name: '时段', + attribute_type: 'SELECT', + type_desc: '枚举', + }, + ], + }, + ], + }, + ], + }); + }); + + it('getShopExpressList 应过滤淘宝代收货款、定时派送、空属性服务并保留普通服务', async () => { + const { service, ctx } = createHarness(); + + ctx.model.Shop.findOne = async () => ({ + get() { + return { + id: 19, + warehouse_id: 100000, + platform_code: 'CAINIAO', + access_token: 'TB_ACCESS_TOKEN', + printPlatform: { + platform_code: 'CAINIAO', + platform_name: '菜鸟电子面单', + }, + }; + }, + }); + service.service.systems.express.getExpressList = async () => ([ + { + code: 'ZTO_SYS', + name: '中通快递', + CAINIAO: 'ZTO', + }, + ]); + service.requestTbWaybillSearch = async () => ({ + cainiao_waybill_ii_search_response: { + request_id: 'TB-REQ-002', + modules: { + waybill_apply_subscription_cols: { + waybill_apply_subscription_info: { + cp_code: 'ZTO', + cp_name: '中通', + waybill_type: 'STANDARD', + branch_account_cols: { + waybill_branch_account: { + branch_name: '上海分拨中心', + customer_code_list: { + string: 'CUST-002', + }, + shipp_address_cols: { + address_dto: { + province: '上海市', + city: '上海市', + district: '青浦区', + detail: '华徐公路99号', + }, + }, + service_info_cols: { + service_info_dto: [ + { + service_code: 'COD', + service_name: '货到付款', + service_desc: '签收收款', + required: false, + service_attributes: { + service_attribute_dto: { + attribute_code: 'AMOUNT_LIMIT', + attribute_name: '金额限制', + attribute_type: 'INPUT', + type_desc: '文本', + }, + }, + }, + { + service_code: 'INTERCEPT_NOTE', + service_name: '拦截件', + service_desc: '异常件拦截服务', + required: false, + service_attributes: { + service_attribute_dto: { + attribute_code: 'INTERCEPT_REASON', + attribute_name: '拦截原因', + attribute_type: 'INPUT', + type_desc: '文本', + }, + }, + }, + { + service_code: 'APPOINTMENT_DELIVERY', + service_name: '定时派送', + service_desc: '预约时间段配送', + required: false, + service_attributes: { + service_attribute_dto: { + attribute_code: 'DELIVERY_TIME', + attribute_name: '派送时间', + attribute_type: 'SELECT', + type_desc: '枚举', + }, + }, + }, + { + service_code: 'TRADE_IN', + service_name: '上门取旧换新', + service_desc: '支持上门取旧换新服务', + required: false, + service_attributes: { + service_attribute_dto: { + attribute_code: 'TRADE_IN_NOTICE', + attribute_name: '换新说明', + attribute_type: 'INPUT', + type_desc: '文本', + }, + }, + }, + { + service_code: 'EMPTY_ATTR_SERVICE', + service_name: '短信通知', + service_desc: '普通服务但无属性', + required: false, + service_attributes: { + service_attribute_dto: [], + }, + }, + { + service_code: 'INSURE', + service_name: '运费险', + service_desc: '普通增值服务', + required: true, + service_attributes: { + service_attribute_dto: { + attribute_code: 'INSURE_TYPE', + attribute_name: '投保类型', + attribute_type: 'SELECT', + type_desc: '枚举', + }, + }, + }, + ], + }, + }, + }, + }, + }, + }, + }, + }); + + const result = await service.getShopExpressList({ + shop_id: 19, + cp_code: 'ZTO', + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.data.list[0].accounts[0].ship_addresses[0].province, '上海市'); + assert.deepEqual(result.data.list[0].accounts[0].services, [ + { + service_code: 'INSURE', + service_name: '运费险', + service_desc: '普通增值服务', + required: true, + attributes: [ + { + attribute_code: 'INSURE_TYPE', + attribute_name: '投保类型', + attribute_type: 'SELECT', + type_desc: '枚举', + }, + ], + }, + ]); + }); + + it('getShopExpressList 应提取淘宝 type_desc.desc 并保留扁平 JSON 字符串', async () => { + const { service, ctx } = createHarness(); + + ctx.model.Shop.findOne = async () => ({ + get() { + return { + id: 20, + warehouse_id: 100000, + platform_code: 'CAINIAO', + access_token: 'TB_ACCESS_TOKEN', + printPlatform: { + platform_code: 'CAINIAO', + platform_name: '菜鸟电子面单', + }, + }; + }, + }); + service.service.systems.express.getExpressList = async () => ([ + { + code: 'SF_SYS', + name: '顺丰速运', + CAINIAO: 'SF', + }, + ]); + service.requestTbWaybillSearch = async () => ({ + cainiao_waybill_ii_search_response: { + request_id: 'TB-REQ-003', + modules: { + waybill_apply_subscription_cols: { + waybill_apply_subscription_info: { + cp_code: 'SF', + cp_name: '顺丰', + waybill_type: 'STANDARD', + branch_account_cols: { + waybill_branch_account: { + branch_name: '顺丰直营网点', + customer_code_list: { + string: 'CUST-003', + }, + service_info_dto: { + service_code: 'SPECIAL', + service_name: '特殊服务', + service_desc: '测试归一化', + required: true, + service_attribute_dto: [ + { + attribute_code: 'EXPRESS_TYPE', + attribute_name: '快递类型', + attribute_type: 'SELECT', + type_desc: '{"desc":{"1":"标准快递","2":"特惠专配"},"required":true,"type":"enum"}', + }, + { + attribute_code: 'PRODUCT_TYPE', + attribute_name: '产品类型', + attribute_type: 'SELECT', + type_desc: '{"T6":"特快","T7":"标快"}', + }, + ], + }, + }, + }, + }, + }, + }, + }, + }); + + const result = await service.getShopExpressList({ + shop_id: 20, + cp_code: 'SF', + }); + + assert.equal(result.flag, 'success'); + assert.deepEqual(result.data.list[0].accounts[0].services[0].attributes, [ + { + attribute_code: 'EXPRESS_TYPE', + attribute_name: '快递类型', + attribute_type: 'SELECT', + type_desc: '{"1":"标准快递","2":"特惠专配"}', + }, + { + attribute_code: 'PRODUCT_TYPE', + attribute_name: '产品类型', + attribute_type: 'SELECT', + type_desc: '{"T6":"特快","T7":"标快"}', + }, + ]); + }); + + it('getCainiaoStfTemplates 应直接查询公共模板列表且不依赖店铺上下文', async () => { + const { service, ctx, calls } = createHarness(); + let shopQueryCount = 0; + let stdTemplateRequestCount = 0; + let waybillSearchCallCount = 0; + + ctx.model.Shop.findAll = async () => { + shopQueryCount += 1; + return []; + }; + service.requestTbWaybillSearch = async () => { + waybillSearchCallCount += 1; + throw new Error('不应调用 cainiao.waybill.ii.search'); + }; + service.requestTbCainiaoStdTemplates = async () => { + stdTemplateRequestCount += 1; + + return { + cainiao_cloudprint_stdtemplates_get_response: { + result: { + datas: [ + { + cp_code: 'YTO', + brand_code: 'YTO', + success: true, + standard_templates: [ + { + standard_template_id: 'TPL-001', + standard_template_name: '圆通标准模板', + standard_template_url: 'https://example.com/tpl-001', + }, + { + standard_template_id: 'TPL-002', + standard_template_name: '圆通扩展模板', + standard_template_url: 'https://example.com/tpl-002', + }, + ], + }, + { + brand_code: 'ZTO', + success: false, + error_code: 'NO_TEMPLATE_PERMISSION', + error_message: '该快递公司暂未返回模板', + standard_templates: [], + }, + ], + }, + }, + }; + }; + + ctx.model.Express.findAll = async options => { + calls.expressFindAll += 1; + calls.expressFindAllPayload = options; + return [ + { + code: 'YTO', + CAINIAO: 'YTO', + }, + ]; + }; + + const result = await service.getCainiaoStfTemplates({ + express_code: 'yto', + }); + + assert.equal(shopQueryCount, 0); + assert.equal(stdTemplateRequestCount, 1); + assert.equal(waybillSearchCallCount, 0); + assert.equal(calls.expressFindAll, 1); + assert.deepEqual(calls.expressFindAllPayload.where, { + CAINIAO: 'YTO', + }); + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.deepEqual(result.data, { + platform_code: 'CAINIAO', + express_code: 'YTO', + responseData: { + cainiao_cloudprint_stdtemplates_get_response: { + result: { + datas: [ + { + cp_code: 'YTO', + brand_code: 'YTO', + success: true, + standard_templates: [ + { + standard_template_id: 'TPL-001', + standard_template_name: '圆通标准模板', + standard_template_url: 'https://example.com/tpl-001', + }, + { + standard_template_id: 'TPL-002', + standard_template_name: '圆通扩展模板', + standard_template_url: 'https://example.com/tpl-002', + }, + ], + }, + ], + }, + }, + }, + }); + }); + + it('getCainiaoStfTemplates 在缓存命中时不应请求淘宝公共模板接口', async () => { + const { service, calls } = createHarness(); + const cachedResponseData = { + cainiao_cloudprint_stdtemplates_get_response: { + result: { + datas: [ + { + cp_code: 'YTO', + standard_templates: [], + }, + { + cp_code: 'ZTO', + standard_templates: [], + }, + ], + }, + }, + }; + let stdTemplateRequestCount = 0; + + service.app.getCacheAsync = async key => { + calls.getCacheAsync += 1; + calls.getCacheAsyncPayload = key; + return cachedResponseData; + }; + service.requestTbCainiaoStdTemplates = async () => { + stdTemplateRequestCount += 1; + throw new Error('命中缓存时不应发起淘宝请求'); + }; + + service.ctx.model.Express.findAll = async options => { + calls.expressFindAll += 1; + calls.expressFindAllPayload = options; + return [ + { + code: 'YTO', + CAINIAO: 'YTO', + }, + ]; + }; + + const result = await service.getCainiaoStfTemplates({ + express_code: 'YTO', + }); + + assert.equal(calls.getCacheAsync, 1); + assert.equal(calls.getCacheAsyncPayload, 'index:cainiao:stfTemplates:responseData'); + assert.equal(stdTemplateRequestCount, 0); + assert.equal(calls.expressFindAll, 1); + assert.equal(calls.setCacheAsync, 0); + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.deepEqual(result.data, { + platform_code: 'CAINIAO', + express_code: 'YTO', + responseData: { + cainiao_cloudprint_stdtemplates_get_response: { + result: { + datas: [ + { + cp_code: 'YTO', + standard_templates: [], + }, + ], + }, + }, + }, + }); + }); + + it('getCainiaoStfTemplates 在缓存未命中时应请求淘宝并写入 1 小时缓存', async () => { + const { service, calls } = createHarness(); + const responseData = { + cainiao_cloudprint_stdtemplates_get_response: { + result: { + datas: [ + { + cp_code: 'STO', + standard_templates: [ + { + standard_template_id: 'TPL-100', + }, + ], + }, + ], + }, + }, + }; + let stdTemplateRequestCount = 0; + + service.requestTbCainiaoStdTemplates = async () => { + stdTemplateRequestCount += 1; + return responseData; + }; + + service.ctx.model.Express.findAll = async options => { + calls.expressFindAll += 1; + calls.expressFindAllPayload = options; + return [ + { + code: 'STO', + CAINIAO: 'STO', + }, + ]; + }; + + const result = await service.getCainiaoStfTemplates({ + express_code: 'STO', + }); + + assert.equal(calls.getCacheAsync, 1); + assert.equal(calls.getCacheAsyncPayload, 'index:cainiao:stfTemplates:responseData'); + assert.equal(stdTemplateRequestCount, 1); + assert.equal(calls.expressFindAll, 1); + assert.equal(calls.setCacheAsync, 1); + assert.deepEqual(calls.setCacheAsyncPayload, { + key: 'index:cainiao:stfTemplates:responseData', + value: responseData, + ttl: 3600, + }); + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.deepEqual(result.data, { + platform_code: 'CAINIAO', + express_code: 'STO', + responseData, + }); + }); + + it('getPrintPlatformTemplateList 应按入参平台编码与 express_code 过滤模板并写入对应缓存键', async () => { + const { service, calls } = createHarness(); + const responseData = { + cainiao_cloudprint_stdtemplates_get_response: { + result: { + datas: [ + { + cp_code: 'YTO', + standard_templates: [ + { + standard_template_id: 'TPL-YTO-1', + }, + ], + }, + { + cp_code: 'ZTO', + standard_templates: [ + { + standard_template_id: 'TPL-ZTO-1', + }, + ], + }, + ], + }, + }, + }; + + service.requestTbCainiaoStdTemplates = async () => responseData; + service.ctx.model.Express.findAll = async options => { + calls.expressFindAll += 1; + calls.expressFindAllPayload = options; + return [ + { + code: 'YTO', + CAINIAO: 'YTO', + }, + ]; + }; + + const result = await service.getPrintPlatformTemplateList({ + platform_code: 'cainiao', + express_code: 'yto', + }); + + assert.equal(calls.getCacheAsync, 1); + assert.equal(calls.getCacheAsyncPayload, 'index:cainiao:stfTemplates:responseData'); + assert.equal(calls.expressFindAll, 1); + assert.equal(calls.setCacheAsync, 1); + assert.deepEqual(calls.setCacheAsyncPayload, { + key: 'index:cainiao:stfTemplates:responseData', + value: responseData, + ttl: 3600, + }); + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.deepEqual(result.data, { + platform_code: 'CAINIAO', + express_code: 'YTO', + responseData: { + cainiao_cloudprint_stdtemplates_get_response: { + result: { + datas: [ + { + cp_code: 'YTO', + standard_templates: [ + { + standard_template_id: 'TPL-YTO-1', + }, + ], + }, + ], + }, + }, + }, + }); + }); + + it('getPrintPlatformTemplateList 应识别 standard_templates 子项中的 brand_code 并仅保留命中模板', async () => { + const { service, calls } = createHarness(); + const responseData = { + cainiao_cloudprint_stdtemplates_get_response: { + result: { + datas: [ + { + cp_code: 'SF', + standard_templates: [ + { + brand_code: 'SF', + standard_template_id: 'TPL-SF-TOP-1', + }, + { + brand_code: 'YTO', + standard_template_id: 'TPL-SF-TOP-2', + }, + ], + }, + { + cp_code: 'CAINIAO_COMMON', + standard_templates: { + standard_template_do: [ + { + brand_code: 'SF', + standard_template_id: 'TPL-SF-NESTED-1', + }, + { + brand_code: 'YTO', + standard_template_id: 'TPL-YTO-NESTED-1', + }, + ], + }, + }, + { + cp_code: 'YTO', + standard_templates: { + standard_template_do: [ + { + brand_code: 'YTO', + standard_template_id: 'TPL-YTO-ONLY-1', + }, + ], + }, + }, + ], + }, + }, + }; + + service.requestTbCainiaoStdTemplates = async () => responseData; + service.ctx.model.Express.findAll = async options => { + calls.expressFindAll += 1; + calls.expressFindAllPayload = options; + return [ + { + code: 'SF', + CAINIAO: 'SF', + }, + ]; + }; + + const result = await service.getPrintPlatformTemplateList({ + platform_code: 'CAINIAO', + express_code: 'sf', + }); + + assert.equal(calls.expressFindAll, 1); + assert.deepEqual(result.data, { + platform_code: 'CAINIAO', + express_code: 'SF', + responseData: { + cainiao_cloudprint_stdtemplates_get_response: { + result: { + datas: [ + { + cp_code: 'SF', + standard_templates: [ + { + brand_code: 'SF', + standard_template_id: 'TPL-SF-TOP-1', + }, + { + brand_code: 'YTO', + standard_template_id: 'TPL-SF-TOP-2', + }, + ], + }, + { + cp_code: 'CAINIAO_COMMON', + standard_templates: { + standard_template_do: [ + { + brand_code: 'SF', + standard_template_id: 'TPL-SF-NESTED-1', + }, + ], + }, + }, + ], + }, + }, + }, + }); + }); + + it('getPrintPlatformTemplateList 对未实现平台应返回空对象并按平台维度缓存', async () => { + const { service, calls } = createHarness(); + + const result = await service.getPrintPlatformTemplateList({ + platformCode: 'pdd', + express_code: 'SF', + }); + + assert.equal(calls.getCacheAsync, 1); + assert.equal(calls.getCacheAsyncPayload, 'index:printPlatform:PDD:templates:responseData'); + assert.equal(calls.setCacheAsync, 1); + assert.deepEqual(calls.setCacheAsyncPayload, { + key: 'index:printPlatform:PDD:templates:responseData', + value: {}, + ttl: 3600, + }); + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.deepEqual(result.data, { + platform_code: 'PDD', + express_code: 'SF', + responseData: {}, + }); + }); + + it('getPrintPlatformTemplateList 缺少 express_code 时应返回参数错误', async () => { + const { service, calls } = createHarness(); + + const result = await service.getPrintPlatformTemplateList({ + platform_code: 'cainiao', + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 400); + assert.equal(result.message, 'express_code 不能为空'); + assert.equal(calls.getCacheAsync, 0); + assert.equal(calls.setCacheAsync, 0); + }); + + it('getPlatformOauthLink 应以打印平台校验店铺平台码,并使用打印平台 OAuth 配置生成 CAINIAO 状态', async () => { + const { service, calls } = createHarness(); + + const result = await service.getPlatformOauthLink({ + platform_code: 'cainiao', + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(calls.printPlatformFindOne, 3); + assert.equal(calls.platformFindOne, 0); + assert.equal( + calls.printPlatformFindOneCalls.some(call => ( + Array.isArray(call && call.attributes) + && call.attributes.includes('auth_base_url') + )), + true + ); + assert.equal(calls.shopCreate, 1); + assert.equal(calls.shopCreatePayload.platform_code, 'CAINIAO'); + assert.equal(result.data.platform_code, 'CAINIAO'); + assert.match(String(result.data.oauth_link || ''), /CAINIAO_/); + }); + + it('getPlatformOauthLink 应从打印平台表读取 auth_base_url', async () => { + const { service, ctx, calls } = createHarness(); + + ctx.model.PrintPlatform.findOne = async options => { + calls.printPlatformFindOne += 1; + calls.printPlatformFindOnePayload = options; + calls.printPlatformFindOneCalls.push(options); + + if (!options || !options.attributes) { + return { + platform_code: 'PDD', + }; + } + + return { + platform_code: 'PDD', + auth_base_url: 'https://pdd.example.com/oauth?state=', + }; + }; + + const result = await service.getPlatformOauthLink({ + platform_code: 'PDD', + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(calls.platformFindOne, 0); + assert.match(String(result.data.oauth_link || ''), /^https:\/\/pdd\.example\.com\/oauth\?state=/); + }); + + it('getShopList 应携带打印平台名称并按打印平台编码过滤', async () => { + const { service, ctx } = createHarness(); + + ctx.model.Shop.findAll = async options => { + assert.equal(options.where.platform_code, 'CAINIAO'); + assert.equal(Array.isArray(options.include), true); + return [{ + get() { + return { + id: 101, + warehouse_id: 100000, + platform_code: 'CAINIAO', + shop_name: '菜鸟店铺A', + custom_name: '打印店铺A', + status: 1, + owner_id: 'owner-12345', + access_token: 'access-token', + refresh_token: 'refresh-token', + auth_random_code: 'auth-code', + printPlatform: { + platform_code: 'CAINIAO', + platform_name: '菜鸟电子面单', + }, + }; + }, + }]; + }; + + const result = await service.getShopList({ platform_code: 'cainiao' }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(result.data.list[0].platform_code, 'CAINIAO'); + assert.equal(result.data.list[0].platform_name, '菜鸟电子面单'); + }); + + it('requestTbCainiaoStdTemplates 应使用公共模板接口且不发送 session', async () => { + const { service, calls } = createHarness(); + + const result = await service.requestTbCainiaoStdTemplates(); + + assert.equal(calls.curl, 1); + assert.equal(calls.request.url, 'https://eco.taobao.com/router/rest'); + assert.equal(calls.request.options.method, 'POST'); + assert.equal(calls.request.options.contentType, 'form'); + assert.equal(calls.request.options.data.method, 'cainiao.cloudprint.stdtemplates.get'); + assert.equal(calls.request.options.data.sign, 'TB_SIGN'); + assert.equal(calls.tbSignParams.method, 'cainiao.cloudprint.stdtemplates.get'); + assert.equal(Object.prototype.hasOwnProperty.call(calls.tbSignParams, 'session'), false); + assert.equal(Object.prototype.hasOwnProperty.call(calls.request.options.data, 'session'), false); + assert.deepEqual(result, { + success: true, + code: 0, + }); + }); + + it('requestTbWaybillSearch 在 accessToken 缺失时不应发送 session 参数', async () => { + const { service, calls } = createHarness(); + + const result = await service.requestTbWaybillSearch({ + cpCode: '', + }); + + assert.equal(calls.curl, 1); + assert.equal(calls.request.url, 'https://eco.taobao.com/router/rest'); + assert.equal(calls.request.options.method, 'POST'); + assert.equal(calls.request.options.contentType, 'form'); + assert.equal(calls.request.options.data.sign, 'TB_SIGN'); + assert.equal(Object.prototype.hasOwnProperty.call(calls.tbSignParams, 'session'), false); + assert.equal(Object.prototype.hasOwnProperty.call(calls.request.options.data, 'session'), false); + assert.deepEqual(result, { + success: true, + code: 0, + }); + }); + + it('listenPlatformOauthBind 应委托平台 service 并返回监听结果', async () => { + const { service } = createHarness(); + let capturedData = null; + + service.service.systems.platform = { + async listenPlatformOauthBind(data) { + capturedData = data; + return { + success: true, + code: 200, + data: { + code: 'BIND001', + status: 'success', + access_token: 'ACCESS_TOKEN', + source: 'event', + }, + message: '授权完成', + }; + }, + }; + + const result = await service.listenPlatformOauthBind({ + business_code: 'BIND001', + long_poll: true, + }); + + assert.deepEqual(capturedData, { + code: 'BIND001', + longPoll: true, + timeoutMs: undefined, + }); + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(result.data.status, 'success'); + assert.equal(result.data.source, 'event'); + }); + + it('getPrintPlatformList 应返回打印平台全量列表', async () => { + const { service, calls } = createHarness(); + + const result = await service.getPrintPlatformList(); + + assert.equal(calls.getPrintPlatformList, 1); + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(Array.isArray(result.data), true); + assert.equal(result.data.length, 1); + assert.deepEqual(result.data[0], { + id: 1, + code: 'CAINIAO', + name: '菜鸟电子面单', + value: 'CAINIAO', + label: '菜鸟电子面单', + platform_code: 'CAINIAO', + platform_name: '菜鸟电子面单', + platid: '1001', + }); + }); +}); diff --git a/test/app/service/systemMethods/order/wave.batchList.assignmentStatus.test.js b/test/app/service/systemMethods/order/wave.batchList.assignmentStatus.test.js index 32106f1..785ec6b 100644 --- a/test/app/service/systemMethods/order/wave.batchList.assignmentStatus.test.js +++ b/test/app/service/systemMethods/order/wave.batchList.assignmentStatus.test.js @@ -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' }, diff --git a/test/app/service/systemMethods/setting/expressInterface.test.js b/test/app/service/systemMethods/setting/expressInterface.test.js index 9da9f95..c70efae 100644 --- a/test/app/service/systemMethods/setting/expressInterface.test.js +++ b/test/app/service/systemMethods/setting/expressInterface.test.js @@ -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', }, diff --git a/test/app/service/systemMethods/shops.test.js b/test/app/service/systemMethods/shops.test.js new file mode 100644 index 0000000..d2fd208 --- /dev/null +++ b/test/app/service/systemMethods/shops.test.js @@ -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', + }); + }); +}); diff --git a/test/app/service/systems/express.async_dispatch.test.js b/test/app/service/systems/express.async_dispatch.test.js index a5beb7f..3dd037e 100644 --- a/test/app/service/systems/express.async_dispatch.test.js +++ b/test/app/service/systems/express.async_dispatch.test.js @@ -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: { diff --git a/test/app/service/systems/express.createWaybillCode.balance.test.js b/test/app/service/systems/express.createWaybillCode.balance.test.js index 3e2dc4f..d50abbf 100644 --- a/test/app/service/systems/express.createWaybillCode.balance.test.js +++ b/test/app/service/systems/express.createWaybillCode.balance.test.js @@ -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'); + }); }); diff --git a/test/app/service/systems/express.createWaybillCodePipeline.matchExpressInterface.test.js b/test/app/service/systems/express.createWaybillCodePipeline.matchExpressInterface.test.js new file mode 100644 index 0000000..577962a --- /dev/null +++ b/test/app/service/systems/express.createWaybillCodePipeline.matchExpressInterface.test.js @@ -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'); + }); +}); diff --git a/test/app/service/systems/express.test.js b/test/app/service/systems/express.test.js index 4411e87..d20ddb3 100644 --- a/test/app/service/systems/express.test.js +++ b/test/app/service/systems/express.test.js @@ -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: [ diff --git a/test/app/service/systems/express_platform.cainiao.test.js b/test/app/service/systems/express_platform.cainiao.test.js new file mode 100644 index 0000000..622eb03 --- /dev/null +++ b/test/app/service/systems/express_platform.cainiao.test.js @@ -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()); + }, + /参数错误/ + ); + }); +}); diff --git a/test/app/service/systems/express_platform.pdd.ext_data.test.js b/test/app/service/systems/express_platform.pdd.ext_data.test.js new file mode 100644 index 0000000..c711c6d --- /dev/null +++ b/test/app/service/systems/express_platform.pdd.ext_data.test.js @@ -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); + }); +}); diff --git a/test/app/service/systems/order_print.getWavePlatformPrintData.test.js b/test/app/service/systems/order_print.getWavePlatformPrintData.test.js index d1beb00..cd2ea06 100644 --- a/test/app/service/systems/order_print.getWavePlatformPrintData.test.js +++ b/test/app/service/systems/order_print.getWavePlatformPrintData.test.js @@ -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'); + }); }); diff --git a/test/app/service/systems/platform.test.js b/test/app/service/systems/platform.test.js index 8ea6b49..f02a332 100644 --- a/test/app/service/systems/platform.test.js +++ b/test/app/service/systems/platform.test.js @@ -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' }, diff --git a/test/app/service/systems/setting/expressInterface.test.js b/test/app/service/systems/setting/expressInterface.test.js index 10aa213..acff587 100644 --- a/test/app/service/systems/setting/expressInterface.test.js +++ b/test/app/service/systems/setting/expressInterface.test.js @@ -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); diff --git a/test/app/service/systems/shops.test.js b/test/app/service/systems/shops.test.js new file mode 100644 index 0000000..f0f9b0c --- /dev/null +++ b/test/app/service/systems/shops.test.js @@ -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', + }); + }, /暂未实现授权会话换取能力/); + }); +}); diff --git a/test/app/service/systems/store_warehouse.listApiConfig.test.js b/test/app/service/systems/store_warehouse.listApiConfig.test.js index 2348d7a..c5005ce 100644 --- a/test/app/service/systems/store_warehouse.listApiConfig.test.js +++ b/test/app/service/systems/store_warehouse.listApiConfig.test.js @@ -129,4 +129,4 @@ describe('test/app/service/systems/store_warehouse.listApiConfig.test.js', () => app_key: [ 'qm-app-key-1' ], }); }); -}); \ No newline at end of file +});