From 150e2977d4b6625e23da8fdb29e0a598093757ae Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 22 May 2026 08:39:07 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=BF=AB=E9=80=92=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E9=85=8D=E7=BD=AE=EF=BC=8C=E6=8B=BC=E5=A4=9A=E5=A4=9A?= =?UTF-8?q?=E5=8F=96=E5=8F=B7=EF=BC=8C=E6=9C=AA=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controller/home.js | 323 +++++++ app/lib/pdd_client.js | 150 ++++ app/lib/pdd_sign.js | 188 ++++ app/lib/printer_data_builder.js | 4 +- app/model/express_interface.js | 7 +- app/model/platform.js | 5 + app/model/qimen_app.js | 18 +- app/model/shop.js | 137 +++ app/model/store_warehouse.js | 2 +- .../store_warehouse_print_quantity_log.js | 1 + app/router.js | 1 + app/service/systemMethods/index.js | 708 ++++++++++++++- .../systemMethods/order/pendingOrder.js | 32 + .../systemMethods/order/recheckOrder.js | 476 +++++++++- app/service/systemMethods/order/wave.js | 78 +- .../systemMethods/setting/expressInterface.js | 10 + .../systemMethods/storeWarehouse/store.js | 50 ++ app/service/systems/express.js | 35 +- app/service/systems/express_platform.js | 362 +++++++- app/service/systems/order_print.js | 115 ++- .../systems/order_storage_allocation.js | 2 +- .../systems/setting/expressInterface.js | 95 +- app/service/systems/store_warehouse.js | 209 ++++- app/service/systems/upload.js | 32 +- app/view/platform_oauth_callback.html | 147 ++++ check_brackets.js | 39 + config/config.default.js | 1 + .../20260519183000-create-wms-review-task.js | 2 +- ...90000-add-customer-id-to-wms-qimen-apps.js | 46 + ...0-add-ext-data-to-wms-express-interface.js | 46 + .../migrations/20260522103000-create-shops.js | 128 +++ ...10000-add-auth-base-url-to-wms_platform.js | 46 + ...000-add-auth-result-fields-to-wms-shops.js | 102 +++ ...0522133000-add-custom-name-to-wms-shops.js | 42 + methods/changes/2026.05.20-system-01.json | 11 +- methods/changes/2026.05.20-system-03.json | 18 + methods/changes/system.json | 104 +++ methods/system.json | 832 +++++++++++++++++- .../system.setting.storeWarehouse.test.js | 153 +++- .../controller/system.storeWarehouse.test.js | 2 +- test/app/lib/pdd_client.test.js | 92 ++ test/app/lib/pdd_sign.test.js | 46 + ...store_warehouse_print_quantity_log.test.js | 83 ++ test/app/service/systemMethods/index.test.js | 103 +++ .../pendingOrder.allocateExpressCode.test.js | 50 +- .../order/wave.batchAllocateExpress.test.js | 114 ++- .../setting/expressInterface.test.js | 12 + .../storeWarehouse/store.test.js | 106 +++ ...der_print.getWavePlatformPrintData.test.js | 101 ++- test/app/service/systems/platform.test.js | 87 ++ .../systems/setting/expressInterface.test.js | 49 ++ .../stock_store.exportWarehouseStock.test.js | 70 +- .../store_warehouse.listApiConfig.test.js | 132 +++ ...e_warehouse.queryPrintQuantityLogs.test.js | 196 +++++ .../store_warehouse.saveApiConfig.test.js | 261 ++++++ test/app/service/systems/upload.test.js | 21 + 56 files changed, 6038 insertions(+), 244 deletions(-) create mode 100644 app/lib/pdd_client.js create mode 100644 app/lib/pdd_sign.js create mode 100644 app/model/shop.js create mode 100644 app/view/platform_oauth_callback.html create mode 100644 check_brackets.js create mode 100644 database/migrations/20260521090000-add-customer-id-to-wms-qimen-apps.js create mode 100644 database/migrations/20260521113000-add-ext-data-to-wms-express-interface.js create mode 100644 database/migrations/20260522103000-create-shops.js create mode 100644 database/migrations/20260522110000-add-auth-base-url-to-wms_platform.js create mode 100644 database/migrations/20260522123000-add-auth-result-fields-to-wms-shops.js create mode 100644 database/migrations/20260522133000-add-custom-name-to-wms-shops.js create mode 100644 methods/changes/2026.05.20-system-03.json create mode 100644 test/app/lib/pdd_client.test.js create mode 100644 test/app/lib/pdd_sign.test.js create mode 100644 test/app/model/store_warehouse_print_quantity_log.test.js create mode 100644 test/app/service/systemMethods/index.test.js create mode 100644 test/app/service/systems/store_warehouse.listApiConfig.test.js create mode 100644 test/app/service/systems/store_warehouse.queryPrintQuantityLogs.test.js create mode 100644 test/app/service/systems/store_warehouse.saveApiConfig.test.js diff --git a/app/controller/home.js b/app/controller/home.js index 7ecb129..9cd7953 100644 --- a/app/controller/home.js +++ b/app/controller/home.js @@ -5,6 +5,93 @@ const { const { toSuccess, toFailure } = require('../lib/api_response'); class HomeController extends Controller { + /** + * 解析平台授权回调 state,提取平台编码与授权随机码。 + * @param {string} state 回调原始 state。 + * @param {string} reservationCodePrefix 配置的预留前缀。 + * @return {{normalizedState: string, platformCode: string, authRandomCode: string}|null} 解析结果,失败时返回 null。 + */ + parsePlatformOauthState(state, reservationCodePrefix) { + const normalizedState = reservationCodePrefix && state.startsWith(reservationCodePrefix) + ? state.slice(reservationCodePrefix.length) + : state; + const separatorIndex = normalizedState.indexOf('_'); + + if (separatorIndex <= 0 || separatorIndex === normalizedState.length - 1) { + return null; + } + + const platformCode = normalizedState.slice(0, separatorIndex).trim(); + const authRandomCode = normalizedState.slice(separatorIndex + 1).trim(); + + if (!platformCode || !authRandomCode) { + return null; + } + + return { + normalizedState, + platformCode, + authRandomCode, + }; + } + + /** + * 组装平台授权回调页面展示数据。 + * @param {object} payload 页面数据参数。 + * @param {string} payload.code 平台回调返回的授权码。 + * @param {string} payload.state 平台回调返回的原始 state。 + * @param {{normalizedState: string, platformCode: string, authRandomCode: string}|null} payload.parsedState 解析后的 state 数据。 + * @param {import('sequelize').Model|null} payload.shop 店铺记录。 + * @param {string} payload.errorMessage 预校验失败提示。 + * @return {object} 页面渲染数据。 + */ + buildPlatformOauthCallbackViewData({ code, state, parsedState, shop, errorMessage }) { + const platformCode = parsedState ? parsedState.platformCode : ''; + const authRandomCode = parsedState ? parsedState.authRandomCode : ''; + const normalizedState = parsedState ? parsedState.normalizedState : ''; + const hasShop = Boolean(shop); + const isProcessed = hasShop ? Number(shop.status) === 1 : null; + const isPlatformMatched = hasShop && parsedState + ? String(shop.platform_code || '') === platformCode + : null; + let resultLevel = 'error'; + let resultText = errorMessage || '授权回调校验失败'; + + if (!errorMessage && !hasShop) { + resultText = '预授权码不存在'; + } else if (!errorMessage && isPlatformMatched === false) { + resultText = '平台不匹配'; + } else if (!errorMessage && isProcessed === true) { + resultLevel = 'warning'; + resultText = '该预授权码已处理'; + } else if (!errorMessage && isProcessed === false && isPlatformMatched === true) { + resultLevel = 'success'; + resultText = '预授权码有效,平台匹配且尚未处理'; + } + + return { + title: '平台授权回调结果', + resultLevel, + resultText, + code, + state, + normalizedState, + platformCode, + authRandomCode, + isProcessed, + isProcessedText: hasShop + ? (isProcessed ? '是(已处理)' : '否(未处理)') + : '无法判断', + isPlatformMatched, + isPlatformMatchedText: hasShop + ? (isPlatformMatched ? '是' : '否') + : '无法判断', + shopPlatformCode: hasShop ? String(shop.platform_code || '') : '', + shopStatus: hasShop ? Number(shop.status) : null, + hasShop, + }; + } + async testSendData() { await this.ctx.service.systems.print.index.test(); this.ctx.body = 'ok'; @@ -16,6 +103,242 @@ class HomeController extends Controller { } = this; ctx.body = 'pong'; } + + /** + * 使用授权码请求拼多多开放平台换取授权结果,并返回结构化处理结果。 + * @param {string} code 平台回调返回的授权码。 + * @return {Promise<{success: boolean, message?: string, result: object|null}>} 请求处理结果。 + */ + async pdd(code) { + const pddConfig = this.app.config.pdd || {}; + + try { + const result = await this.ctx.curl('https://open-api.pinduoduo.com/oauth/token', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + dataType: 'json', + data: { + client_id: pddConfig.client_id || '', + code, + grant_type: 'authorization_code', + client_secret: pddConfig.client_secret || '', + }, + }); + + console.log(result); + + if (result && result.data && result.data.error_response) { + const errorMessage = result.data.error_response.error_msg || '未知错误'; + + return { + success: false, + message: `拼多多授权失败:${errorMessage}`, + result, + }; + } + + return { + success: true, + result, + }; + } catch (error) { + this.ctx.logger.error('[platform-oauth][PDD] oauth/token 请求异常: %s', error); + + return { + success: false, + message: `拼多多授权请求异常:${error.message}`, + result: null, + }; + } + } + + /** + * 构建拼多多授权店铺回写字段。 + * @param {object|null|undefined} oauthData 拼多多授权返回数据。 + * @return {object} 可直接用于店铺模型回写的字段对象。 + */ + buildPddOauthShopUpdatePayload(oauthData) { + const toDateFromUnixSeconds = value => { + const seconds = Number(value); + + if (!Number.isFinite(seconds) || seconds <= 0) { + return null; + } + + return new Date(seconds * 1000); + }; + const updatePayload = { + owner_id: oauthData && oauthData.owner_id !== undefined ? oauthData.owner_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: toDateFromUnixSeconds(oauthData && oauthData.expires_at), + refresh_token_expires_at: toDateFromUnixSeconds(oauthData && oauthData.refresh_token_expires_at), + auth_expire_at: toDateFromUnixSeconds(oauthData && oauthData.expires_at), + scope: oauthData && oauthData.scope !== undefined ? oauthData.scope : null, + status: 1, + }; + + if (oauthData && oauthData.owner_name) { + updatePayload.shop_name = oauthData.owner_name; + } + + return updatePayload; + } + + /** + * 按仓库、平台与授权标识查找已授权的旧店铺记录。 + * @param {import('sequelize').Model} shop 当前预申请店铺记录。 + * @param {object|null|undefined} oauthData 拼多多授权返回数据。 + * @param {import('sequelize').Transaction} transaction 当前事务对象。 + * @return {Promise} 命中的已授权店铺记录。 + */ + async findAuthorizedPddOauthShop(shop, oauthData, transaction) { + const { Op } = this.app.Sequelize; + 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() + : ''; + const matchConditions = []; + + if (ownerId) { + matchConditions.push({ owner_id: oauthData.owner_id }); + } + + if (ownerName) { + matchConditions.push({ shop_name: ownerName }); + } + + if (!matchConditions.length) { + return null; + } + + return await this.ctx.model.Shop.findOne({ + where: { + warehouse_id: shop.warehouse_id, + platform_code: shop.platform_code, + status: 1, + id: { + [Op.ne]: shop.id, + }, + [Op.or]: matchConditions, + }, + transaction, + }); + } + + /** + * 将拼多多授权成功后的关键字段回写到店铺记录。 + * @param {import('sequelize').Model} shop 店铺模型实例。 + * @param {object|null|undefined} oauthData 拼多多授权返回数据。 + * @return {Promise} 已保存的店铺模型实例。 + */ + async updatePddOauthShop(shop, oauthData) { + const updatePayload = this.buildPddOauthShopUpdatePayload(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.findAuthorizedPddOauthShop(shop, oauthData, 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} 无返回值。 + */ + async platformOauthCallback() { + const { + ctx, + app, + } = this; + const code = typeof ctx.query.code === 'string' ? ctx.query.code.trim() : ''; + const state = typeof ctx.query.state === 'string' ? ctx.query.state.trim() : ''; + const reservationCodePrefix = app.config.platformOauthReservationCodePrefix || ''; + const parsedState = state ? this.parsePlatformOauthState(state, reservationCodePrefix) : null; + let errorMessage = ''; + let shop = null; + + if (!code) { + errorMessage = 'code不能为空'; + } else if (!state) { + errorMessage = 'state不能为空'; + } else if (!parsedState) { + errorMessage = 'state解析失败'; + } else { + switch (parsedState.platformCode) { + case 'PDD': + { + const pddResult = await this.pdd(code); + + if (pddResult.success === false) { + errorMessage = pddResult.message; + break; + } + + shop = await ctx.model.Shop.findOne({ + where: { + auth_random_code: parsedState.authRandomCode, + }, + }); + + if (shop && String(shop.platform_code || '') === parsedState.platformCode) { + const oauthData = pddResult.result && pddResult.result.data + ? pddResult.result.data + : pddResult.result; + + shop = await this.updatePddOauthShop(shop, oauthData); + } + } + break; + default: + errorMessage = `暂未接入该平台授权回调处理`; + break; + } + } + + const viewData = this.buildPlatformOauthCallbackViewData({ + code, + state, + parsedState, + shop, + errorMessage, + }); + + ctx.status = viewData.resultLevel === 'error' ? 400 : 200; + await ctx.render('platform_oauth_callback.html', viewData); + } /** * 处理奇门统一入口请求,完成参数校验、XML 解析、仓库编码提取与方法分发。 * @return {Promise} 无返回值。 diff --git a/app/lib/pdd_client.js b/app/lib/pdd_client.js new file mode 100644 index 0000000..8f97fae --- /dev/null +++ b/app/lib/pdd_client.js @@ -0,0 +1,150 @@ +'use strict'; + +const pddSign = require('./pdd_sign'); + +const DEFAULT_BASE_URL = 'https://gw-api.pinduoduo.com/api/router'; + +/** + * 判断输入是否为普通对象。 + * @param {*} value 任意输入值。 + * @return {boolean} 是否为普通对象。 + */ +function isPlainObject(value) { + return Object.prototype.toString.call(value) === '[object Object]'; +} + +/** + * 获取当前秒级时间戳。 + * @return {string} 秒级 UNIX 时间戳。 + */ +function nowSec() { + return String(Math.floor(Date.now() / 1000)); +} + +/** + * 拼多多开放平台 API 客户端。 + * 负责组装请求体、生成签名、发送请求。 + */ +class PddClient { + /** + * @param {object} ctx - Egg 上下文对象。 + * @param {object} [options={}] - 客户端默认配置。 + */ + constructor(ctx, options = {}) { + this.ctx = ctx; + this.options = options; + } + + /** + * 解析客户端凭据。 + * @param {object} [options={}] 请求级配置。 + * @return {{ clientId: string, clientSecret: string }} 凭据。 + */ + resolveCredentials(options = {}) { + const config = (this.ctx && this.ctx.app && this.ctx.app.config && this.ctx.app.config.pdd) || {}; + + const clientId = options.clientId + ?? this.options.clientId + ?? config.client_id + ?? config.clientId + ?? ''; + const clientSecret = options.clientSecret + ?? this.options.clientSecret + ?? config.client_secret + ?? config.clientSecret + ?? ''; + + return { + clientId: String(clientId || '').trim(), + clientSecret: String(clientSecret || '').trim(), + }; + } + + /** + * 构建请求体。 + * @param {object} [options={}] 请求参数。 + * @return {{ requestBody: object, signText: string, sortedPairs: Array<[string, string]> }} 请求体和签名信息。 + */ + buildRequest(options = {}) { + const { + type, + bizParams = {}, + request = {}, + accessToken, + dataType = 'JSON', + version, + timestamp = nowSec(), + } = options; + + const { clientId, clientSecret } = this.resolveCredentials(options); + const payload = isPlainObject(bizParams) ? { ...bizParams } : {}; + if (isPlainObject(request)) { + Object.assign(payload, request); + } + + const signed = pddSign.buildRequestBody({ + type, + clientId, + timestamp, + dataType, + accessToken, + version, + bizParams: payload, + clientSecret, + }); + + return signed; + } + + /** + * 发起拼多多 API 请求。 + * @param {object} [options={}] 请求参数。 + * @return {Promise} 接口响应。 + */ + async request(options = {}) { + const { + baseUrl = DEFAULT_BASE_URL, + headers = {}, + timeout, + responseType = 'json', + } = options; + + if (!baseUrl) { + throw new Error('baseUrl 不能为空'); + } + + const { requestBody } = this.buildRequest(options); + const response = await this.ctx.curl(String(baseUrl), { + method: 'POST', + dataType: responseType, + timeout, + headers: { + 'Content-Type': 'application/json', + ...(headers || {}), + }, + data: requestBody, + }); + + return response && response.data !== undefined ? response.data : response; + } + + /** + * 同步调用接口,和 request 等价。 + * @param {object} [options={}] 请求参数。 + * @return {Promise} 接口响应。 + */ + async syncInvoke(options = {}) { + return this.request(options); + } + + /** + * 异步调用接口,和 request 等价。 + * @param {object} [options={}] 请求参数。 + * @return {Promise} 接口响应。 + */ + async asyncInvoke(options = {}) { + return this.request(options); + } +} + +module.exports = PddClient; \ No newline at end of file diff --git a/app/lib/pdd_sign.js b/app/lib/pdd_sign.js new file mode 100644 index 0000000..622e5da --- /dev/null +++ b/app/lib/pdd_sign.js @@ -0,0 +1,188 @@ +'use strict'; + +const crypto = require('node:crypto'); + +/** + * 判断输入是否为普通对象。 + * @param {*} value 任意输入值。 + * @return {boolean} 是否为普通对象。 + */ +function isPlainObject(value) { + return Object.prototype.toString.call(value) === '[object Object]'; +} + +/** + * 将对象按 key 排序后稳定序列化。 + * @param {*} value 待序列化值。 + * @return {string} 稳定序列化字符串。 + */ +function stableStringify(value) { + if (value === undefined) { + return 'null'; + } + + if (value === null || typeof value !== 'object') { + return JSON.stringify(value); + } + + if (Array.isArray(value)) { + return `[${value.map(item => stableStringify(item)).join(',')}]`; + } + + if (!isPlainObject(value)) { + return JSON.stringify(value); + } + + const keys = Object.keys(value) + .filter(key => value[key] !== undefined) + .sort(); + return `{${keys.map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`; +} + +/** + * 归一化参数值为可拼接字符串。 + * @param {*} value 参数值。 + * @return {string} 归一化后的字符串。 + */ +function normalizeValue(value) { + if (value === undefined || value === null) { + return ''; + } + + if (typeof value === 'object') { + return stableStringify(value); + } + + return String(value); +} + +/** + * 归一化密钥值。 + * @param {string} clientSecret 客户端密钥。 + * @return {string} 归一化后的密钥。 + */ +function normalizeSecret(clientSecret) { + return String(clientSecret || '').trim(); +} + +/** + * 归一化并排序请求参数。 + * @param {Object} [params={}] 请求参数。 + * @return {Array<[string, string]>} 排序后的键值对。 + */ +function buildSortedPairs(params = {}) { + if (!isPlainObject(params)) { + throw new Error('params 必须是对象'); + } + + return Object.keys(params) + .filter(key => params[key] !== undefined) + .sort() + .map(key => [ key, normalizeValue(params[key]) ]); +} + +/** + * 构建拼多多签名原文。 + * @param {Object} [params={}] 所有参与签名的参数。 + * @param {string} clientSecret 客户端密钥。 + * @return {{ signText: string, sortedPairs: Array<[string, string]> }} 签名原文与排序结果。 + */ +function buildSignText(params = {}, clientSecret) { + const secret = normalizeSecret(clientSecret); + if (!secret) { + throw new Error('clientSecret 不能为空'); + } + + const sortedPairs = buildSortedPairs(params); + const signText = secret + sortedPairs.map(([ key, value ]) => key + value).join('') + secret; + + return { + signText, + sortedPairs, + }; +} + +/** + * 生成拼多多 API 签名。 + * @param {Object} [params={}] 所有参与签名的参数。 + * @param {string} clientSecret 客户端密钥。 + * @return {{ sign: string, signText: string, sortedPairs: Array<[string, string]> }} 签名结果。 + */ +function sign(params = {}, clientSecret) { + const { signText, sortedPairs } = buildSignText(params, clientSecret); + + return { + signText, + sortedPairs, + sign: crypto.createHash('md5').update(signText, 'utf8').digest('hex').toUpperCase(), + }; +} + +/** + * 构建拼多多接口请求体,并自动补充 sign。 + * @param {Object} [options={}] 请求选项。 + * @param {string} options.type API 接口名。 + * @param {string|number} options.clientId 应用 client_id。 + * @param {string|number} options.timestamp UNIX 时间戳。 + * @param {string} [options.dataType='JSON'] 返回数据格式。 + * @param {string} [options.accessToken] 用户授权令牌。 + * @param {string} [options.version] API 版本。 + * @param {Object} [options.bizParams={}] 业务参数。 + * @param {string} options.clientSecret 客户端密钥。 + * @return {{ requestBody: Object, signText: string, sortedPairs: Array<[string, string]> }} 请求结果。 + */ +function buildRequestBody(options = {}) { + const { + type, + clientId, + timestamp, + dataType = 'JSON', + accessToken, + version, + bizParams = {}, + clientSecret, + } = options; + + const requestBody = { + ...(isPlainObject(bizParams) ? bizParams : {}), + type, + client_id: clientId, + timestamp, + data_type: dataType, + access_token: accessToken, + version, + }; + + Object.keys(requestBody).forEach(key => { + if (requestBody[key] === undefined || requestBody[key] === null || requestBody[key] === '') { + delete requestBody[key]; + } + }); + + // PDD 路由参数验签以字符串值为准,复杂参数需与签名使用同一序列化结果。 + Object.keys(requestBody).forEach(key => { + if (requestBody[key] && typeof requestBody[key] === 'object') { + requestBody[key] = normalizeValue(requestBody[key]); + } + }); + + const signed = sign(requestBody, clientSecret); + + return { + requestBody: { + ...requestBody, + sign: signed.sign, + }, + signText: signed.signText, + sortedPairs: signed.sortedPairs, + }; +} + +module.exports = { + buildRequestBody, + buildSignText, + normalizeSecret, + normalizeValue, + sign, + stableStringify, +}; \ No newline at end of file diff --git a/app/lib/printer_data_builder.js b/app/lib/printer_data_builder.js index bb55deb..b7487a6 100644 --- a/app/lib/printer_data_builder.js +++ b/app/lib/printer_data_builder.js @@ -954,7 +954,7 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde * 拼多多平台密文字段回填。 * * 规则: - * - wms_order_express.printinfo -> encryptedData + * - wms_order_express.encryptprintinfo -> encryptedData * - wms_order_express.signature -> signature * - policy_config 面单发货信息 -> content.addData.sender * @@ -982,7 +982,7 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli return; } - const encryptedData = toTrimmedString(safeOrderExpress.printinfo); + const encryptedData = toTrimmedString(safeOrderExpress.encryptprintinfo); const signature = toTrimmedString(safeOrderExpress.signature); const waybillCode = toTrimmedString(safeOrderExpress.waybill_code); const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; diff --git a/app/model/express_interface.js b/app/model/express_interface.js index 01c76f1..11de16e 100644 --- a/app/model/express_interface.js +++ b/app/model/express_interface.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = app => { - const { INTEGER, STRING, BIGINT, TINYINT } = app.Sequelize; + const { INTEGER, STRING, BIGINT, TINYINT, JSON } = app.Sequelize; const ExpressInterface = app.model.define('express_interface', { id: { @@ -139,6 +139,11 @@ module.exports = app => { allowNull: true, comment: '寄件网点编码', }, + ext_data: { + type: JSON, + allowNull: true, + comment: '扩展信息', + }, }, { tableName: 'wms_express_interface', freezeTableName: true, diff --git a/app/model/platform.js b/app/model/platform.js index 5b19330..9901334 100644 --- a/app/model/platform.js +++ b/app/model/platform.js @@ -70,6 +70,11 @@ module.exports = app => { allowNull: true, comment: '打印组件标识', }, + auth_base_url: { + type: STRING(255), + allowNull: true, + comment: '授权基础地址', + }, }, { tableName: 'wms_platform', freezeTableName: true, diff --git a/app/model/qimen_app.js b/app/model/qimen_app.js index 70164fb..57a85d3 100644 --- a/app/model/qimen_app.js +++ b/app/model/qimen_app.js @@ -1,5 +1,10 @@ 'use strict'; +/** + * 定义奇门应用配置模型。 + * @param {import('egg').Application} app Egg 应用实例 + * @return {import('sequelize').ModelCtor} 奇门应用配置模型 + */ module.exports = app => { const { INTEGER, STRING, DATE } = app.Sequelize; @@ -28,6 +33,14 @@ module.exports = app => { }, comment: '应用密钥', }, + customer_id: { + type: STRING(100), + allowNull: true, + validate: { + len: [ 0, 100 ], + }, + comment: '客户标识', + }, created_at: { type: DATE, allowNull: false, @@ -59,7 +72,10 @@ module.exports = app => { ], }); - // 定义实例方法 + /** + * 输出模型的 JSON 数据。 + * @return {object} 当前实例的普通对象数据 + */ QimenApp.prototype.toJSON = function() { const values = { ...this.get() }; return values; diff --git a/app/model/shop.js b/app/model/shop.js new file mode 100644 index 0000000..bb734ce --- /dev/null +++ b/app/model/shop.js @@ -0,0 +1,137 @@ +'use strict'; + +/** + * 店铺模型定义。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} 店铺模型。 + */ +module.exports = app => { + const { BIGINT, STRING, DATE, TINYINT, JSON } = app.Sequelize; + + const Shop = app.model.define('shops', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT.UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + platform_code: { + type: STRING(50), + allowNull: false, + comment: '平台编码', + }, + shop_name: { + type: STRING(100), + allowNull: false, + comment: '店铺名称', + }, + custom_name: { + type: STRING(100), + allowNull: true, + comment: '店铺自定义名称', + }, + status: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + validate: { + isIn: { + args: [[ 0, 1 ]], + msg: '状态值不合法,0=未授权,1=已授权', + }, + }, + comment: '授权状态:0=未授权,1=已授权', + }, + auth_expire_at: { + type: DATE, + allowNull: true, + comment: '授权到期时间', + }, + auth_random_code: { + type: STRING(128), + allowNull: true, + comment: '授权随机码', + }, + owner_id: { + type: STRING(64), + allowNull: true, + comment: '平台店铺/主体ID', + }, + access_token: { + type: STRING(255), + allowNull: true, + comment: '访问令牌', + }, + refresh_token: { + type: STRING(255), + allowNull: true, + comment: '刷新令牌', + }, + token_expires_at: { + type: DATE, + allowNull: true, + comment: '访问令牌过期时间', + }, + refresh_token_expires_at: { + type: DATE, + allowNull: true, + comment: '刷新令牌过期时间', + }, + scope: { + type: JSON, + allowNull: true, + comment: '授权范围', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + }, { + tableName: 'wms_shops', + freezeTableName: true, + underscored: true, + timestamps: true, + paranoid: false, + createdAt: 'created_at', + updatedAt: 'updated_at', + comment: '店铺表', + indexes: [ + { + name: 'idx_warehouse_id', + fields: [ 'warehouse_id' ], + }, + { + name: 'idx_platform_code', + fields: [ 'platform_code' ], + }, + { + name: 'idx_status', + fields: [ 'status' ], + }, + { + name: 'uk_warehouse_platform_shop_name', + unique: true, + fields: [ 'warehouse_id', 'platform_code', 'shop_name' ], + }, + { + name: 'uk_auth_random_code', + unique: true, + fields: [ 'auth_random_code' ], + }, + ], + }); + + return Shop; +}; \ No newline at end of file diff --git a/app/model/store_warehouse.js b/app/model/store_warehouse.js index 4e19170..379587f 100644 --- a/app/model/store_warehouse.js +++ b/app/model/store_warehouse.js @@ -4,7 +4,7 @@ module.exports = app => { const { BIGINT, TEXT, STRING, DATE, TINYINT, INTEGER, JSON: JSON_TYPE } = app.Sequelize; const POLICY_CONFIG_FIELDS = Object.freeze([ - + Object.freeze({ key: 'auto_allocate_bin', name: '自动分配库位', diff --git a/app/model/store_warehouse_print_quantity_log.js b/app/model/store_warehouse_print_quantity_log.js index 07f613c..4417657 100644 --- a/app/model/store_warehouse_print_quantity_log.js +++ b/app/model/store_warehouse_print_quantity_log.js @@ -100,6 +100,7 @@ module.exports = app => { freezeTableName: true, underscored: true, timestamps: true, + paranoid: false, createdAt: 'created_at', updatedAt: 'updated_at', comment: '货主-仓库签约面单余额变更记录表', diff --git a/app/router.js b/app/router.js index 6db78f4..f34f43d 100644 --- a/app/router.js +++ b/app/router.js @@ -4,6 +4,7 @@ module.exports = app => { const { router, controller } = app; router.get('/', controller.home.index); + router.get('/auth/platformOauthCallback', controller.home.platformOauthCallback); // 内部网关接口 router.post('/internal/v1/gateway', controller.gateway.internal); diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index d74ae59..2db0f2c 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -1,8 +1,204 @@ 'use strict'; -const { type } = require('os'); const MainService = require('../main'); const crypto = require('crypto'); +const PddClient = require('../../lib/pdd_client'); + +const DEFAULT_PDD_ROUTER_URL = 'https://gw-api.pinduoduo.com/api/router'; +const SHOP_MASK_PLACEHOLDER = `***`; + +/** + * 脱敏通用敏感文本。 + * + * @param {*} value 原始敏感值 + * @return {string|null} 脱敏后的值;原值为空时返回 null + */ +function maskSensitiveText(value) { + if (value === null || value === undefined || String(value).trim() === '') { + return null; + } + + return SHOP_MASK_PLACEHOLDER; +} + +/** + * 脱敏店铺归属人标识。 + * + * @param {*} ownerId 店铺归属人标识 + * @return {string|null} 脱敏后的归属人标识;原值为空时返回 null + */ +function maskShopOwnerId(ownerId) { + if (ownerId === null || ownerId === undefined || String(ownerId).trim() === '') { + return null; + } + + const ownerIdText = String(ownerId); + if (ownerIdText.length <= 5) { + return SHOP_MASK_PLACEHOLDER; + } + + return `${ownerIdText.slice(0, 3)}${SHOP_MASK_PLACEHOLDER}${ownerIdText.slice(-2)}`; +} + +/** + * 将店铺记录裁剪为安全的列表输出。 + * + * @param {Object} shopItem 店铺记录或模型实例 + * @return {Object} 脱敏后的店铺列表项 + */ +function maskShopListItem(shopItem) { + const plainItem = shopItem && typeof shopItem.get === 'function' + ? shopItem.get({ plain: true }) + : shopItem || {}; + + return { + id: plainItem.id, + warehouse_id: plainItem.warehouse_id, + platform_code: plainItem.platform_code, + shop_name: plainItem.shop_name, + custom_name: plainItem.custom_name, + status: plainItem.status, + auth_expire_at: plainItem.auth_expire_at, + token_expires_at: plainItem.token_expires_at, + refresh_token_expires_at: plainItem.refresh_token_expires_at, + scope: plainItem.scope, + created_at: plainItem.created_at, + updated_at: plainItem.updated_at, + owner_id: maskShopOwnerId(plainItem.owner_id), + access_token: maskSensitiveText(plainItem.access_token), + refresh_token: maskSensitiveText(plainItem.refresh_token), + auth_random_code: maskSensitiveText(plainItem.auth_random_code), + }; +} + +/** + * 将任意值标准化为空字符串。 + * + * @param {*} value 原始值 + * @return {string} 标准化后的字符串 + */ +function normalizeText(value) { + if (value === null || value === undefined) { + return ''; + } + + return String(value); +} + +/** + * 将任意值标准化为数组。 + * + * @param {*} value 原始值 + * @return {Array} 数组值;非数组时返回空数组 + */ +function normalizeArray(value) { + return Array.isArray(value) ? value : []; +} + +/** + * 根据平台编码构建平台侧快递编码到系统快递名称的映射。 + * + * @param {Array} expressList 系统快递列表 + * @param {string} platformCode 平台编码 + * @return {Object} 平台侧快递编码到系统快递名称的映射 + */ +function buildPlatformExpressNameMap(expressList, platformCode) { + const normalizedPlatformCode = String(platformCode || '').trim().toUpperCase(); + + if (!normalizedPlatformCode) { + return {}; + } + + return normalizeArray(expressList).reduce((result, expressItem) => { + const currentExpressItem = expressItem && typeof expressItem === 'object' ? expressItem : {}; + const platformExpressCode = normalizeText(currentExpressItem[normalizedPlatformCode]).trim(); + + if (!platformExpressCode) { + return result; + } + + result[platformExpressCode] = normalizeText(currentExpressItem.name); + return result; + }, {}); +} + +/** + * 解析拼多多电子面单网点查询响应,收敛为前端易消费的结构。 + * + * @param {*} responseData 拼多多原始响应 + * @param {Object} [expressNameMap={}] 平台快递编码到系统快递名称的映射 + * @return {Object} 解析后的电子面单网点结构 + */ +function formatPddWaybillSearchResponse(responseData, expressNameMap = {}) { + const waybillResponse = responseData && typeof responseData === 'object' + ? responseData.pdd_waybill_search_response || {} + : {}; + const subscriptions = normalizeArray(waybillResponse.waybill_apply_subscription_cols); + + const list = subscriptions.map(subscription => { + const subscriptionItem = subscription && typeof subscription === 'object' ? subscription : {}; + const accounts = normalizeArray(subscriptionItem.branch_account_cols).map(account => { + const accountItem = account && typeof account === 'object' ? account : {}; + const shipAddresses = normalizeArray(accountItem.shipp_address_cols).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), + detail: normalizeText(addressItem.detail), + full_address: normalizeText(addressItem.full_address), + }; + }); + const services = normalizeArray(accountItem.service_info_cols).map(service => { + const serviceItem = service && typeof service === 'object' ? service : {}; + const attributes = normalizeArray(serviceItem.service_attributes).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: normalizeText(attributeItem.type_desc), + }; + }); + + return { + service_code: normalizeText(serviceItem.service_code), + service_name: normalizeText(serviceItem.service_name), + service_desc: normalizeText(serviceItem.service_desc), + required: Boolean(serviceItem.required), + attributes, + }; + }); + + return { + branch_code: normalizeText(accountItem.branch_code), + 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, + ship_addresses: shipAddresses, + services, + }; + }); + + return { + wp_code: normalizeText(subscriptionItem.wp_code), + wp_name: normalizeText(expressNameMap[normalizeText(subscriptionItem.wp_code)]) || '', + wp_type: normalizeText(subscriptionItem.wp_type), + accounts, + }; + }); + + return { + request_id: normalizeText(waybillResponse.request_id), + total: subscriptions.length, + list, + }; +} class indexService extends MainService { /** @@ -12,10 +208,10 @@ class indexService extends MainService { */ constructor(ctx) { super(ctx); - const _noNeedLogin = 'getI18nMessage,putI18nCollect'; - const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate'; + 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 _noNeedLog = '*'; - const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate'; + const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPlatformOauthLink,recognizeLicensePlate,test'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } async fastWhereTree(data) { @@ -82,6 +278,129 @@ class indexService extends MainService { return this.success('ok', { data: result, code: 200 }); } + /** + * 后台专用的拼多多接口测试入口。 + * + * @param {Object} data 请求参数 + * @param {string} data.type 拼多多接口名,例如 pdd.order.number.list.get + * @param {Object} [data.bizParams] 业务参数对象 + * @param {Object} [data.request] 业务参数别名,兼容旧调用方式 + * @param {string} [data.accessToken] 用户授权令牌 + * @param {string} [data.dataType='JSON'] 响应格式 + * @param {string} [data.version] API 版本 + * @param {string|number} [data.timestamp] 时间戳 + * @param {string} [data.clientId] client_id 覆盖值 + * @param {string} [data.clientSecret] client_secret 覆盖值 + * @param {string} [data.baseUrl] 请求地址 + * @param {Object} [data.headers] 额外请求头 + * @param {number} [data.timeout] 请求超时 + * @return {Promise} 调用结果 + */ + async test(data = {}) { + const { ctx } = this; + const input = data && typeof data === 'object' ? data : {}; + const { + type, + access_token: accessTokenSnake, + accessToken, + data_type: dataTypeSnake, + dataType = 'JSON', + version, + timestamp, + client_id: clientIdSnake, + clientId, + client_secret: clientSecretSnake, + clientSecret, + base_url: baseUrlSnake, + baseUrl = DEFAULT_PDD_ROUTER_URL, + headers = {}, + timeout, + bizParams, + biz_params: bizParamsSnake, + request, + ...rest + } = input; + + if (!String(type || '').trim()) { + return this.fail('type 不能为空', { code: 400 }); + } + + const requestParams = {}; + if (rest && typeof rest === 'object' && !Array.isArray(rest)) { + Object.assign(requestParams, rest); + } + if (bizParams && typeof bizParams === 'object' && !Array.isArray(bizParams)) { + Object.assign(requestParams, bizParams); + } + if (request && typeof request === 'object' && !Array.isArray(request)) { + Object.assign(requestParams, request); + } + + const normalizedAccessToken = accessToken !== undefined ? accessToken : accessTokenSnake; + const normalizedDataType = dataTypeSnake !== undefined ? dataTypeSnake : dataType; + const normalizedClientId = clientId !== undefined ? clientId : clientIdSnake; + const normalizedClientSecret = clientSecret !== undefined ? clientSecret : clientSecretSnake; + const normalizedBaseUrl = baseUrlSnake !== undefined ? baseUrlSnake : baseUrl; + if (bizParamsSnake && typeof bizParamsSnake === 'object' && !Array.isArray(bizParamsSnake)) { + Object.assign(requestParams, bizParamsSnake); + } + + const pddClient = new PddClient(ctx); + const builtRequest = pddClient.buildRequest({ + type, + accessToken: normalizedAccessToken, + dataType: normalizedDataType, + version, + timestamp, + clientId: normalizedClientId, + clientSecret: normalizedClientSecret, + bizParams: requestParams, + }); + + try { + const response = await ctx.curl(String(normalizedBaseUrl || DEFAULT_PDD_ROUTER_URL), { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(headers && typeof headers === 'object' ? headers : {}), + }, + dataType: String(normalizedDataType || 'json').toLowerCase() === 'xml' ? 'text' : 'json', + data: builtRequest.requestBody, + timeout, + }); + + const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data') + ? response.data + : response; + const parsedResponse = type === 'pdd.waybill.search' + ? formatPddWaybillSearchResponse(responseData) + : null; + + return this.success('ok', { + data: { + requestBody: builtRequest.requestBody, + signText: builtRequest.signText, + sortedPairs: builtRequest.sortedPairs, + response: responseData, + parsed_response: parsedResponse, + baseUrl: String(normalizedBaseUrl || DEFAULT_PDD_ROUTER_URL), + }, + code: 200, + }); + } catch (error) { + ctx.logger.error('PDD 测试接口调用失败:', error); + return this.fail(error.message || 'PDD 测试接口调用失败', { + code: 500, + data: { + requestBody: builtRequest.requestBody, + signText: builtRequest.signText, + sortedPairs: builtRequest.sortedPairs, + baseUrl: String(normalizedBaseUrl || DEFAULT_PDD_ROUTER_URL), + }, + }); + } + } + // app/controller/i18n.js 中 async getI18nMessage(data) { const { ctx } = this; @@ -474,6 +793,37 @@ class indexService extends MainService { return this.success('ok', { list, total: list.length, code: 200 }); } + /** + * 获取奇门应用列表。 + * + * @return {Promise} 返回奇门应用列表结果 + */ + async getQimenAppList() { + const { ctx } = this; + const cacheKey = 'index:qimenAppList'; + const cached = await this.app.getCacheAsync(cacheKey); + + if (Array.isArray(cached)) { + return this.success('ok', { list: cached, total: cached.length, code: 200 }); + } + + const rows = await ctx.model.QimenApp.findAll({ + attributes: [ 'id', 'name', 'app_key' ], + order: [[ 'id', 'ASC' ]], + }); + const list = rows.map(row => { + const item = typeof row.get === 'function' ? row.get({ plain: true }) : row; + return { + id: Number(item.id || 0), + name: item.name || '', + app_key: item.app_key || '', + }; + }); + + await this.app.setCacheAsync(cacheKey, list, 300); + + return this.success('ok', { list, total: list.length, code: 200 }); + } /** * 获取快递列表。 * @@ -519,9 +869,357 @@ class indexService extends MainService { const result = await service.systems.platform.getPlatformList(isSystemOnly, isFull); return this.success('ok', { data: result, code: 200 }); } + + /** + * 获取当前仓库下的店铺列表。 + * + * @return {Promise} 返回店铺列表结果 + */ + async getShopList() { + const { ctx } = this; + const warehouseId = Number(ctx.user?.store_id); + + if (!warehouseId) { + return this.fail('未识别到当前仓库', { code: 400 }); + } + + const list = await ctx.model.Shop.findAll({ + where: { + warehouse_id: warehouseId, + status: 1, + }, + order: [[ 'status', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + }); + + const maskedList = list.map(maskShopListItem); + + return this.success('ok', { data: { list: maskedList }, code: 200 }); + } + + /** + * 实时请求拼多多电子面单网点列表。 + * + * @param {string} accessToken 店铺授权令牌 + * @return {Promise} 拼多多原始响应数据 + * @throws {Error} 拼多多返回错误结构或请求失败时抛出异常 + */ + async requestPddWaybillSearch(accessToken) { + const { ctx } = this; + const pddClient = new PddClient(ctx); + const builtRequest = pddClient.buildRequest({ + type: 'pdd.waybill.search', + accessToken, + dataType: 'JSON', + }); + const response = await ctx.curl(DEFAULT_PDD_ROUTER_URL, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + dataType: 'json', + data: builtRequest.requestBody, + }); + 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.error_msg || '拼多多电子面单查询失败'); + } + + return responseData; + } + + /** + * 获取指定店铺的快递签约列表。 + * + * @param {Object} data 请求参数 + * @param {string|number} [data.shop_id] 店铺 ID + * @param {string|number} [data.shopId] 店铺 ID,兼容驼峰字段 + * @return {Promise} 返回店铺对应的快递签约列表 + */ + async getShopExpressList(data = {}) { + const { ctx } = this; + const { shop_id: shopIdSnake, shopId: shopIdCamel } = data || {}; + const shopId = [ shopIdSnake, shopIdCamel ].find(item => item !== undefined && item !== null && String(item).trim() !== ''); + + if (shopId === undefined) { + return this.fail('shop_id 不能为空', { code: 400 }); + } + + const warehouseId = Number(ctx.user?.store_id); + + if (!warehouseId) { + return this.fail('未识别到当前仓库', { code: 400 }); + } + + const shop = await ctx.model.Shop.findOne({ + where: { + id: shopId, + warehouse_id: warehouseId, + }, + }); + + if (!shop) { + return this.fail('店铺不存在', { code: 404 }); + } + + const shopPlain = typeof shop.get === 'function' + ? shop.get({ plain: true }) + : shop; + const platformCode = String(shopPlain.platform_code || '').trim().toUpperCase(); + let list = []; + + switch (platformCode) { + case 'PDD': { + const accessToken = String(shopPlain.access_token || '').trim(); + + if (!accessToken) { + return this.fail('店铺未授权', { code: 400 }); + } + + const expressList = await this.service.systems.express.getExpressList(true); + const expressNameMap = buildPlatformExpressNameMap(expressList, platformCode); + const responseData = await this.requestPddWaybillSearch(accessToken); + const parsed = formatPddWaybillSearchResponse(responseData, expressNameMap); + + list = parsed.list; + break; + } + default: + list = []; + break; + } + + return this.success('ok', { + data: { + shop_id: shopPlain.id, + platform_code: platformCode, + list, + }, + code: 200, + }); + } + + /** + * 判断是否为店铺预占记录的唯一约束冲突。 + * + * @param {Error} error 异常对象 + * @return {boolean} 是否可重试的唯一约束冲突 + */ + isPlatformOauthReservationDuplicateError(error) { + if (!error || error.name !== 'SequelizeUniqueConstraintError') { + return false; + } + + const fields = Array.isArray(error.errors) ? error.errors.map(item => item && item.path).filter(Boolean) : []; + return fields.length === 0 || fields.includes('auth_random_code') || fields.includes('shop_name'); + } + + /** + * 获取平台授权预占码前缀配置。 + * + * @return {string} 授权预占码前缀 + */ + getPlatformOauthReservationCodePrefix() { + const { app } = this; + return String(app.config.platformOauthReservationCodePrefix || '').trim(); + } + + /** + * 判断授权预占码是否已带当前前缀。 + * + * @param {string} authRandomCode 授权预占码 + * @param {string} prefix 授权预占码前缀 + * @return {boolean} 是否已带前缀 + */ + hasPlatformOauthReservationCodePrefix(authRandomCode, prefix) { + if (!prefix) { + return true; + } + + return String(authRandomCode || '').startsWith(prefix); + } + + /** + * 规范化平台授权预占码。 + * + * @param {string} authRandomCode 授权预占码 + * @param {string} prefix 授权预占码前缀 + * @return {string} 去掉当前前缀后的裸码,若未带前缀则原样返回 + */ + normalizePlatformOauthReservationCode(authRandomCode, prefix) { + const normalizedCode = String(authRandomCode || '').trim(); + + if (!normalizedCode) { + return ''; + } + + if (prefix && this.hasPlatformOauthReservationCodePrefix(normalizedCode, prefix)) { + return normalizedCode.slice(prefix.length); + } + + return normalizedCode; + } + + /** + * 生成平台授权预占裸码。 + * + * @return {string} 新授权预占裸码 + */ + generatePlatformOauthReservationCode() { + return crypto.randomBytes(24).toString('hex'); + } + + /** + * 创建平台授权的店铺预占记录。 + * + * @param {Object} data 请求参数 + * @param {string|number} data.warehouseId 仓库 ID + * @param {string} data.platformCode 平台编码 + * @return {Promise<{ shop: Object, authRandomCode: string }>} 预占结果 + */ + async createPlatformOauthReservation(data) { + const { ctx } = this; + const { warehouseId, platformCode } = data; + const maxRetryCount = 5; + const prefix = this.getPlatformOauthReservationCodePrefix(); + + const shop = await ctx.model.Shop.findOne({ + where: { + warehouse_id: warehouseId, + platform_code: platformCode, + status: 0, + }, + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + }); + + if (shop) { + const storedAuthRandomCode = String(shop.auth_random_code || '').trim(); + if (storedAuthRandomCode) { + const authRandomCode = this.normalizePlatformOauthReservationCode(storedAuthRandomCode, prefix); + + if (authRandomCode !== storedAuthRandomCode) { + shop.auth_random_code = authRandomCode; + await shop.save(); + } + + return { + shop, + authRandomCode, + }; + } + } + + for (let retryIndex = 0; retryIndex < maxRetryCount; retryIndex++) { + const authRandomCode = this.generatePlatformOauthReservationCode(); + + try { + if (shop) { + shop.auth_random_code = authRandomCode; + await shop.save(); + + return { + shop, + authRandomCode, + }; + } + + const createdShop = await ctx.model.Shop.create({ + warehouse_id: warehouseId, + platform_code: platformCode, + shop_name: `PENDING_${authRandomCode}`, + status: 0, + auth_expire_at: null, + auth_random_code: authRandomCode, + }); + + return { + shop: createdShop, + authRandomCode, + }; + } catch (error) { + if (this.isPlatformOauthReservationDuplicateError(error) && retryIndex < maxRetryCount - 1) { + continue; + } + + if (this.isPlatformOauthReservationDuplicateError(error)) { + throw new Error('生成唯一授权码失败,请稍后重试'); + } + + throw error; + } + } + + throw new Error('生成唯一授权码失败,请稍后重试'); + } + + /** + * 获取平台授权链接。 + * + * @param {Object} data 请求参数 + * @param {string} [data.code] 平台编码 + * @param {string} [data.platform_code] 平台编码 + * @param {string} [data.platformCode] 平台编码 + * @return {Promise} 返回授权链接结果 + */ + async getPlatformOauthLink(data) { + const { ctx } = this; + const { + code = '', + platform_code: platformCodeSnake = '', + platformCode = '', + } = data || {}; + const platform_code = String(code || platformCodeSnake || platformCode || '').trim().toUpperCase(); + const warehouseId = String(ctx.user?.store_id ?? '').trim(); + + if (!platform_code) { + return this.fail('平台编码不能为空', { code: 400 }); + } + + if (!warehouseId) { + return this.fail('未识别到当前仓库', { code: 400 }); + } + + const platform = await ctx.model.Platform.findOne({ + where: { + code: platform_code, + }, + }); + + if (!platform) { + return this.fail('平台不存在', { code: 400 }); + } + + const authBaseUrl = String(platform.auth_base_url || '').trim(); + if (!authBaseUrl) { + return this.fail('平台授权基础地址未配置', { code: 400 }); + } + + let reservation; + try { + reservation = await this.createPlatformOauthReservation({ warehouseId, platformCode: platform_code }); + } catch (error) { + ctx.logger.error('创建平台授权预占记录失败:', error); + return this.fail(error.message || '创建平台授权预占记录失败', { code: 500 }); + } + + const prefix = this.getPlatformOauthReservationCodePrefix(); + const oauthLink = `${authBaseUrl}${encodeURIComponent(`${prefix}${platform_code}_${reservation.authRandomCode}`)}`; + + return this.success('ok', { + data: { + platform_code, + oauth_link: oauthLink, + }, + code: 200, + }); + } /** * 前端请求生成唯一的登录码,后续可以通过这个登录码在IM系统中完成登录状态的绑定。登录码只写入到缓存中,不存储在数据库,具有较短的过期时间(如5分钟),并且只能使用一次。 - * @param {*} data + * + * @return {Promise} 返回登录码及用户信息 */ async loginToIm() { const { ctx } = this; diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 48e02c6..779c59b 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -753,17 +753,49 @@ class PendingOrderService extends OrderBaseService { throw new Error('分配快递号接口仅支持订单对象数组入参'); } + const isBusinessIdOne = businessKey => { + const businessKeys = Array.isArray(businessKey) ? businessKey : [ businessKey ]; + return businessKeys.some(item => Number(item) === 1); + }; + const orderIds = [ ...new Set( orders .map(order => Number(order && (order.order_id || order.id))) .filter(orderId => Number.isFinite(orderId) && orderId > 0) ) ]; + const rollbackOrderIds = [ ...new Set( + orders + .filter(order => isBusinessIdOne(order && order.business_key)) + .map(order => Number(order && (order.order_id || order.id))) + .filter(orderId => Number.isFinite(orderId) && orderId > 0) + ) ]; const { service } = this; try { const result = await service.systems.express.createWaybillCodePipeline(orders); return this.success('ok', result); } catch (error) { + try { + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + const orderDeliveryModel = orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function' + ? await orderDeliveryFactory.getCurrentModel() + : null; + + if (rollbackOrderIds.length > 0) { + await this.service.systems.express.markWaybillAsyncOrdersAsError( + orderDeliveryModel, + rollbackOrderIds, + error && error.message ? `${error.message}` : `${error}` + ); + } else { + this.ctx.logger.info('[PendingOrderService.allocateExpressCode] 未命中 business_id=1 订单,跳过 post_status 失败回写', { + totalOrderCount: orderIds.length, + }); + } + } catch (markError) { + this.ctx.logger.warn('[PendingOrderService.allocateExpressCode] 通过统一 helper 回写订单失败状态失败,不影响主流程', markError); + } + try { const operationLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog; if (orderIds.length > 0 && operationLogService && typeof operationLogService.createOperationLogs === 'function') { diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index cad41a6..24bcfdd 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -10,24 +10,29 @@ class RecheckOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'scanWaybill,confirmRecheck'; - const _noNeedLog = 'scanWaybill,confirmRecheck'; - const _noNeedAuth = 'scanWaybill,confirmRecheck'; + const _noNeedRight = 'scanOrder,scanWaybill,confirmRecheck'; + const _noNeedLog = 'scanOrder,scanWaybill,confirmRecheck'; + const _noNeedAuth = 'scanOrder,scanWaybill,confirmRecheck'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } /** - * 扫描运单号并返回订单头与商品明细。 + * 扫描关键词并返回订单头与商品明细。 * @param {Object} data 请求体。 + * @param {string} [data.keyword] 通用扫描关键词。 + * @param {string} [data.value] 通用扫描关键词别名。 * @param {string} [data.waybill_no] 运单号。 * @param {string} [data.waybillCode] 运单号别名。 * @param {string} [data.waybill_code] 运单号别名。 + * @param {string} [data.cart_code] 车号。 + * @param {string} [data.cartCode] 车号别名。 * @return {Promise} 扫描结果。 */ - async scanWaybill(data = {}) { + async scanOrder(data = {}) { const warehouseId = this.getWarehouseId(); - const waybillNo = this.resolveWaybillNo(data); - const orderId = await this.pickOrderIdByWaybill(waybillNo); + const keyword = this.resolveScanKeyword(data); + const matchedResult = await this.pickOrderMatchByKeyword(keyword); + const { orderId, matchType, cartMatchContext } = matchedResult; const orderModel = await this.getOrderModelByTableType('current', warehouseId); const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); const order = await orderModel.findOne({ @@ -39,24 +44,40 @@ class RecheckOrderService extends OrderBaseService { throw new Error('未找到对应订单'); } - if (String(order.print_status || '') !== 'fin') { - throw new Error('运单状态必须已打印'); - } + this.assertOrderCanRecheck(order); const detailResult = await this.detail({ id: orderId, }); + const expresses = Array.isArray(detailResult.expresses) ? detailResult.expresses : []; + const resolvedWaybillNo = matchType === 'waybill' + ? keyword + : String(expresses?.[0]?.waybill_code || '').trim(); + const cartMatchView = matchType === 'cart' + ? await this.buildCartMatchView(cartMatchContext) + : null; return { + match_type: matchType, + cart_match_view: cartMatchView, order_id: orderId, - waybill_no: waybillNo, + waybill_no: resolvedWaybillNo, order: detailResult.detail || {}, items: Array.isArray(detailResult.items) ? detailResult.items : [], - expresses: Array.isArray(detailResult.expresses) ? detailResult.expresses : [], + expresses, logs: Array.isArray(detailResult.logs) ? detailResult.logs : [], }; } + /** + * 兼容旧方法名,内部统一转发到 scanOrder。 + * @param {Object} data 请求体。 + * @return {Promise} 扫描结果。 + */ + async scanWaybill(data = {}) { + return await this.scanOrder(data); + } + /** * 确认订单已复核,并写入复核任务记录。 * @param {Object} data 请求体。 @@ -80,9 +101,7 @@ class RecheckOrderService extends OrderBaseService { throw new Error('未找到对应订单'); } - if (String(order.print_status || '') !== 'fin') { - throw new Error('运单状态必须已打印'); - } + this.assertOrderCanRecheck(order); const expresses = await this.getOrderExpressesByOrderId(orderId); const waybillNo = String(expresses?.[0]?.waybill_code || '').trim(); @@ -195,37 +214,73 @@ class RecheckOrderService extends OrderBaseService { } /** - * 从多种兼容字段中解析运单号。 + * 从多种兼容字段中解析扫描关键词。 * @param {Object} data 请求体。 - * @return {string} 规范化后的运单号。 + * @return {string} 规范化后的扫描关键词。 */ - resolveWaybillNo(data = {}) { + resolveScanKeyword(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; const { + keyword, + value, waybill_no: waybillNo, waybillCode, waybill_code: waybillCodeAlias, + cart_code: cartCode, + cartCode: cartCodeAlias, } = requestData; - const normalizedWaybillNo = String(waybillNo || waybillCode || waybillCodeAlias || '').trim(); + const normalizedKeyword = String( + keyword || value || waybillNo || waybillCode || waybillCodeAlias || cartCode || cartCodeAlias || '' + ).trim(); - if (!normalizedWaybillNo) { - throw new Error('运单号不能为空'); + if (!normalizedKeyword) { + throw new Error('扫描关键词不能为空'); } - return normalizedWaybillNo; + return normalizedKeyword; + } + + /** + * 根据扫描关键词解析订单ID。 + * 优先按运单号匹配,未命中时回退到车号匹配。 + * @param {string} keyword 扫描关键词。 + * @return {Promise<{ orderId: number, matchType: string, cartMatchContext?: Object }>} 命中结果。 + */ + async pickOrderMatchByKeyword(keyword) { + const waybillOrderId = await this.pickOrderIdByWaybill(keyword); + + if (Number.isFinite(waybillOrderId) && waybillOrderId > 0) { + return { + orderId: waybillOrderId, + matchType: 'waybill', + }; + } + + const cartMatchContext = await this.pickCartMatchContextByCartCode(keyword); + const cartOrderId = Number(cartMatchContext?.order_id || 0); + + if (Number.isFinite(cartOrderId) && cartOrderId > 0) { + return { + orderId: cartOrderId, + matchType: 'cart', + cartMatchContext, + }; + } + + throw new Error('未找到对应订单'); } /** * 根据运单号解析唯一订单ID。 * @param {string} waybillNo 运单号。 - * @return {Promise} 订单ID。 + * @return {Promise} 订单ID,未命中返回 0。 */ async pickOrderIdByWaybill(waybillNo) { const warehouseId = this.getWarehouseId(); const orderIds = await this.findOrderIdsByExpressNumbers([ waybillNo ], warehouseId); if (!Array.isArray(orderIds) || orderIds.length === 0) { - throw new Error('未找到对应订单'); + return 0; } const normalizedOrderIds = orderIds @@ -234,12 +289,371 @@ class RecheckOrderService extends OrderBaseService { .sort((a, b) => a - b); if (normalizedOrderIds.length === 0) { - throw new Error('未找到对应订单'); + return 0; } return normalizedOrderIds[0]; } + /** + * 根据车号在波次拣货任务维度反查订单ID。 + * 匹配字段:任务主表当前车号快照与任务订单行车号快照。 + * @param {string} cartCode 车号。 + * @return {Promise} 订单ID,未命中返回 0。 + */ + async pickOrderIdByCartCode(cartCode) { + const cartMatchContext = await this.pickCartMatchContextByCartCode(cartCode); + const orderId = Number(cartMatchContext?.order_id || 0); + + return Number.isFinite(orderId) && orderId > 0 ? orderId : 0; + } + + /** + * 根据车号读取任务上下文及任务订单行。 + * @param {string} cartCode 车号。 + * @return {Promise<{order_id:number, task:Object, task_orders:Array, matched_order_ids:Array}>} 命中上下文。 + */ + async pickCartMatchContextByCartCode(cartCode) { + const { ctx } = this; + const warehouseId = this.getWarehouseId(); + const taskOrderColumnSet = await this.getTableColumnSet('wms_wave_pick_task_order'); + const taskRows = await ctx.model.query( + ` + SELECT + t.id AS task_id, + t.task_no, + t.pick_mode, + t.status, + t.review_status, + t.current_cart_code_snapshot + FROM wms_wave_pick_task t + WHERE t.warehouse_id = :warehouseId + AND ( + t.current_cart_code_snapshot = :cartCode + OR EXISTS ( + SELECT 1 + FROM wms_wave_pick_task_order pto + WHERE pto.task_id = t.id + AND pto.cart_code_snapshot = :cartCode + ) + ) + ORDER BY t.create_time DESC, t.id DESC + LIMIT 1 + `, + { + replacements: { + warehouseId, + cartCode, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const taskRow = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null; + const taskId = Number(taskRow && taskRow.task_id || 0); + if (!Number.isInteger(taskId) || taskId <= 0) { + return { + order_id: 0, + task: null, + task_orders: [], + matched_order_ids: [], + }; + } + + const pickStatusSelect = taskOrderColumnSet.has('pick_status') + ? 'pto.pick_status' + : 'NULL AS pick_status'; + const waveIdSelect = taskOrderColumnSet.has('wave_id') + ? 'pto.wave_id' + : 'NULL AS wave_id'; + const boxNoSelect = taskOrderColumnSet.has('box_no') + ? 'pto.box_no' + : 'NULL AS box_no'; + const cartCodeSnapshotSelect = taskOrderColumnSet.has('cart_code_snapshot') + ? 'pto.cart_code_snapshot' + : 'NULL AS cart_code_snapshot'; + const taskOrderWarehouseFilterSql = taskOrderColumnSet.has('warehouse_id') + ? ' AND pto.warehouse_id = :warehouseId' + : ''; + const taskOrderRowsRaw = await ctx.model.query( + ` + SELECT + pto.id AS task_order_id, + pto.order_id, + ${pickStatusSelect}, + ${waveIdSelect}, + ${boxNoSelect}, + ${cartCodeSnapshotSelect} + FROM wms_wave_pick_task_order pto + WHERE pto.task_id = :taskId + ${taskOrderWarehouseFilterSql} + ORDER BY pto.id ASC + `, + { + replacements: { + taskId, + warehouseId, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const task = { + task_id: Number(taskRow.task_id || 0), + task_no: String(taskRow.task_no || '').trim(), + pick_mode: Number(taskRow.pick_mode || 0), + status: Number(taskRow.status || 0), + review_status: Number(taskRow.review_status || 0), + current_cart_code_snapshot: String(taskRow.current_cart_code_snapshot || '').trim(), + }; + const taskOrderRows = (Array.isArray(taskOrderRowsRaw) ? taskOrderRowsRaw : []).map(row => ({ + task_order_id: Number(row && row.task_order_id || 0), + order_id: Number(row && row.order_id || 0), + pick_status: String(row && row.pick_status || '').trim(), + wave_id: Number(row && row.wave_id || 0), + box_no: Number(row && row.box_no || 0), + cart_code_snapshot: String(row && row.cart_code_snapshot || '').trim(), + })); + const matchedOrderIds = [ ...new Set(taskOrderRows + .map(row => Number(row && row.order_id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; + const primaryOrderId = Number(matchedOrderIds[0] || 0); + + return { + order_id: Number.isFinite(primaryOrderId) && primaryOrderId > 0 ? primaryOrderId : 0, + task, + task_orders: taskOrderRows, + matched_order_ids: matchedOrderIds, + }; + } + + /** + * 读取数据表字段集合。 + * @param {string} tableName 数据表名。 + * @return {Promise>} 字段名集合。 + */ + async getTableColumnSet(tableName) { + const { ctx } = this; + const normalizedTableName = String(tableName || '').trim(); + + if (!normalizedTableName) { + return new Set(); + } + + const escapedTableName = normalizedTableName.replace(/`/g, '``'); + + try { + const rows = await ctx.model.query(`SHOW COLUMNS FROM \`${escapedTableName}\``, { + type: ctx.model.QueryTypes.SELECT, + }); + + return new Set((Array.isArray(rows) ? rows : []) + .map(row => String(row && row.Field || '').trim()) + .filter(Boolean)); + } catch (error) { + ctx.logger.warn(`[recheckOrder.getTableColumnSet] 获取字段失败, table=${normalizedTableName}, error=${error.message}`); + return new Set(); + } + } + + /** + * 解析拣货模式名称。 + * @param {number|string} pickMode 拣货模式编码。 + * @return {string} 拣货模式名称。 + */ + resolvePickModeName(pickMode) { + const pickModeMap = { + 1: '团购小波次', + 2: '散单单品单件', + 3: '散单先拣后分', + 4: '边拣边分', + 5: '团购大波次', + }; + const normalizedPickMode = Number(pickMode || 0); + + return pickModeMap[normalizedPickMode] || '未知模式'; + } + + /** + * 构建车号命中语义化视图。 + * @param {Object} cartMatchContext 车号命中上下文。 + * @return {Promise} 语义化视图。 + */ + async buildCartMatchView(cartMatchContext = {}) { + const context = this.isPlainObject(cartMatchContext) ? cartMatchContext : {}; + const task = this.isPlainObject(context.task) ? context.task : {}; + const taskOrders = Array.isArray(context.task_orders) ? context.task_orders : []; + const pickMode = Number(task.pick_mode || 0); + const modeName = this.resolvePickModeName(pickMode); + const enrichedTaskOrders = await this.enrichTaskOrderRows(taskOrders); + const taskSummary = { + task_id: Number(task.task_id || 0), + task_no: String(task.task_no || '').trim(), + pick_mode: pickMode, + status: Number(task.status || 0), + review_status: Number(task.review_status || 0), + current_cart_code_snapshot: String(task.current_cart_code_snapshot || '').trim(), + order_count: enrichedTaskOrders.length, + }; + + const baseView = { + mode_code: pickMode, + mode_name: modeName, + view_type: 'orders', + task: taskSummary, + }; + + if ([ 1, 5 ].includes(pickMode)) { + return { + ...baseView, + view_type: 'groups', + groups: this.groupTaskOrdersByWaveId(enrichedTaskOrders), + }; + } + if (pickMode === 2) { + return { + ...baseView, + view_type: 'orders', + orders: enrichedTaskOrders, + }; + } + if (pickMode === 3) { + return { + ...baseView, + view_type: 'pick_groups', + pick_groups: this.groupTaskOrdersByPickStatus(enrichedTaskOrders), + }; + } + if (pickMode === 4) { + return { + ...baseView, + view_type: 'box_groups', + box_groups: this.groupTaskOrdersByBoxNo(enrichedTaskOrders), + }; + } + + return { + ...baseView, + view_type: 'orders', + orders: enrichedTaskOrders, + }; + } + + /** + * 追加任务订单行的订单维度字段。 + * @param {Array} taskOrders 任务订单行。 + * @return {Promise>} 扩展后的任务订单行。 + */ + async enrichTaskOrderRows(taskOrders = []) { + const warehouseId = this.getWarehouseId(); + const normalizedTaskOrders = Array.isArray(taskOrders) ? taskOrders : []; + const orderIds = [ ...new Set(normalizedTaskOrders + .map(row => Number(row && row.order_id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; + + if (orderIds.length === 0) { + return []; + } + + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderRows = await orderModel.findAll({ + where: this.buildOrderWhere(orderIds, warehouseId), + attributes: [ 'id', 'wave_id', 'pick_status' ], + raw: true, + }); + const orderMap = new Map((Array.isArray(orderRows) ? orderRows : []) + .map(row => [ + Number(row && row.id || 0), + { + wave_id: Number(row && row.wave_id || 0), + pick_status: String(row && row.pick_status || '').trim(), + }, + ]) + .filter(item => Number(item[0]) > 0)); + + return normalizedTaskOrders.map(row => { + const orderId = Number(row && row.order_id || 0); + const orderInfo = orderMap.get(orderId) || {}; + const waveId = Number(row && row.wave_id || 0) > 0 + ? Number(row && row.wave_id || 0) + : Number(orderInfo.wave_id || 0); + const pickStatus = String(row && row.pick_status || '').trim() || String(orderInfo.pick_status || '').trim() || 'unknown'; + + return { + task_order_id: Number(row && row.task_order_id || 0), + order_id: orderId, + wave_id: Number.isInteger(waveId) && waveId > 0 ? waveId : 0, + pick_status: pickStatus, + box_no: Number(row && row.box_no || 0), + cart_code_snapshot: String(row && row.cart_code_snapshot || '').trim(), + }; + }); + } + + /** + * 按 wave_id 分组。 + * @param {Array} taskOrders 任务订单行。 + * @return {Array} wave 分组结果。 + */ + groupTaskOrdersByWaveId(taskOrders = []) { + return this.groupTaskOrders(taskOrders, row => `wave_${Number(row && row.wave_id || 0)}`, row => ({ + wave_id: Number(row && row.wave_id || 0), + orders: [], + })); + } + + /** + * 按 pick_status 分组。 + * @param {Array} taskOrders 任务订单行。 + * @return {Array} pick_status 分组结果。 + */ + groupTaskOrdersByPickStatus(taskOrders = []) { + return this.groupTaskOrders(taskOrders, row => `pick_status_${String(row && row.pick_status || 'unknown').trim() || 'unknown'}`, row => ({ + pick_status: String(row && row.pick_status || 'unknown').trim() || 'unknown', + orders: [], + })); + } + + /** + * 按 box_no 分组。 + * @param {Array} taskOrders 任务订单行。 + * @return {Array} box_no 分组结果。 + */ + groupTaskOrdersByBoxNo(taskOrders = []) { + return this.groupTaskOrders(taskOrders, row => `box_${Number(row && row.box_no || 0)}`, row => ({ + box_no: Number(row && row.box_no || 0), + orders: [], + })); + } + + /** + * 通用任务订单分组。 + * @param {Array} taskOrders 任务订单行。 + * @param {Function} keyGetter 分组键生成器。 + * @param {Function} initGroup 分组初始化函数。 + * @return {Array} 分组列表。 + */ + groupTaskOrders(taskOrders = [], keyGetter, initGroup) { + const normalizedTaskOrders = Array.isArray(taskOrders) ? taskOrders : []; + const groupMap = new Map(); + + normalizedTaskOrders.forEach(row => { + const groupKey = String(keyGetter(row)); + + if (!groupMap.has(groupKey)) { + groupMap.set(groupKey, initGroup(row)); + } + + const group = groupMap.get(groupKey); + group.orders.push({ ...row }); + }); + + return Array.from(groupMap.values()).map(group => ({ + ...group, + order_count: Array.isArray(group.orders) ? group.orders.length : 0, + })); + } + /** * 生成复核单号。 * @param {number} orderId 订单ID。 @@ -252,6 +666,16 @@ class RecheckOrderService extends OrderBaseService { return `RC${timestamp}${paddedOrderId}`; } + + /** + * 校验订单是否允许复核,仅未拣货订单可执行复核。 + * @param {Object} order 订单信息。 + */ + assertOrderCanRecheck(order = {}) { + if (String(order.pick_status || '') !== 'none') { + throw new Error('订单未拣货,不允许复核。'); + } + } } -module.exports = RecheckOrderService; \ No newline at end of file +module.exports = RecheckOrderService; diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index a361ef8..27e3354 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -5493,7 +5493,7 @@ class WaveService extends OrderBaseService { waveType: 2, distinguishExpress: false, logisticsName: '', - itemSnapshotKey: 'manual_single_ids', + itemSnapshotKey: '混合订单', wavePrefix: singleFetchByIdsWavePrefix, transaction, }); @@ -7178,6 +7178,11 @@ class WaveService extends OrderBaseService { } const startTime = Date.now(); + let matchedOrderIds = []; + let matchedOrderCount = 0; + let orderModel = null; + let useBusinessKeyColumn = true; + let normalizedOrders = []; await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'running', { warehouse_id: warehouseId, wave_ids: waveIds.join(','), @@ -7197,7 +7202,7 @@ class WaveService extends OrderBaseService { }); try { - const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + orderModel = await this.getOrderModel('pendingOrder', warehouseId); const baseOrderWhere = { warehouse_id: warehouseId, wave_id: { @@ -7208,7 +7213,6 @@ class WaveService extends OrderBaseService { }, }; let orderRows = []; - let useBusinessKeyColumn = true; try { orderRows = await orderModel.findAll({ @@ -7243,20 +7247,22 @@ class WaveService extends OrderBaseService { matchedOrderCount: Array.isArray(orderRows) ? orderRows.length : 0, }); - const normalizedOrders = (Array.isArray(orderRows) ? orderRows : []) + normalizedOrders = (Array.isArray(orderRows) ? orderRows : []) .map(row => { const orderId = Number(row && row.id || 0); if (!Number.isInteger(orderId) || orderId <= 0) { return null; } - const businessKey = Number(useBusinessKeyColumn ? row && row.business_key : 1); + const businessKey = Number(useBusinessKeyColumn ? row && row.business_key : 0); return { order_id: orderId, - business_key: Number.isInteger(businessKey) && businessKey > 0 ? businessKey : 1, + business_key: Number.isInteger(businessKey) && businessKey > 0 ? businessKey : 0, }; }) .filter(Boolean); + matchedOrderIds = normalizedOrders.map(item => Number(item && item.order_id || 0)).filter(orderId => Number.isInteger(orderId) && orderId > 0); + matchedOrderCount = matchedOrderIds.length; if (normalizedOrders.length === 0) { this.ctx.logger.info('[wave.batchAllocateExpress] 未筛选到可分配快递号订单', { @@ -7334,6 +7340,57 @@ class WaveService extends OrderBaseService { trace_id: traceId, }); } catch (error) { + const durationMs = Date.now() - startTime; + const canIdentifyBusinessKey = useBusinessKeyColumn; + const rollbackOrderIds = canIdentifyBusinessKey + ? normalizedOrders + .filter(item => Number(item && item.business_key) === 1) + .map(item => Number(item && item.order_id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0) + : []; + if (!canIdentifyBusinessKey) { + this.ctx.logger.warn('[wave.batchAllocateExpress] business_key 列不可用,按强约束跳过 post_status 失败回写', { + traceId, + taskId: normalizedTaskId, + warehouseId, + waveIds, + matchedOrderCount, + }); + } else if (rollbackOrderIds.length === 0) { + this.ctx.logger.info('[wave.batchAllocateExpress] 未命中 business_id=1 订单,跳过 post_status 失败回写', { + traceId, + taskId: normalizedTaskId, + warehouseId, + waveIds, + matchedOrderCount, + }); + } + + if (rollbackOrderIds.length > 0 && orderModel && typeof orderModel.update === 'function') { + try { + await this.service.systems.express.markWaybillAsyncOrdersAsError( + orderModel, + rollbackOrderIds, + error && error.message ? `${error.message}` : `${error}`, + { + warehouse_id: warehouseId, + wave_id: { + [Op.in]: waveIds, + }, + } + ); + } catch (updateError) { + this.ctx.logger.warn('[wave.batchAllocateExpress] 通过统一 helper 回写订单失败状态失败', { + traceId, + taskId: normalizedTaskId, + warehouseId, + waveIds, + matchedOrderCount: rollbackOrderIds.length, + error: updateError && updateError.message ? updateError.message : `${updateError}`, + }); + } + } + this.ctx.logger.error('[wave.batchAllocateExpress] 后台任务执行失败', { traceId, taskId: normalizedTaskId, @@ -7344,9 +7401,14 @@ class WaveService extends OrderBaseService { }); await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'failed', { warehouse_id: warehouseId, - progress_percent: 0, + total_wave_count: waveIds.length, + total_order_count: matchedOrderCount, + processed_order_count: matchedOrderCount, + success_order_count: 0, + failed_order_count: matchedOrderCount, + progress_percent: 100, end_time: Date.now(), - duration_ms: Date.now() - startTime, + duration_ms: durationMs, error: error && error.message ? error.message : `${error}`, error_code: 'WAVE_BATCH_ALLOCATE_EXPRESS_FAILED', trace_id: traceId, diff --git a/app/service/systemMethods/setting/expressInterface.js b/app/service/systemMethods/setting/expressInterface.js index 4ea5a52..81b7c1c 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, + ext_data: extData, + extData: camelExtData, ...rest } = data || {}; @@ -187,6 +189,9 @@ class expressInterfaceService extends MainService { if (shipperNo !== undefined || camelShipperNo !== undefined) { payload.shipperno = shipperNo !== undefined ? shipperNo : camelShipperNo; } + if (extData !== undefined || camelExtData !== undefined) { + payload.ext_data = extData !== undefined ? extData : camelExtData; + } return await this.callSystemExpressInterface('create', payload, '创建快递接口失败'); } @@ -218,6 +223,8 @@ class expressInterfaceService extends MainService { isPickup: camelIsPickup, shipperno: shipperNo, shipperNo: camelShipperNo, + ext_data: extData, + extData: camelExtData, ...rest } = data || {}; @@ -253,6 +260,9 @@ class expressInterfaceService extends MainService { if (shipperNo !== undefined || camelShipperNo !== undefined) { payload.shipperno = shipperNo !== undefined ? shipperNo : camelShipperNo; } + if (extData !== undefined || camelExtData !== undefined) { + payload.ext_data = extData !== undefined ? extData : camelExtData; + } return await this.callSystemExpressInterface('update', payload, '更新快递接口失败'); } diff --git a/app/service/systemMethods/storeWarehouse/store.js b/app/service/systemMethods/storeWarehouse/store.js index 12394fd..f908d90 100644 --- a/app/service/systemMethods/storeWarehouse/store.js +++ b/app/service/systemMethods/storeWarehouse/store.js @@ -162,6 +162,56 @@ class StoreWarehouseStoreService extends MainService { } } + /** + * 查询面单余额变更日志(分页)。 + * + * @param {Object} data 请求数据。 + * @param {number|string} data.store_id 货主 ID。 + * @param {Object} [data.where] 筛选条件。 + * @param {Object} [data.pagination] 分页对象。 + * @param {number|string} [data.pagination.page] 页码。 + * @param {number|string} [data.pagination.page_size] 每页条数。 + * @return {Promise} 统一响应结果。 + */ + async queryPrintQuantityLogs(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.queryPrintQuantityLogs !== 'function') { + return this.fail('查询面单余额变更日志失败', { + code: 500, + }); + } + + try { + const requestData = normalizeStoreWarehousePayload(data); + const { where } = this.prepareWhereContext(requestData); + const { + store_id, + } = requestData; + const rawPagination = requestData.pagination && typeof requestData.pagination === 'object' + ? requestData.pagination + : {}; + const { + page, + page_size, + } = rawPagination; + + const result = await targetService.queryPrintQuantityLogs({ + store_id, + where, + pagination: { + page, + page_size, + }, + }); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '查询面单余额变更日志失败', { + code: Number(error.code) || 500, + }); + } + } + /** * 获取合约策略配置。 * diff --git a/app/service/systems/express.js b/app/service/systems/express.js index 72ce990..01219b3 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -646,9 +646,10 @@ class ExpressService extends Service { * @param {Object} orderDeliveryModel 订单主表模型。 * @param {Array} orderIds 订单ID 列表。 * @param {string} errorMessage 错误信息。 + * @param {Object} [extraWhere={}] 追加 where 约束,用于限制更新边界。 * @return {Promise} 无返回值。 */ - async markWaybillAsyncOrdersAsError(orderDeliveryModel, orderIds = [], errorMessage = '') { + async markWaybillAsyncOrdersAsError(orderDeliveryModel, orderIds = [], errorMessage = '', extraWhere = {}) { if (!orderDeliveryModel || typeof orderDeliveryModel.update !== 'function') { return; } @@ -663,17 +664,23 @@ class ExpressService extends Service { return; } + const normalizedExtraWhere = extraWhere && typeof extraWhere === 'object' && !Array.isArray(extraWhere) + ? { ...extraWhere } + : {}; + const where = { + ...normalizedExtraWhere, + id: { + [Op.in]: normalizedOrderIds, + }, + }; + await orderDeliveryModel.update({ post_status: 'error', step: 3, order_flag: normalizedErrorMessage, updated_at: new Date(), }, { - where: { - id: { - [Op.in]: normalizedOrderIds, - }, - }, + where, }); } @@ -1654,24 +1661,10 @@ class ExpressService extends Service { matchedPlatformCode: matchedPlatform && matchedPlatform.code, hasExpressInterface: Boolean(listByWarehousePlatformCode && listByWarehousePlatformCode.data && listByWarehousePlatformCode.data[0]), }); - // 先获取货主配置货主是否配置了发件人,如果没有再使用快递接口的发件人信息。发件人信息在 listByWarehousePlatformCode.data[0] 中。 - const storeInfo = await this.service.systems.storeWarehouse.getContractConfig(warehouseId, groupedOrder.options.store_id); const expressInterface = listByWarehousePlatformCode.data[0]; - const storeConfig = storeInfo ? storeInfo.policy_config : null; - const useStoreSenderInfoValue = storeConfig ? storeConfig.use_store_sender_info : 1; - const shouldUseStoreSenderInfo = Number(useStoreSenderInfoValue === undefined || useStoreSenderInfoValue === null || useStoreSenderInfoValue === '' ? 1 : useStoreSenderInfoValue) === 1; + // 发件人相关字段统一走接口配置,货主配置仅用于打印链路。 const expressInterfaceConfig = expressInterface ? { ...expressInterface, - ...(shouldUseStoreSenderInfo ? { - shop_name: (storeConfig && storeConfig.shop_name) || expressInterface.shop_name || '', - sender_name: (storeConfig && storeConfig.sender_name) || expressInterface.sender_name || '', - sender_tel: (storeConfig && storeConfig.sender_tel) || expressInterface.sender_tel || '', - province_name: (storeConfig && storeConfig.province_name) || expressInterface.province_name || '', - city_name: (storeConfig && storeConfig.city_name) || expressInterface.city_name || '', - district_name: (storeConfig && storeConfig.district_name) || expressInterface.district_name || '', - town_name: (storeConfig && storeConfig.town_name) || expressInterface.town_name || '', - address: (storeConfig && storeConfig.address) || expressInterface.address || '', - } : {}), } : null; for (const batch of batches) { // 异步不阻塞调用 createWaybillCode,快速返回结果给前端,后续的订单处理和异常回写都在 createWaybillCode 内部完成。 diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index 3383ff8..e851193 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -1,6 +1,9 @@ 'use strict'; const MainService = require('../main'); +const PddClient = require('../../lib/pdd_client'); + +const DEFAULT_PDD_ROUTER_URL = 'https://gw-api.pinduoduo.com/api/router'; /** * 快递平台服务类。 @@ -755,8 +758,363 @@ class ExpressPlatformService extends MainService { * @return {Promise} 当前暂未实现,直接抛出异常。 */ async pdd(data = {}) { - void data; - throw new Error('拼多多平台接口未实现'); + const { + matchedPlatform = {}, + listByWarehousePlatformCode = {}, + orders = [], + } = data && typeof data === 'object' ? data : {}; + const normalizedOrders = Array.isArray(orders) ? orders : []; + + console.log('拼多多平台接口入参', data); + + const tradeOrderList = normalizedOrders.map( + order_tmp => { + return { + logistics_services:listByWarehousePlatformCode.ext_data || "", + notify_extend_info: listByWarehousePlatformCode.ext_data || "", + 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 || ''], + }, + 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 || '', + }, + 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, + } + } + ) + //构建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, + }, + moblie:listByWarehousePlatformCode.sender_tel, + name:listByWarehousePlatformCode.sender_name, + phone:listByWarehousePlatformCode.sender_tel, + }, + trade_order_info_dtos:tradeOrderList, + wp_code:listByWarehousePlatformCode && listByWarehousePlatformCode.express + ? (listByWarehousePlatformCode.express.PDD || '') + : '', + } + }; + console.log('拼多多平台接口构建的请求参数', JSON.stringify(pddPayload, null, 2)); + // 这里写一个调用pdd_client的入参示例 + // + // + // + + const pddClient = new PddClient(this.ctx); + const { + type, + accessToken, + dataType, + timestamp, + ...requestParams + } = pddPayload; + const pddConfig = (this.ctx && this.ctx.app && this.ctx.app.config && this.ctx.app.config.pdd) || {}; + const configClientId = pddConfig.client_id || pddConfig.clientId; + const configClientSecret = pddConfig.client_secret || pddConfig.clientSecret; + console.log('拼多多签名凭据来源', { + clientId: configClientId || '(missing app.config.pdd.client_id)', + hasClientSecret: Boolean(configClientSecret), + source: 'app.config.pdd', + }); + const builtRequest = pddClient.buildRequest({ + type, + accessToken, + dataType, + timestamp, + clientId: configClientId, + clientSecret: configClientSecret, + bizParams: requestParams, + }); + + console.log('拼多多平台接口请求参数', JSON.stringify({ + baseUrl: DEFAULT_PDD_ROUTER_URL, + requestBody: builtRequest.requestBody, + signText: builtRequest.signText, + sortedPairs: builtRequest.sortedPairs, + }, null, 2)); + + try { + const response = await this.ctx.curl(DEFAULT_PDD_ROUTER_URL, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + dataType: String(pddPayload.dataType || 'JSON').toLowerCase() === 'xml' ? 'text' : 'json', + data: builtRequest.requestBody, + }); + + const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data') + ? response.data + : response; + console.log('拼多多平台接口返回参数', JSON.stringify(responseData, null, 2)); + + const errorResponse = responseData && responseData.error_response; + if (errorResponse) { + const errorMessage = String(errorResponse.sub_msg || errorResponse.error_msg || '拼多多平台接口调用失败').trim(); + throw new Error(errorMessage); + } + + const modules = responseData + && responseData.pdd_waybill_get_response + && Array.isArray(responseData.pdd_waybill_get_response.modules) + ? responseData.pdd_waybill_get_response.modules + : []; + + 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 => `${order.order_delivery.warehouse_id}_${order.order_delivery.id}_${order.business_key}`)); + 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'}`); + } + + const [ warehouseId, orderId, businessKey ] = objectId.split('_'); + const waybillCode = String(moduleItem && (moduleItem.parent_waybill_code || moduleItem.waybill_code) || '').trim(); + if (!waybillCode) { + throw new Error(`拼多多平台接口返回运单号为空: ${objectId}`); + } + + let parsedPrintData = null; + if (moduleItem && moduleItem.print_data) { + try { + parsedPrintData = JSON.parse(moduleItem.print_data); + } catch (parseError) { + throw new Error(`拼多多平台接口返回 print_data 解析失败: ${objectId}`); + } + } + + return { + warehouse_id: Number(warehouseId) || 0, + order_id: Number(orderId) || 0, + business_key: Number(businessKey) || 0, + waybill_code: waybillCode, + orderExpressValues: { + waybill_code: waybillCode, + signature: (parsedPrintData && parsedPrintData.signature) || String(moduleItem && moduleItem.signature || '').trim() || null, + encryptprintinfo: (parsedPrintData && parsedPrintData.encryptedData) || null, + 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: '', + }, + }; + }); + + const orderMetaMap = new Map(); + for (const order of normalizedOrders) { + const orderDelivery = order && 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, + }); + } + + const settlementRelationMap = new Map(); + for (const item of 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); + } + + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + if (typeof this.ctx.model.transaction === 'function' && successUpdates.length > 0) { + await this.ctx.model.transaction(async transaction => { + for (const item of successUpdates) { + 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 = successUpdates + .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); + } + + return { + flag: true, + code: 0, + message: '拼多多平台数据处理成功', + data: responseData, + }; + } catch (error) { + console.log('拼多多平台接口返回异常', error && error.message ? error.message : `${error}`); + throw error; + } } } diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index 91612dc..154ac47 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -55,6 +55,51 @@ class OrderPrintSystemService extends OrderBaseService { }; } + /** + * 组装单订单“已锁定”平台打印中间态结果(轻量对象)。 + * + * @param {Object} payload 聚合入参。 + * @param {Object} payload.orderRow 订单行。 + * @param {string} payload.platformCode 平台编码。 + * @return {Object} 锁定订单中间态。 + */ + buildLockedOrderPlatformPrintItem(payload = {}) { + const requestPayload = this.isPlainObject(payload) ? payload : {}; + const orderRow = this.isPlainObject(requestPayload.orderRow) ? requestPayload.orderRow : {}; + const platformCode = String(requestPayload.platformCode || '').trim(); + const normalizedPlatform = PrinterDataBuilder.normalizePlatformAlias(platformCode); + const orderId = Number(orderRow.id || 0); + + return { + wave_id: Number(orderRow.wave_id || 0), + wave_no: String(orderRow.wave_no || '').trim(), + order_id: orderId, + order_no: String(orderRow.delivery_order_code || orderRow.source_order_codes || '').trim(), + store_id: Number(orderRow.store_id || 0), + warehouse_id: Number(orderRow.warehouse_id || 0), + platform: platformCode, + platform_name: normalizedPlatform.meta && normalizedPlatform.meta.name + ? String(normalizedPlatform.meta.name).trim() + : '', + sys_logistics_code: String(orderRow.sys_logistics_code || '').trim(), + sys_logistics_name: String(orderRow.sys_logistics_name || '').trim(), + waybill_code: '', + print_data: { + order_id: orderId, + order_no: String(orderRow.delivery_order_code || orderRow.source_order_codes || '').trim(), + wave_id: Number(orderRow.wave_id || 0), + wave_no: String(orderRow.wave_no || '').trim(), + platform: platformCode, + platform_name: normalizedPlatform.meta && normalizedPlatform.meta.name + ? String(normalizedPlatform.meta.name).trim() + : '', + status: 'locked', + status_text: '已锁定', + print_lock_status: String(orderRow.print_lock_status || '').trim() || 'none', + }, + }; + } + /** * 判断当前配置是否需要补查拣货明细。 * @@ -397,9 +442,14 @@ class OrderPrintSystemService extends OrderBaseService { total_waves: 0, total_orders: 0, total_platforms: 0, + locked_count: 0, + total_locked_orders: 0, }, waveGroups: [], + locked_wave_groups: [], wave_ids: [], + locked_count: 0, + locked_orders: [], ext: { missing_wave_ids: normalizedWaveIds, filtered_wave_ids: [], @@ -417,43 +467,53 @@ class OrderPrintSystemService extends OrderBaseService { } = this.filterFullyAssignedExpressWaves(hitWaveIds, orderRows); const validWaveIdSet = new Set(validWaveIds); const validOrderRows = orderRows.filter(order => validWaveIdSet.has(Number(order && order.wave_id || 0))); - const lockedOrders = validOrderRows - .filter(orderRow => this.isOrderLocked(orderRow)) + const lockedOrderRows = validOrderRows.filter(orderRow => this.isOrderLocked(orderRow)); + const unlockedOrderRows = validOrderRows.filter(orderRow => !this.isOrderLocked(orderRow)); + const lockedOrders = lockedOrderRows .map(orderRow => ({ order_id: Number(orderRow && orderRow.id || 0), order_no: String(orderRow && (orderRow.delivery_order_code || orderRow.source_order_codes) || '').trim(), wave_id: Number(orderRow && orderRow.wave_id || 0), wave_no: String(orderRow && orderRow.wave_no || '').trim(), print_lock_status: String(orderRow && orderRow.print_lock_status || '').trim() || 'none', + status: 'locked', + status_text: '已锁定', })); - if (lockedOrders.length > 0) { - return this.buildLockedWavePlatformResult({ - lockedOrders, - validWaveIds, - missingWaveIds, - filteredWaveIds, - }); - } - const validOrderWaveIds = Array.from(new Set(validOrderRows + const lockedWaveIds = Array.from(new Set(lockedOrderRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0))); + const lockedOrderPrintList = lockedOrderRows.map(orderRow => { + const platformCode = this.resolvePrintPlatformCode(orderRow, {}); + return this.buildLockedOrderPlatformPrintItem({ + orderRow, + platformCode, + }); + }); + const lockedWaveGroups = this.groupOrderPrintItemsByWaveAndPlatform({ + waveRows, + hitWaveIds: lockedWaveIds, + orderPrintList: lockedOrderPrintList, + }); + + const validOrderWaveIds = Array.from(new Set(unlockedOrderRows .map(row => Number(row && row.wave_id || 0)) .filter(waveId => Number.isInteger(waveId) && waveId > 0))); - if (validOrderRows.length === 0) { - const waveGroups = this.groupOrderPrintItemsByWaveAndPlatform({ - waveRows, - hitWaveIds: validWaveIds, - orderPrintList: [], - }); - + if (unlockedOrderRows.length === 0) { return { summary: { - total_waves: waveGroups.length, + total_waves: 0, total_orders: 0, total_platforms: 0, + locked_count: lockedOrders.length, + total_locked_orders: lockedOrders.length, }, - waveGroups, + waveGroups: [], + locked_wave_groups: lockedWaveGroups, wave_ids: validWaveIds, + locked_count: lockedOrders.length, + locked_orders: lockedOrders, ext: { missing_wave_ids: missingWaveIds, filtered_wave_ids: filteredWaveIds, @@ -461,14 +521,14 @@ class OrderPrintSystemService extends OrderBaseService { }; } - const orderIds = validOrderRows + const orderIds = unlockedOrderRows .map(row => Number(row && row.id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0); const orderExpressRows = await this.queryOrderExpressByOrderIds(orderIds); this.assertBusinessWaybillCompleteness(orderIds, orderExpressRows); const orderExpressMap = this.buildOrderExpressMap(orderExpressRows); - const policyConfigMap = await this.getPolicyConfigMapByStore(validOrderRows, normalizedWarehouseId); - const pickingCandidateRows = validOrderRows.filter(orderRow => { + const policyConfigMap = await this.getPolicyConfigMapByStore(unlockedOrderRows, normalizedWarehouseId); + const pickingCandidateRows = unlockedOrderRows.filter(orderRow => { const storeId = Number(orderRow && orderRow.store_id || 0); const policyConfig = policyConfigMap.get(storeId) || {}; return this.shouldLoadPickingDetails(policyConfig); @@ -484,7 +544,7 @@ class OrderPrintSystemService extends OrderBaseService { const templateSampleCache = new Map(); const orderPrintList = []; - for (const orderRow of validOrderRows) { + for (const orderRow of unlockedOrderRows) { const orderId = Number(orderRow && orderRow.id || 0); if (!Number.isInteger(orderId) || orderId <= 0) { continue; @@ -519,7 +579,7 @@ class OrderPrintSystemService extends OrderBaseService { const waveGroups = this.groupOrderPrintItemsByWaveAndPlatform({ waveRows, - hitWaveIds: validWaveIds, + hitWaveIds: validOrderWaveIds, orderPrintList, }); const totalPlatforms = waveGroups.reduce((sum, waveGroup) => { @@ -531,9 +591,14 @@ class OrderPrintSystemService extends OrderBaseService { total_waves: waveGroups.length, total_orders: orderPrintList.length, total_platforms: totalPlatforms, + locked_count: lockedOrders.length, + total_locked_orders: lockedOrders.length, }, waveGroups, + locked_wave_groups: lockedWaveGroups, wave_ids: validWaveIds, + locked_count: lockedOrders.length, + locked_orders: lockedOrders, ext: { missing_wave_ids: missingWaveIds, filtered_wave_ids: filteredWaveIds, diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index 14bb9fd..17f688c 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -1392,7 +1392,7 @@ class OrderStorageAllocationService extends MainService { async syncOrderIds(data = {}) { const { ctx } = this; const unallocatedPostStatus = 'none'; - const fastFailReason = `快递状态未分配,禁止同步`; + const fastFailReason = '快递状态未分配,禁止同步'; const requestData = data && typeof data === 'object' ? data : {}; const normalizeNumber = (value, defaultValue = 0) => { const numericValue = Number(value); diff --git a/app/service/systems/setting/expressInterface.js b/app/service/systems/setting/expressInterface.js index 6ae5ae6..0c60b34 100644 --- a/app/service/systems/setting/expressInterface.js +++ b/app/service/systems/setting/expressInterface.js @@ -138,6 +138,34 @@ class SettingExpressInterfaceService extends Service { return normalized; } + /** + * 规范化可选 JSON 值。 + * + * @param {*} value 原始值 + * @param {string} fieldName 字段名称 + * @return {*|null} 规范化后的 JSON 值 + */ + normalizeOptionalJson(value, fieldName) { + if (value === undefined || value === null || value === '') { + return null; + } + + if (typeof value === 'string') { + const normalized = value.trim(); + if (!normalized) { + return null; + } + + try { + return this.clonePlainValue(JSON.parse(normalized)); + } catch (error) { + throw this.createError(`${fieldName} 必须是合法 JSON`, 400); + } + } + + return this.clonePlainValue(value); + } + /** * 规范化整数值。 * @@ -499,14 +527,12 @@ class SettingExpressInterfaceService extends Service { sender_tel: this.normalizeOptionalText(row.sender_tel, 'sender_tel', 11), weight: row.weight === undefined || row.weight === null ? null : Number(row.weight), weight_type: row.weight_type === undefined || row.weight_type === null ? null : Number(row.weight_type), - token: this.normalizeOptionalText(row.token, 'token', 500), viewer: this.normalizeOptionalText(row.viewer, 'viewer', 50), client_id: this.normalizeOptionalText(row.client_id, 'client_id', 50), 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), - share_id: row.share_id === undefined || row.share_id === null ? null : Number(row.share_id), shipperno: this.normalizeOptionalText(row.shipperno, 'shipperno', 255), - can_use_count: row.can_use_count === undefined || row.can_use_count === null ? null : Number(row.can_use_count), + 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), district_name: this.normalizeOptionalText(row.district_name, 'district_name', 255), @@ -794,9 +820,9 @@ class SettingExpressInterfaceService extends Service { attributes: [ 'id', 'name', 'express_code', 'warehouse_id', 'platform_code', 'sys_express_code', - 'sender_name', 'sender_tel', 'weight', 'token', 'viewer', 'client_id', 'is_share', - 'share_id', 'can_use_count', 'province_name', 'city_name', 'district_name', 'site_code', - 'product_type', 'weight_type', 'shop_name', 'address', 'town_name', 'ispickup', 'shipperno', + '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', ], order: [[ 'id', 'DESC' ]], offset, @@ -932,20 +958,11 @@ class SettingExpressInterfaceService extends Service { weight_type: this.normalizeInteger(data.weight_type !== undefined ? data.weight_type : data.weightType, 'weight_type', { allowEmpty: true, }), - token: this.normalizeOptionalText(data.token, 'token', 500), viewer: this.normalizeOptionalText(data.viewer, 'viewer', 50), client_id: this.normalizeOptionalText(data.client_id || data.clientId, 'client_id', 50), - is_share: this.normalizeFlag(data.is_share !== undefined ? data.is_share : data.isShare, 'is_share', 0), ispickup: this.normalizeFlag(data.ispickup !== undefined ? data.ispickup : data.isPickup, 'ispickup', 0), - share_id: this.normalizeInteger(data.share_id || data.shareId, 'share_id', { - allowEmpty: true, - min: 1, - }), shipperno: this.normalizeOptionalText(data.shipperno !== undefined ? data.shipperno : data.shipperNo, 'shipperno', 255), - can_use_count: this.normalizeInteger(data.can_use_count !== undefined ? data.can_use_count : data.canUseCount, 'can_use_count', { - allowEmpty: true, - min: 0, - }), + 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), district_name: this.normalizeOptionalText(data.district_name || data.districtName, 'district_name', 255), @@ -1000,20 +1017,13 @@ 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 hasToken = Object.prototype.hasOwnProperty.call(data, 'token'); const hasViewer = Object.prototype.hasOwnProperty.call(data, 'viewer'); const hasClientId = Object.prototype.hasOwnProperty.call(data, 'client_id') || Object.prototype.hasOwnProperty.call(data, 'clientId'); - const hasIsShare = Object.prototype.hasOwnProperty.call(data, 'is_share') - || Object.prototype.hasOwnProperty.call(data, 'isShare'); - const hasShareId = Object.prototype.hasOwnProperty.call(data, 'share_id') - || Object.prototype.hasOwnProperty.call(data, 'shareId'); const hasIsPickup = Object.prototype.hasOwnProperty.call(data, 'ispickup') || Object.prototype.hasOwnProperty.call(data, 'isPickup'); const hasShipperNo = Object.prototype.hasOwnProperty.call(data, 'shipperno') || Object.prototype.hasOwnProperty.call(data, 'shipperNo'); - const hasCanUseCount = Object.prototype.hasOwnProperty.call(data, 'can_use_count') - || Object.prototype.hasOwnProperty.call(data, 'canUseCount'); const hasProvinceName = Object.prototype.hasOwnProperty.call(data, 'province_name') || Object.prototype.hasOwnProperty.call(data, 'provinceName'); const hasCityName = Object.prototype.hasOwnProperty.call(data, 'city_name') @@ -1029,13 +1039,15 @@ class SettingExpressInterfaceService extends Service { || Object.prototype.hasOwnProperty.call(data, 'productType'); const hasShopName = Object.prototype.hasOwnProperty.call(data, 'shop_name') || Object.prototype.hasOwnProperty.call(data, 'shopName'); + const hasExtData = Object.prototype.hasOwnProperty.call(data, 'ext_data') + || Object.prototype.hasOwnProperty.call(data, 'extData'); if (!hasName && !hasExpressCode && !hasPlatformCode && !hasSysExpressCode - && !hasSenderName && !hasSenderTel && !hasWeight && !hasWeightType && !hasToken - && !hasViewer && !hasClientId && !hasIsShare && !hasShareId && !hasIsPickup - && !hasShipperNo && !hasCanUseCount && !hasProvinceName && !hasCityName + && !hasSenderName && !hasSenderTel && !hasWeight && !hasWeightType + && !hasViewer && !hasClientId && !hasIsPickup + && !hasShipperNo && !hasProvinceName && !hasCityName && !hasDistrictName && !hasAddress && !hasTownName && !hasSiteCode - && !hasProductType && !hasShopName) { + && !hasProductType && !hasShopName && !hasExtData) { throw this.createError('至少需要提供一个可更新字段', 400); } @@ -1089,10 +1101,6 @@ class SettingExpressInterfaceService extends Service { }); } - if (hasToken) { - updates.token = this.normalizeOptionalText(data.token, 'token', 500); - } - if (hasViewer) { updates.viewer = this.normalizeOptionalText(data.viewer, 'viewer', 50); } @@ -1101,17 +1109,6 @@ class SettingExpressInterfaceService extends Service { updates.client_id = this.normalizeOptionalText(data.client_id || data.clientId, 'client_id', 50); } - if (hasIsShare) { - updates.is_share = this.normalizeFlag(data.is_share !== undefined ? data.is_share : data.isShare, 'is_share', 0); - } - - if (hasShareId) { - updates.share_id = this.normalizeInteger(data.share_id || data.shareId, 'share_id', { - allowEmpty: true, - min: 1, - }); - } - if (hasIsPickup) { updates.ispickup = this.normalizeFlag(data.ispickup !== undefined ? data.ispickup : data.isPickup, 'ispickup', 0); } @@ -1120,13 +1117,6 @@ class SettingExpressInterfaceService extends Service { updates.shipperno = this.normalizeOptionalText(data.shipperno !== undefined ? data.shipperno : data.shipperNo, 'shipperno', 255); } - if (hasCanUseCount) { - updates.can_use_count = this.normalizeInteger(data.can_use_count !== undefined ? data.can_use_count : data.canUseCount, 'can_use_count', { - allowEmpty: true, - min: 0, - }); - } - if (hasProvinceName) { updates.province_name = this.normalizeOptionalText(data.province_name || data.provinceName, 'province_name', 255); } @@ -1159,6 +1149,13 @@ class SettingExpressInterfaceService extends Service { updates.shop_name = this.normalizeOptionalText(data.shop_name || data.shopName, 'shop_name', 255); } + if (hasExtData) { + updates.ext_data = this.normalizeOptionalJson( + data.ext_data !== undefined ? data.ext_data : data.extData, + 'ext_data' + ); + } + if (hasExpressCode || hasPlatformCode || hasSysExpressCode) { updates.sys_express_code = await this.resolveSysExpressCode({ expressCode: nextExpressCode, diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index be35a72..a2b794e 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -2,6 +2,7 @@ const crypto = require('node:crypto'); const Service = require('egg').Service; +const { Op } = require('sequelize'); const SIGN_TEMP_EXPIRE_SECONDS = 600; const AUTH_STATUS_LABELS = Object.freeze({ @@ -1040,6 +1041,79 @@ class SettingStoreWarehouseService extends Service { return this.getApiInterfaceType(data, options); } + /** + * 根据奇门 AppKey 解析客户标识。 + * + * @param {string|null} qimenAppKey 奇门应用 AppKey。 + * @param {Object} [options={}] 查询选项。 + * @param {Object|null} [options.transaction=null] 事务对象。 + * @return {Promise} 命中的客户标识;未传 AppKey 时返回 null。 + * @throws {Error} 当 AppKey 不存在或未配置 customer_id 时抛出,状态码为 400。 + */ + async resolveQimenCustomerIdByAppKey(qimenAppKey, options = {}) { + const { ctx } = this; + const { transaction = null } = options; + const normalizedAppKey = this.normalizeText(qimenAppKey, 'qimen_app_key', 100); + if (!normalizedAppKey) { + return null; + } + + const qimenApp = await ctx.model.QimenApp.findOne({ + where: { + app_key: normalizedAppKey, + }, + attributes: [ 'id', 'app_key', 'customer_id' ], + transaction, + }); + + if (!qimenApp) { + throw this.createError('未找到与 qimen_app_key 对应的奇门应用配置', 400); + } + + const customerId = this.normalizeText(qimenApp.customer_id, 'customer_id', 100); + if (!customerId) { + throw this.createError('对应的奇门应用未配置 customer_id,无法保存接口配置', 400); + } + + return customerId; + } + + /** + * 根据奇门 AppKey 列表查询 ERP 名称映射。 + * + * @param {Array} appKeys 奇门 AppKey 列表。 + * @param {Object} [options={}] 查询选项。 + * @param {Object|null} [options.transaction=null] 事务对象。 + * @return {Promise>} AppKey 到 ERP 名称的映射。 + */ + async getQimenErpNameMapByAppKeys(appKeys = [], options = {}) { + const { ctx } = this; + const { transaction = null } = options; + const normalizedAppKeys = [ ...new Set( + appKeys + .map(value => this.normalizeText(value, 'qimen_app_key', 100, { allowEmpty: true })) + .filter(Boolean) + ) ]; + + if (!normalizedAppKeys.length) { + return new Map(); + } + + const rows = await ctx.model.QimenApp.findAll({ + where: { + app_key: normalizedAppKeys, + }, + attributes: [ 'app_key', 'name' ], + raw: true, + transaction, + }); + + return new Map(rows.map(item => [ + String(item.app_key || ''), + String(item.name || ''), + ])); + } + /** * 序列化奇门配置。 * @@ -1062,6 +1136,7 @@ class SettingStoreWarehouseService extends Service { interface_code: interfaceType.interface_code || item.interface_code || '', interface_name: interfaceType.interface_name || item.interface_name || '', interface_category: interfaceType.interface_category || item.interface_category || '', + erp_name: item.erp_name || item.erpName || '', contract_id: Number(item.contract_id || 0), warehouse_id: item.warehouse_id ? Number(item.warehouse_id) : null, app_name: item.app_name || '', @@ -1717,6 +1792,102 @@ class SettingStoreWarehouseService extends Service { } } + /** + * 按货主查询面单余额变更日志(分页)。 + * + * @param {Object} [data={}] 请求参数。 + * @param {number|string} data.store_id 货主 ID。 + * @param {Object} [data.where] 动态筛选条件。 + * @param {Object} [data.pagination] 分页对象。 + * @param {number|string} [data.pagination.page] 页码。 + * @param {number|string} [data.pagination.page_size] 每页条数。 + * @return {Promise} 接口响应对象。 + */ + async queryPrintQuantityLogs(data = {}) { + const { ctx } = this; + const currentSubject = await this.getCurrentSubject(); + const storeId = this.toPositiveNumber(data.store_id, 'store_id'); + const pagination = data.pagination && typeof data.pagination === 'object' + ? data.pagination + : {}; + const page = this.normalizePage(pagination.page, 'page', 1, 1000000); + const pageSize = this.normalizePage(pagination.page_size, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + + if (!currentSubject.isWarehouse && Number(currentSubject.id) !== Number(storeId)) { + throw this.createError('仅可查询当前货主的面单余额变更日志', 403); + } + + const where = { + store_id: Number(storeId), + }; + + if (currentSubject.isWarehouse) { + where.warehouse_id = Number(currentSubject.id); + } + + const dynamicConditions = this.ctx.whereParsed && Array.isArray(this.ctx.whereParsed.dynamicConditions) + ? this.ctx.whereParsed.dynamicConditions.filter(Boolean) + : []; + + if (dynamicConditions.length > 0) { + where[Op.and] = dynamicConditions; + } + + const { rows, count } = await ctx.model.StoreWarehousePrintQuantityLog.findAndCountAll({ + where, + order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], + offset, + limit: pageSize, + }); + + const total = Number(count || 0); + const totalPages = total > 0 ? Math.ceil(total / pageSize) : 0; + + return { + code: 200, + data: { + list: rows.map(item => { + const payload = item && typeof item.get === 'function' + ? item.get({ plain: true }) + : (item || {}); + + return { + id: Number(payload.id || 0), + contract_id: Number(payload.contract_id || 0), + store_id: Number(payload.store_id || 0), + warehouse_id: Number(payload.warehouse_id || 0), + change_type: payload.change_type ? String(payload.change_type) : '', + business_type: payload.business_type ? String(payload.business_type) : null, + business_id: payload.business_id !== undefined && payload.business_id !== null + ? Number(payload.business_id) + : null, + change_quantity: Number(payload.change_quantity || 0), + balance_before: Number(payload.balance_before || 0), + balance_after: Number(payload.balance_after || 0), + reason: payload.reason || '', + operator_id: payload.operator_id !== undefined && payload.operator_id !== null + ? Number(payload.operator_id) + : null, + created_by: payload.created_by !== undefined && payload.created_by !== null + ? Number(payload.created_by) + : null, + created_at: payload.created_at || null, + updated_at: payload.updated_at || null, + }; + }), + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: totalPages > 0 && page < totalPages, + }, + }, + }; + } + /** * 获取策略配置字段。 * @@ -1854,7 +2025,34 @@ class SettingStoreWarehouseService extends Service { order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], }); - const list = rows.map(item => this.serializeQimenConfig(item)); + const qimenAppKeys = rows + .map(item => { + const plainItem = item && typeof item.get === 'function' + ? item.get({ plain: true }) + : item; + const interfaceCategory = plainItem?.interface_type?.interface_category || plainItem?.interface_category || ''; + if (interfaceCategory !== 'QM_WMS') { + return null; + } + return plainItem?.qimen_app_key || null; + }) + .filter(Boolean); + const qimenErpNameMap = await this.getQimenErpNameMapByAppKeys(qimenAppKeys); + + const list = rows.map(item => { + const plainItem = item && typeof item.get === 'function' + ? item.get({ plain: true }) + : item; + const interfaceCategory = plainItem?.interface_type?.interface_category || plainItem?.interface_category || ''; + const erpName = interfaceCategory === 'QM_WMS' + ? (qimenErpNameMap.get(String(plainItem?.qimen_app_key || '')) || '') + : ''; + + return this.serializeQimenConfig({ + ...plainItem, + erp_name: erpName, + }); + }); const primaryApiConfig = list.length ? list[0] : null; return { @@ -1896,10 +2094,7 @@ class SettingStoreWarehouseService extends Service { if (!qimenAppKey) { throw this.createError('奇门接口类型下 qimen_app_key 参数不能为空', 400); } - qimenCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100); - if (!qimenCustomerId) { - throw this.createError('奇门接口类型下 qimen_customer_id 参数不能为空', 400); - } + qimenCustomerId = await this.resolveQimenCustomerIdByAppKey(qimenAppKey, { transaction }); qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100); if (!qimenWarehouseCode) { throw this.createError('奇门接口类型下 qimen_warehouse_code 参数不能为空', 400); @@ -1907,7 +2102,9 @@ class SettingStoreWarehouseService extends Service { } else { // OPEN_API: 奇门字段可选输入 qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100) || null; - qimenCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100) || null; + qimenCustomerId = qimenAppKey + ? await this.resolveQimenCustomerIdByAppKey(qimenAppKey, { transaction }) + : null; qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100) || null; } diff --git a/app/service/systems/upload.js b/app/service/systems/upload.js index 188bf17..0dbf547 100644 --- a/app/service/systems/upload.js +++ b/app/service/systems/upload.js @@ -84,18 +84,36 @@ class UploadService extends Service { this.validateFileInfo({ fileName, fileSize }); const warehouse_quota = await this.app.model.query( - 'SELECT * FROM vw_warehouse_quota WHERE warehouse_id = :warehouseId', + `SELECT + s.id AS warehouse_id, + COALESCE(s.quota_bytes, 0) AS quota_bytes, + COALESCE(SUM(CASE WHEN f.is_deleted = 0 OR f.is_deleted IS NULL THEN f.file_size ELSE 0 END), 0) AS used_bytes, + GREATEST( + COALESCE(s.quota_bytes, 0) - COALESCE(SUM(CASE WHEN f.is_deleted = 0 OR f.is_deleted IS NULL THEN f.file_size ELSE 0 END), 0), + 0 + ) AS remaining_bytes + FROM wms_store s + LEFT JOIN wms_file f ON f.warehouse_id = s.id + WHERE s.id = :warehouseId + GROUP BY s.id, s.quota_bytes`, { replacements: { warehouseId }, type: this.app.model.QueryTypes.SELECT, } ); - const remaining_bytes = warehouse_quota[0].remaining_bytes; - if (remaining_bytes - fileSize < 0) { - return { - error: true, - msg: '空间配额已满', - }; + const warehouseQuota = Array.isArray(warehouse_quota) ? warehouse_quota[0] : null; + const remainingBytes = warehouseQuota ? Number(warehouseQuota.remaining_bytes) : NaN; + if (Number.isFinite(remainingBytes)) { + if (remainingBytes - fileSize < 0) { + return { + error: true, + msg: '空间配额已满', + }; + } + } else { + this.ctx.logger.warn( + `仓库配额查询结果无效,跳过配额拦截,warehouseId=${warehouseId}, quotaRow=${JSON.stringify(warehouseQuota)}` + ); } // 生成文件名 const cosFileName = this.generateFileName(fileName, fileType, type, md5); diff --git a/app/view/platform_oauth_callback.html b/app/view/platform_oauth_callback.html new file mode 100644 index 0000000..53a8c4b --- /dev/null +++ b/app/view/platform_oauth_callback.html @@ -0,0 +1,147 @@ + + + + + + <%= title %> + + + +
+
+

<%= title %>

+
用于人工核对平台授权回调参数与预授权码处理状态
+
+ +
+ 综合结果:<%= resultText %> +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
平台返回 code<%= code || '-' %>
平台返回 state<%= state || '-' %>
去前缀后的 state<%= normalizedState || '-' %>
解析出的 platform_code<%= platformCode || '-' %>
解析出的 auth_random_code<%= authRandomCode || '-' %>
是否找到预授权码记录<%= hasShop ? '是' : '否' %>
预授权码是否已处理<%= isProcessedText %>
平台是否正确<%= isPlatformMatchedText %>
记录中的 platform_code<%= shopPlatformCode || '-' %>
记录中的 status<%= shopStatus === null ? '-' : shopStatus %>
+
+
+ + \ No newline at end of file diff --git a/check_brackets.js b/check_brackets.js new file mode 100644 index 0000000..9e77f37 --- /dev/null +++ b/check_brackets.js @@ -0,0 +1,39 @@ +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 = []; +let isInString = null; +let isInComment = null; +let isEscaped = false; +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++; +} +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/config/config.default.js b/config/config.default.js index 8a56b23..f24da08 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -195,6 +195,7 @@ module.exports = appInfo => { }; config.debug = false; // 生成环境默认关闭 debug,开发环境通过 config.local.js 开启 + config.platformOauthReservationCodePrefix = ''; config.printService = { url: 'http://printer.wms.gztbyc.com', }; diff --git a/database/migrations/20260519183000-create-wms-review-task.js b/database/migrations/20260519183000-create-wms-review-task.js index c5b2933..990b0c8 100644 --- a/database/migrations/20260519183000-create-wms-review-task.js +++ b/database/migrations/20260519183000-create-wms-review-task.js @@ -249,4 +249,4 @@ module.exports.down = async queryInterface => { } await queryInterface.dropTable('wms_recheck_task'); -}; \ No newline at end of file +}; diff --git a/database/migrations/20260521090000-add-customer-id-to-wms-qimen-apps.js b/database/migrations/20260521090000-add-customer-id-to-wms-qimen-apps.js new file mode 100644 index 0000000..6d560fa --- /dev/null +++ b/database/migrations/20260521090000-add-customer-id-to-wms-qimen-apps.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为奇门应用配置表新增 customer_id 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 customer_id 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_qimen_apps'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.customer_id) { + return; + } + + await queryInterface.addColumn(tableName, 'customer_id', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '客户标识', + }); + }, + + /** + * 回滚迁移:删除 customer_id 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_qimen_apps'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.customer_id) { + return; + } + + await queryInterface.removeColumn(tableName, 'customer_id'); + }, +}; diff --git a/database/migrations/20260521113000-add-ext-data-to-wms-express-interface.js b/database/migrations/20260521113000-add-ext-data-to-wms-express-interface.js new file mode 100644 index 0000000..e7ed9b2 --- /dev/null +++ b/database/migrations/20260521113000-add-ext-data-to-wms-express-interface.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递接口配置表新增扩展信息字段 ext_data。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 ext_data 字段(幂等)。 + * @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.ext_data) { + return; + } + + await queryInterface.addColumn(tableName, 'ext_data', { + type: Sequelize.JSON, + allowNull: true, + comment: '扩展信息', + }); + }, + + /** + * 回滚迁移:删除 ext_data 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.ext_data) { + return; + } + + await queryInterface.removeColumn(tableName, 'ext_data'); + }, +}; diff --git a/database/migrations/20260522103000-create-shops.js b/database/migrations/20260522103000-create-shops.js new file mode 100644 index 0000000..02c9bc6 --- /dev/null +++ b/database/migrations/20260522103000-create-shops.js @@ -0,0 +1,128 @@ +'use strict'; + +const TABLE_NAME = 'wms_shops'; + +/** + * 获取当前数据库已存在的表名集合。 + * @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 {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createShopsTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + platform_code: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '平台编码', + }, + shop_name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '店铺名称', + }, + status: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '授权状态:0=未授权,1=已授权', + }, + auth_expire_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '授权到期时间', + }, + auth_random_code: { + type: Sequelize.STRING(128), + allowNull: true, + comment: '授权随机码', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '店铺表', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { + name: 'idx_warehouse_id', + }); + await queryInterface.addIndex(TABLE_NAME, [ 'platform_code' ], { + name: 'idx_platform_code', + }); + await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { + name: 'idx_status', + }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'platform_code', 'shop_name' ], { + name: 'uk_warehouse_platform_shop_name', + unique: true, + }); + await queryInterface.addIndex(TABLE_NAME, [ 'auth_random_code' ], { + name: 'uk_auth_random_code', + unique: true, + }); +}; + +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 createShopsTable(queryInterface, Sequelize); + } + }, + + /** + * 回滚删除店铺表。 + * @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); + } + }, +}; \ 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 new file mode 100644 index 0000000..48c2d7b --- /dev/null +++ b/database/migrations/20260522110000-add-auth-base-url-to-wms_platform.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为 wms_platform 新增 auth_base_url 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 auth_base_url 字段(幂等)。 + * @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.auth_base_url) { + return; + } + + await queryInterface.addColumn(tableName, 'auth_base_url', { + type: Sequelize.STRING(255), + allowNull: true, + comment: '授权基础地址', + }); + }, + + /** + * 回滚迁移:删除 auth_base_url 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_platform'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.auth_base_url) { + return; + } + + 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 new file mode 100644 index 0000000..6d45470 --- /dev/null +++ b/database/migrations/20260522123000-add-auth-result-fields-to-wms-shops.js @@ -0,0 +1,102 @@ +'use strict'; + +/** + * 为店铺表新增授权结果字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增授权结果字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_shops'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.owner_id) { + await queryInterface.addColumn(tableName, 'owner_id', { + type: Sequelize.STRING(64), + allowNull: true, + comment: '平台店铺/主体ID', + }); + } + + if (!columns.access_token) { + await queryInterface.addColumn(tableName, 'access_token', { + type: Sequelize.STRING(255), + allowNull: true, + comment: '访问令牌', + }); + } + + if (!columns.refresh_token) { + await queryInterface.addColumn(tableName, 'refresh_token', { + type: Sequelize.STRING(255), + allowNull: true, + comment: '刷新令牌', + }); + } + + if (!columns.token_expires_at) { + await queryInterface.addColumn(tableName, 'token_expires_at', { + type: Sequelize.DATE, + allowNull: true, + comment: '访问令牌过期时间', + }); + } + + if (!columns.refresh_token_expires_at) { + await queryInterface.addColumn(tableName, 'refresh_token_expires_at', { + type: Sequelize.DATE, + allowNull: true, + comment: '刷新令牌过期时间', + }); + } + + if (!columns.scope) { + await queryInterface.addColumn(tableName, 'scope', { + type: Sequelize.JSON, + allowNull: true, + comment: '授权范围', + }); + } + }, + + /** + * 回滚迁移:删除授权结果字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_shops'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.scope) { + await queryInterface.removeColumn(tableName, 'scope'); + } + + if (columns.refresh_token_expires_at) { + await queryInterface.removeColumn(tableName, 'refresh_token_expires_at'); + } + + if (columns.token_expires_at) { + await queryInterface.removeColumn(tableName, 'token_expires_at'); + } + + if (columns.refresh_token) { + await queryInterface.removeColumn(tableName, 'refresh_token'); + } + + if (columns.access_token) { + await queryInterface.removeColumn(tableName, 'access_token'); + } + + if (columns.owner_id) { + 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 new file mode 100644 index 0000000..cb22eac --- /dev/null +++ b/database/migrations/20260522133000-add-custom-name-to-wms-shops.js @@ -0,0 +1,42 @@ +'use strict'; + +/** + * 为店铺表新增自定义名称字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增店铺自定义名称字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_shops'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.custom_name) { + await queryInterface.addColumn(tableName, 'custom_name', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '店铺自定义名称', + }); + } + }, + + /** + * 回滚迁移:删除店铺自定义名称字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_shops'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.custom_name) { + await queryInterface.removeColumn(tableName, 'custom_name'); + } + }, +}; \ No newline at end of file diff --git a/methods/changes/2026.05.20-system-01.json b/methods/changes/2026.05.20-system-01.json index 671ac38..8424c5d 100644 --- a/methods/changes/2026.05.20-system-01.json +++ b/methods/changes/2026.05.20-system-01.json @@ -2,14 +2,17 @@ { "version": "2026.05.20-system-01", "date": "2026-05-20", - "summary": "新增订单复核模块方法:order.recheckOrder.scanWaybill、order.recheckOrder.confirmRecheck", + "summary": "新增订单复核模块方法:order.recheckOrder.scanOrder、order.recheckOrder.confirmRecheck", "methods": [ - "order.recheckOrder.scanWaybill", + "order.recheckOrder.scanOrder", "order.recheckOrder.confirmRecheck" ], "notes": [ - "用途:扫码查询订单明细(scanWaybill);确认复核并落库 wms_recheck_task(confirmRecheck)。", - "scanWaybill 返回运单号、订单头、商品明细、运单信息与相关日志;confirmRecheck 将复核结果写入 wms_recheck_task 并返回复核摘要信息(order_id、recheck_status、recheck_time、review_no)。" + "用途:扫码查询订单明细(scanOrder);确认复核并落库 wms_recheck_task(confirmRecheck)。", + "scanOrder 返回运单号或车号匹配的订单头、商品明细、运单信息与相关日志;confirmRecheck 将复核结果写入 wms_recheck_task 并返回复核摘要信息(order_id、recheck_status、recheck_time、review_no)。", + "变更概要:confirmRecheck 改为按 order_id 进行复核(兼容 id/orderId);scanOrder 返回准确的 order_id 供前端直接使用;新增支持:查找范围包含 wms_wave_pick_task 的车号快照(current_cart_code_snapshot / wms_wave_pick_task_order.cart_code_snapshot)。", + "规则调整:移除打印状态约束,改为未拣货约束。", + "scanOrder 在车号命中场景按波次类型返回不同结构(1/5 groups, 2 orders, 3 pick_groups, 4 box_groups)。" ], "type": "added" } diff --git a/methods/changes/2026.05.20-system-03.json b/methods/changes/2026.05.20-system-03.json new file mode 100644 index 0000000..b8ed107 --- /dev/null +++ b/methods/changes/2026.05.20-system-03.json @@ -0,0 +1,18 @@ +[ + { + "version": "2026.05.20-system-03", + "date": "2026-05-20", + "summary": "新增 storeWarehouse.store.queryPrintQuantityLogs:按 store_id 分页查询面单余额变更日志", + "methods": [ + "storeWarehouse.store.queryPrintQuantityLogs" + ], + "notes": [ + "新增方法:storeWarehouse.store.queryPrintQuantityLogs,用于按货主(store_id)分页查询面单余额变更日志。", + "入参:store_id(必填)、page(可选)、page_size / pageSize(可选,兼容别名)。", + "仅同步 methods/system.json 与本变更记录,不修改业务代码或测试。", + "返回:使用默认分页格式,响应在 `data` 下包含 `list`(变更日志数组)和 `pagination` 对象,`pagination` 字段:`page`、`pageSize`、`total`、`totalPages`、`hasPrevious`、`hasNext`。" + ], + "type": "added", + "module": "storeWarehouse" + } +] diff --git a/methods/changes/system.json b/methods/changes/system.json index 16730e0..4cdc45c 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -2003,5 +2003,109 @@ ], "module": "print", "type": "added" + }, + { + "version": "2026.05.20-system-01", + "date": "2026-05-20", + "summary": "同步 order.recheckOrder.scanOrder 返回结构,补充 cart_match_view 语义化视图说明", + "methods": [ + "order.recheckOrder.scanOrder" + ], + "notes": [ + "新增返回字段:match_type(waybill/cart)与 cart_match_view(仅 cart 命中返回)。", + "cart_match_view 包含通用子字段:mode_code / mode_name / view_type / task;当车号命中时按 pick_mode 返回语义化结构:mode 1/5 返回 groups,mode 2 返回 orders,mode 3 返回 pick_groups,mode 4 返回 box_groups。" + ], + "type": "updated" + }, + { + "version": "2026.05.22-system-01", + "date": "2026-05-22", + "summary": "新增 index.getPlatformOauthLink 文档,补充平台授权链接接口说明", + "methods": [ + "index.getPlatformOauthLink" + ], + "notes": [ + "入参支持 code、platform_code、platformCode 三种平台编码字段别名。", + "当前仅支持 PDD;成功返回 data.platform_code、data.oauth_link 和 code=200,其他平台返回 code=400。", + "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改业务代码。" + ], + "type": "added", + "module": "index" + }, + { + "version": "2026.05.22-system-02", + "date": "2026-05-22", + "summary": "更新 index.getPlatformOauthLink 文档,补充仓库上下文、预占记录与错误说明", + "methods": [ + "index.getPlatformOauthLink" + ], + "notes": [ + "补充真实行为:从 ctx.user.store_id 读取当前仓库 ID,从 wms_platform.auth_base_url 读取授权基础地址,并在 wms_shops 创建平台授权预占记录。", + "补充 oauth_link 细节:追加 client_id、redirect_uri(配置非空时)以及长查询参数 wms_authorization_reservation_code,对应唯一 auth_random_code。", + "补充常见错误:平台编码为空、仓库上下文缺失、平台不存在、授权基础地址缺失/格式错误、不支持的平台,以及预占记录创建失败。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.22-system-03", + "date": "2026-05-22", + "summary": "同步 index.getPlatformOauthLink 当前实现:裸码入库与 state 拼接规则", + "methods": [ + "index.getPlatformOauthLink" + ], + "notes": [ + "补充真实行为:从 ctx.user.store_id 读取当前仓库,从 wms_platform.auth_base_url 读取基础授权链接,并优先复用 wms_shops 中 status=0 的未授权记录。", + "明确 auth_random_code 当前以裸码保存;若复用到历史带前缀记录,会先去掉 platformOauthReservationCodePrefix 后再回写。", + "更新 oauth_link 说明:state 由“前缀 + 平台编码 + '_' + 裸码”组成并整体 URL 编码后直接拼接到基础授权链接后,例如 xxxxx_PDD_;同时移除已不存在的基础地址格式错误/不支持平台错误描述。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.22-system-04", + "date": "2026-05-22", + "summary": "修正 index.getPlatformOauthLink 文档中的残留平台限制描述", + "methods": [ + "index.getPlatformOauthLink" + ], + "notes": [ + "移除 index.getPlatformOauthLink 参数与返回字段中残留的“当前仅支持 PDD”描述,避免与当前实现不一致。", + "保留授权链接仅依赖平台已配置基础授权链接模式的说明,不再把示例平台编码误写成实现限制。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.22-system-05", + "date": "2026-05-22", + "summary": "新增 index.getShopList 文档,并同步 custom_name 与店铺列表脱敏返回规则", + "methods": [ + "index.getShopList" + ], + "notes": [ + "新增 index.getShopList:接口依赖当前登录仓库上下文 ctx.user.store_id,不接受额外业务入参,缺少仓库时返回 400:未识别到当前仓库。", + "补充真实返回结构:data.list 为数组,包含 id、warehouse_id、platform_code、shop_name、custom_name、status、auth_expire_at、token_expires_at、refresh_token_expires_at、scope、created_at、updated_at 以及脱敏后的 owner_id、access_token、refresh_token、auth_random_code。", + "同步脱敏规则:owner_id 非空且长度大于 5 时返回前 3 位 + *** + 后 2 位,长度小于等于 5 时返回 ***;access_token、refresh_token、auth_random_code 非空时固定返回 ***,空值返回 null。", + "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改任何业务代码。" + ], + "type": "added", + "module": "index" + }, + { + "version": "2026.05.22-system-06", + "date": "2026-05-22", + "summary": "新增 index.getShopExpressList 文档,补充店铺快递列表统一返回结构", + "methods": [ + "index.getShopExpressList" + ], + "notes": [ + "按 ctx.user.store_id 校验店铺归属,仅允许查询当前登录仓库下的店铺。", + "服务端按店铺所属平台拉取并收敛快递签约/电子面单可用列表,统一返回前端消费结构。", + "未接入平台当前返回空列表;若店铺缺少授权 access_token,则返回 400:店铺未授权。", + "仅文档同步,不改业务代码。" + ], + "type": "added", + "module": "index" } ] diff --git a/methods/system.json b/methods/system.json index 851d24f..8df1aac 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-20", + "updatedAt": "2026-05-22", "headers": [ { "name": "platform", @@ -450,6 +450,140 @@ "response": [], "errors": [] }, + { + "method": "index.test", + "description": "后台专用的拼多多开放平台测试接口,用于传入请求参数并发起真实请求,返回签名后的请求体和接口响应", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "type", + "type": "string", + "required": true, + "source": "body", + "description": "拼多多接口名,例如 pdd.order.number.list.get" + }, + { + "name": "bizParams", + "type": "object", + "required": false, + "source": "body", + "description": "业务参数对象,会参与签名和请求" + }, + { + "name": "request", + "type": "object", + "required": false, + "source": "body", + "description": "bizParams 兼容字段" + }, + { + "name": "accessToken", + "type": "string", + "required": false, + "source": "body", + "description": "用户授权令牌" + }, + { + "name": "access_token", + "type": "string", + "required": false, + "source": "body", + "description": "accessToken 的下划线命名兼容字段" + }, + { + "name": "dataType", + "type": "string", + "required": false, + "source": "body", + "description": "返回格式,默认 JSON" + }, + { + "name": "version", + "type": "string", + "required": false, + "source": "body", + "description": "API 版本" + }, + { + "name": "timestamp", + "type": "string|number", + "required": false, + "source": "body", + "description": "时间戳,不传则使用当前秒级时间戳" + }, + { + "name": "clientId", + "type": "string", + "required": false, + "source": "body", + "description": "覆盖配置中的 client_id" + }, + { + "name": "clientSecret", + "type": "string", + "required": false, + "source": "body", + "description": "覆盖配置中的 client_secret" + }, + { + "name": "baseUrl", + "type": "string", + "required": false, + "source": "body", + "description": "请求地址,默认拼多多开放平台网关" + }, + { + "name": "headers", + "type": "object", + "required": false, + "source": "body", + "description": "额外请求头" + }, + { + "name": "timeout", + "type": "number", + "required": false, + "source": "body", + "description": "请求超时时间(毫秒)" + } + ], + "response": [ + { + "name": "requestBody", + "type": "object", + "description": "实际发送到 PDD 网关的请求体,已包含 sign" + }, + { + "name": "response", + "type": "any", + "description": "拼多多接口返回内容" + }, + { + "name": "baseUrl", + "type": "string", + "description": "实际请求地址" + } + ], + "errors": [ + { + "code": "400", + "description": "type 不能为空" + }, + { + "code": "500", + "description": "PDD 接口调用失败" + } + ] + }, { "method": "index.recognizeLicensePlate", "description": "识别车牌号码(通过 base64 图片)", @@ -727,6 +861,458 @@ } ], "errors": [] + }, + { + "method": "index.getPlatformOauthLink", + "description": "获取平台授权链接。入参支持 code / platform_code / platformCode,服务端按首个非空值标准化为大写平台编码;会从当前登录上下文读取仓库 ID(ctx.user.store_id),再从 wms_platform.auth_base_url 读取授权基础地址。接口会优先复用当前仓库与平台下 status=0 的未授权记录;若历史 auth_random_code 带有当前配置前缀,则会先去前缀后以裸码回写,当前数据库最终保存的 auth_random_code 为裸码。若无可复用记录则生成新的裸码并写入 wms_shops。返回的 oauth_link 会从配置 platformOauthReservationCodePrefix 读取前缀(本地示例为 xxxxx_),按“前缀 + 平台编码 + '_' + 裸码”生成 state,并将 URL 编码后的 state 直接拼接到平台基础授权链接后,例如 xxxxx_PDD_。当前仅支持已按上述模式配置好的基础授权链接。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "code", + "type": "string", + "required": false, + "source": "body", + "description": "平台编码主字段;与 platform_code / platformCode 三选一即可,服务端按 code -> platform_code -> platformCode 顺序取首个非空值并转为大写" + }, + { + "name": "platform_code", + "type": "string", + "required": false, + "source": "body", + "description": "平台编码下划线别名" + }, + { + "name": "platformCode", + "type": "string", + "required": false, + "source": "body", + "description": "平台编码驼峰别名" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功时返回 200" + }, + { + "name": "data.platform_code", + "type": "string", + "required": true, + "description": "标准化后的平台编码" + }, + { + "name": "data.oauth_link", + "type": "string", + "required": true, + "description": "基于 wms_platform.auth_base_url 构造的授权链接;实际拼接值为 encodeURIComponent(prefix + platform_code + '_' + rawCode),其中 prefix 来自 platformOauthReservationCodePrefix,rawCode 为数据库 auth_random_code 中保存的裸码。基础授权链接需预先配置为可直接追加 state 值的模式。" + } + ], + "errors": [ + { + "code": 400, + "message": "平台编码不能为空" + }, + { + "code": 400, + "message": "未识别到当前仓库" + }, + { + "code": 400, + "message": "平台不存在" + }, + { + "code": 400, + "message": "平台授权基础地址未配置" + }, + { + "code": 500, + "message": "创建平台授权预占记录失败" + }, + { + "code": 500, + "message": "生成唯一授权码失败,请稍后重试" + } + ] + }, + { + "method": "index.getShopList", + "description": "获取当前登录仓库下的店铺列表。仓库上下文来自 ctx.user.store_id,不接受额外业务入参;服务端按 status DESC、updated_at DESC、id DESC 排序查询 wms_shops,并对敏感字段完成脱敏后返回 data.list。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功时返回 200" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息,成功时返回 ok" + }, + { + "name": "data.list", + "type": "array", + "required": true, + "description": "当前登录仓库下的店铺列表数组;结果按 status DESC、updated_at DESC、id DESC 排序,且 owner_id、access_token、refresh_token、auth_random_code 已按实现规则脱敏。", + "children": [ + { + "name": "id", + "type": "number", + "description": "店铺主键 ID" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "所属仓库 ID(来自当前登录仓库上下文)" + }, + { + "name": "platform_code", + "type": "string", + "description": "平台编码" + }, + { + "name": "shop_name", + "type": "string", + "description": "店铺名称" + }, + { + "name": "custom_name", + "type": "string|null", + "description": "店铺自定义名称;wms_shops 当前真实字段,未设置时返回 null" + }, + { + "name": "status", + "type": "number", + "description": "授权状态:0=未授权,1=已授权" + }, + { + "name": "auth_expire_at", + "type": "string|null", + "description": "授权到期时间,未设置时返回 null" + }, + { + "name": "token_expires_at", + "type": "string|null", + "description": "访问令牌过期时间,未设置时返回 null" + }, + { + "name": "refresh_token_expires_at", + "type": "string|null", + "description": "刷新令牌过期时间,未设置时返回 null" + }, + { + "name": "scope", + "type": "object|array|null", + "description": "授权范围;直接返回数据库 JSON 字段内容,可能为对象、数组或 null" + }, + { + "name": "created_at", + "type": "string", + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "description": "更新时间" + }, + { + "name": "owner_id", + "type": "string|null", + "description": "平台店铺/主体 ID;非空且长度大于 5 时返回前 3 位 + *** + 后 2 位,长度小于等于 5 时返回 ***,空值返回 null" + }, + { + "name": "access_token", + "type": "string|null", + "description": "访问令牌;非空固定返回 ***,空值返回 null" + }, + { + "name": "refresh_token", + "type": "string|null", + "description": "刷新令牌;非空固定返回 ***,空值返回 null" + }, + { + "name": "auth_random_code", + "type": "string|null", + "description": "授权随机码;非空固定返回 ***,空值返回 null" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库" + } + ] + }, + { + "method": "index.getShopExpressList", + "description": "获取指定店铺的快递签约/电子面单可用列表。接口依赖当前登录仓库上下文 ctx.user.store_id 校验店铺归属;服务端会按店铺所属平台拉取并收敛可用快递列表,统一返回前端消费结构;未接入的平台当前返回空列表。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "shop_id", + "type": "string|number", + "required": false, + "source": "body", + "description": "店铺 ID;与 shopId 兼容,二选一至少传一个。服务端按 shop_id、shopId 的顺序读取首个非空值。" + }, + { + "name": "shopId", + "type": "string|number", + "required": false, + "source": "body", + "description": "店铺 ID 的驼峰兼容字段;当 shop_id 为空时读取该值。" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功时返回 200。" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息,成功时返回 ok。" + }, + { + "name": "data.shop_id", + "type": "number", + "required": true, + "description": "当前店铺 ID。" + }, + { + "name": "data.platform_code", + "type": "string", + "required": true, + "description": "店铺所属平台编码,返回值按服务端实现转为大写。" + }, + { + "name": "data.list", + "type": "array", + "required": true, + "description": "服务端按店铺所属平台拉取并统一收敛后的快递签约/电子面单可用列表;未接入的平台返回空数组。", + "children": [ + { + "name": "wp_code", + "type": "string", + "required": true, + "description": "快递/面单服务编码。" + }, + { + "name": "wp_type", + "type": "string", + "required": true, + "description": "快递/面单类型标识。" + }, + { + "name": "accounts", + "type": "array", + "required": true, + "description": "当前快递服务下的签约账号列表;无签约账号时返回空数组。", + "children": [ + { + "name": "branch_code", + "type": "string", + "required": true, + "description": "网点/签约账号编码。" + }, + { + "name": "branch_name", + "type": "string", + "required": true, + "description": "网点/签约账号名称。" + }, + { + "name": "quantity", + "type": "number", + "required": true, + "description": "当前可用单量。" + }, + { + "name": "cancel_quantity", + "type": "number", + "required": true, + "description": "已取消单量。" + }, + { + "name": "recycled_quantity", + "type": "number", + "required": true, + "description": "已回收单量。" + }, + { + "name": "allocated_quantity", + "type": "number", + "required": true, + "description": "已分配单量。" + }, + { + "name": "ship_addresses", + "type": "array", + "required": true, + "description": "发货地址列表;无可用地址时返回空数组。", + "children": [ + { + "name": "country", + "type": "string", + "required": true, + "description": "国家。" + }, + { + "name": "province", + "type": "string", + "required": true, + "description": "省。" + }, + { + "name": "city", + "type": "string", + "required": true, + "description": "市。" + }, + { + "name": "district", + "type": "string", + "required": true, + "description": "区/县。" + }, + { + "name": "detail", + "type": "string", + "required": true, + "description": "详细地址。" + }, + { + "name": "full_address", + "type": "string", + "required": true, + "description": "完整地址。" + } + ] + }, + { + "name": "services", + "type": "array", + "required": true, + "description": "当前签约账号可用的附加服务列表;无可用服务时返回空数组。", + "children": [ + { + "name": "service_code", + "type": "string", + "required": true, + "description": "服务编码。" + }, + { + "name": "service_name", + "type": "string", + "required": true, + "description": "服务名称。" + }, + { + "name": "service_desc", + "type": "string", + "required": true, + "description": "服务说明。" + }, + { + "name": "required", + "type": "boolean", + "required": true, + "description": "是否为必选服务。" + }, + { + "name": "attributes", + "type": "array", + "required": true, + "description": "服务属性列表;无属性时返回空数组。", + "children": [ + { + "name": "attribute_code", + "type": "string", + "required": true, + "description": "属性编码。" + }, + { + "name": "attribute_name", + "type": "string", + "required": true, + "description": "属性名称。" + }, + { + "name": "attribute_type", + "type": "string", + "required": true, + "description": "属性类型编码。" + }, + { + "name": "type_desc", + "type": "string", + "required": true, + "description": "属性类型说明。" + } + ] + } + ] + } + ] + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "shop_id 不能为空" + }, + { + "code": 400, + "message": "未识别到当前仓库" + }, + { + "code": 404, + "message": "店铺不存在" + }, + { + "code": 400, + "message": "店铺未授权" + } + ] } ] }, @@ -2598,8 +3184,8 @@ "module": "order.recheckOrder", "list": [ { - "method": "order.recheckOrder.scanWaybill", - "description": "扫码查询运单并返回订单详情", + "method": "order.recheckOrder.scanOrder", + "description": "扫码查询订单(支持运单号与车号)并返回订单详情。车号命中时按 pick_mode 返回语义化结构。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -2612,54 +3198,132 @@ ], "params": [ { - "name": "waybill_no / waybillCode / waybill_code", + "name": "keyword / value / waybill_no / waybillCode / waybill_code / cart_code / cartCode", "type": "string", "required": true, "source": "body|query", - "description": "运单号;支持别名 waybillCode、waybill_code" + "description": "扫描关键词;优先按运单号匹配,未命中时回退到 wms_wave_pick_task.current_cart_code_snapshot / wms_wave_pick_task_order.cart_code_snapshot 车号匹配,支持别名 waybillCode/waybill_code/cart_code/cartCode" } ], "response": [ + { + "name": "match_type", + "type": "string", + "required": true, + "description": "命中类型:waybill(运单号命中)/ cart(车号命中)" + }, + { + "name": "cart_match_view", + "type": "object|null", + "required": true, + "description": "仅 cart 命中返回对象,waybill 命中返回 null" + }, + { + "name": "cart_match_view.mode_code", + "type": "number", + "required": false, + "description": "波次类型编码(pick_mode)" + }, + { + "name": "cart_match_view.mode_name", + "type": "string", + "required": false, + "description": "波次类型名称" + }, + { + "name": "cart_match_view.view_type", + "type": "string", + "required": false, + "description": "语义化视图类型:groups/orders/pick_groups/box_groups" + }, + { + "name": "cart_match_view.task", + "type": "object", + "required": false, + "description": "任务摘要信息" + }, + { + "name": "cart_match_view.groups", + "type": "array", + "required": false, + "description": "仅 mode_code=1/5 返回,按 wave 分组" + }, + { + "name": "cart_match_view.orders", + "type": "array", + "required": false, + "description": "仅 mode_code=2 返回,直接返回订单列表" + }, + { + "name": "cart_match_view.pick_groups", + "type": "array", + "required": false, + "description": "仅 mode_code=3 返回,按 pick_status 分组" + }, + { + "name": "cart_match_view.box_groups", + "type": "array", + "required": false, + "description": "仅 mode_code=4 返回,按 box_no 分组" + }, + { + "name": "order_id", + "type": "number", + "required": true, + "description": "准确的订单 ID(供 confirmRecheck 使用)" + }, { "name": "waybill_no", "type": "string", + "required": true, "description": "匹配到的运单号" }, { "name": "order", "type": "object", + "required": true, "description": "订单头对象" }, { "name": "items", "type": "array", + "required": true, "description": "订单商品明细" }, { "name": "expresses", "type": "array", + "required": true, "description": "运单信息数组" }, { "name": "logs", "type": "array", + "required": true, "description": "相关操作日志" } ], "errors": [ { "code": "400", - "description": "运单号不能为空" + "message": "扫描关键词不能为空", + "description": "扫描关键词不能为空" }, { "code": "404", + "message": "未找到对应订单", "description": "未找到对应订单" + }, + { + "code": "400", + "message": "订单未拣货,不允许复核。", + "description": "订单未拣货,不允许复核。" } ] }, { "method": "order.recheckOrder.confirmRecheck", - "description": "确认复核并记录复核任务到 wms_recheck_task", + "description": "按订单 ID 确认复核并记录复核任务到 wms_recheck_task(入参兼容 id/orderId)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -2672,11 +3336,11 @@ ], "params": [ { - "name": "waybill_no / waybillCode / waybill_code", - "type": "string", + "name": "order_id / id / orderId", + "type": "string|number", "required": true, "source": "body|query", - "description": "运单号,支持别名 waybillCode、waybill_code" + "description": "订单 ID;优先使用 order_id,兼容别名 id 与 orderId" } ], "response": [ @@ -2709,11 +3373,15 @@ "errors": [ { "code": "400", - "description": "运单号不能为空" + "description": "订单ID不能为空" }, { "code": "404", "description": "未找到对应订单" + }, + { + "code": "400", + "description": "订单未拣货,不允许复核。" } ] } @@ -9241,6 +9909,11 @@ "name": "shop_name", "type": "string", "description": "店铺名称/分组标识" + }, + { + "name": "ext_data", + "type": "object", + "description": "扩展信息 JSON(支持任意键值对象)" } ] }, @@ -9412,6 +10085,11 @@ "type": "string", "description": "店铺名称/分组标识" }, + { + "name": "ext_data", + "type": "object", + "description": "扩展信息 JSON(支持任意键值对象)" + }, { "name": "express", "type": "object", @@ -9634,6 +10312,13 @@ "required": false, "source": "body", "description": "店铺名称/分组标识(支持 shopName,可选,最长 255 字符)" + }, + { + "name": "ext_data", + "type": "object", + "required": false, + "source": "body", + "description": "扩展信息 JSON(支持 extData),可选,建议传对象" } ], "response": [ @@ -9847,6 +10532,13 @@ "required": false, "source": "body", "description": "店铺名称/分组标识(支持 shopName)" + }, + { + "name": "ext_data", + "type": "object", + "required": false, + "source": "body", + "description": "扩展信息 JSON(支持 extData)" } ], "response": [ @@ -15795,6 +16487,124 @@ "response": [], "errors": [] }, + { + "method": "storeWarehouse.store.queryPrintQuantityLogs", + "description": "按 store_id 分页查询面单余额变更日志", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "store_id", + "type": "number|string", + "required": true, + "source": "body", + "description": "货主ID(必填)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页对象,包含 page 与 page_size;默认 { page: 1, page_size: 20 }", + "children": [ + { + "name": "page", + "type": "number", + "required": false, + "description": "页码,默认 1" + }, + { + "name": "page_size", + "type": "number", + "required": false, + "description": "每页条数,默认 20" + } + ] + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "返回结果对象,包含 list 和 pagination", + "children": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "变更日志列表,字段示例:id, contract_id, store_id, warehouse_id, change_type, business_type, business_id, change_quantity, balance_before, balance_after, reason, operator_id, created_by, created_at, updated_at" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)", + "children": [ + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页码" + }, + { + "name": "pageSize", + "type": "number", + "required": true, + "description": "每页条数" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "totalPages", + "type": "number", + "required": false, + "description": "总页数" + }, + { + "name": "hasPrevious", + "type": "boolean", + "required": false, + "description": "是否有上一页" + }, + { + "name": "hasNext", + "type": "boolean", + "required": false, + "description": "是否有下一页" + } + ] + } + ] + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误或缺少 store_id" + }, + { + "code": "403", + "description": "仅可查询当前货主的面单余额变更日志" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, { "method": "storeWarehouse.store.getPolicyConfig", "description": "读取签约策略配置", diff --git a/test/app/controller/system.setting.storeWarehouse.test.js b/test/app/controller/system.setting.storeWarehouse.test.js index be01ed6..ae6dbe7 100644 --- a/test/app/controller/system.setting.storeWarehouse.test.js +++ b/test/app/controller/system.setting.storeWarehouse.test.js @@ -1,6 +1,7 @@ 'use strict'; const assert = require('node:assert/strict'); +const { app } = require('egg-mock/bootstrap'); const { getAuthToken, invokeSystemMethod, @@ -25,6 +26,50 @@ function pickFixedTestRelation(relations) { || null; } +/** + * 确保指定 AppKey 存在对应的奇门应用记录。 + * + * @param {string} appKey 奇门应用 AppKey。 + * @param {string} customerId 客户标识。 + * @return {Promise} 是否为本次测试新建的记录。 + */ +async function ensureQimenAppRecord(appKey, customerId) { + const existing = await app.model.QimenApp.findOne({ + where: { + app_key: appKey, + }, + }); + + if (existing) { + return false; + } + + await app.model.QimenApp.create({ + name: `autotest_qimen_app_${Date.now()}`, + app_key: appKey, + customer_id: customerId, + }); + return true; +} + +/** + * 删除测试创建的奇门应用记录。 + * + * @param {string} appKey 奇门应用 AppKey。 + * @return {Promise} 无返回值。 + */ +async function removeQimenAppRecord(appKey) { + if (!appKey) { + return; + } + + await app.model.QimenApp.destroy({ + where: { + app_key: appKey, + }, + }); +} + describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { const METHOD_PREFIX = 'storeWarehouse.store'; let token = ''; @@ -324,12 +369,17 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { const originalApiConfig = candidate.api_config || candidate.apiConfig || null; const seed = Date.now(); + const createdCustomerId = `autotest_customer_db_${seed}`; + const updatedCustomerId = `${createdCustomerId}_updated`; + const ignoredCustomerId = `autotest_customer_external_${seed}`; + const restoreAppKey = originalApiConfig?.qimen_app_key || ''; + let createdQimenApp = false; + let createdRestoreQimenApp = false; const createPayload = { id: Number(candidate.id), interface_type_id: Number((originalApiConfig && originalApiConfig.interface_type_id) || 0) || undefined, app_name: `autotest_api_${seed}`, qimen_app_key: `autotest_app_${seed}`, - qimen_customer_id: `autotest_customer_${seed}`, qimen_warehouse_code: `autotest_wh_${seed}`, contact_person: 'autotest', contact_phone: '13800138000', @@ -338,6 +388,11 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { }; try { + createdQimenApp = await ensureQimenAppRecord(createPayload.qimen_app_key, createdCustomerId); + if (restoreAppKey && String(originalApiConfig?.qimen_customer_id || '').trim()) { + createdRestoreQimenApp = await ensureQimenAppRecord(restoreAppKey, String(originalApiConfig.qimen_customer_id || '').trim()); + } + const saveRes = await invokeSystemMethod(`${METHOD_PREFIX}.saveApiConfig`, createPayload, token, EXTRA_HEADERS); assert.equal(saveRes.status, 200); assert.equal(saveRes.body.flag, 'success'); @@ -347,14 +402,22 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { const savedApiConfig = saveRes.body?.data?.api_config || saveRes.body?.data?.apiConfig || saveRes.body?.data?.qimen_config || null; assert.ok(savedApiConfig, '保存后应返回 api_config'); assert.equal(String(savedApiConfig?.qimen_app_key || ''), createPayload.qimen_app_key); - assert.equal(String(savedApiConfig?.qimen_customer_id || ''), createPayload.qimen_customer_id); + assert.equal(String(savedApiConfig?.qimen_customer_id || ''), createdCustomerId); assert.equal(String(savedApiConfig?.qimen_warehouse_code || ''), createPayload.qimen_warehouse_code); + await app.model.QimenApp.update({ + customer_id: updatedCustomerId, + }, { + where: { + app_key: createPayload.qimen_app_key, + }, + }); + const updatePayload = { ...createPayload, interface_type_id: Number((savedApiConfig && savedApiConfig.interface_type_id) || createPayload.interface_type_id || 0) || undefined, app_name: `${createPayload.app_name}_updated`, - qimen_customer_id: `${createPayload.qimen_customer_id}_updated`, + qimen_customer_id: ignoredCustomerId, qimen_warehouse_code: `${createPayload.qimen_warehouse_code}_updated`, is_enabled: 0, }; @@ -366,7 +429,8 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { const updatedApiConfig = updateRes.body?.data?.api_config || updateRes.body?.data?.apiConfig || updateRes.body?.data?.qimen_config || null; assert.ok(updatedApiConfig, '更新后应返回 api_config'); - assert.equal(String(updatedApiConfig?.qimen_customer_id || ''), updatePayload.qimen_customer_id); + assert.equal(String(updatedApiConfig?.qimen_customer_id || ''), updatedCustomerId); + assert.notEqual(String(updatedApiConfig?.qimen_customer_id || ''), ignoredCustomerId); assert.equal(String(updatedApiConfig?.qimen_warehouse_code || ''), updatePayload.qimen_warehouse_code); assert.equal(Number(updatedApiConfig?.is_enabled), 0); @@ -378,7 +442,7 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.equal(verifyRes.body.code, 200); const verified = Array.isArray(verifyRes.body?.data?.list) ? verifyRes.body.data.list[0] : null; assert.ok(verified, '保存接口配置后应能查询到签约关系'); - assert.equal(String((verified?.api_config || verified?.apiConfig || {}).qimen_customer_id || ''), updatePayload.qimen_customer_id); + assert.equal(String((verified?.api_config || verified?.apiConfig || {}).qimen_customer_id || ''), updatedCustomerId); const configListRes = await invokeSystemMethod(`${METHOD_PREFIX}.listApiConfig`, { id: Number(candidate.id), @@ -389,7 +453,7 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.equal(Number(configListRes.body?.data?.contract_id || 0), Number(candidate.id)); assert.ok(Array.isArray(configListRes.body?.data?.list), '应返回接口配置列表'); assert.ok((configListRes.body?.data?.list || []).length >= 1, '保存后应至少返回一条接口配置'); - assert.equal(String(configListRes.body?.data?.list?.[0]?.qimen_customer_id || ''), updatePayload.qimen_customer_id); + assert.equal(String(configListRes.body?.data?.list?.[0]?.qimen_customer_id || ''), updatedCustomerId); const deleteRes = await invokeSystemMethod(`${METHOD_PREFIX}.deleteQimenConfig`, { id: Number(candidate.id), @@ -419,23 +483,74 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.ok(Array.isArray(emptyListRes.body?.data?.list), '删除后仍应返回列表结构'); assert.equal(Number(emptyListRes.body?.data?.total || 0), 0); } finally { - if (originalApiConfig) { - await invokeSystemMethod(`${METHOD_PREFIX}.saveApiConfig`, { - id: Number(candidate.id), - interface_type_id: Number(originalApiConfig.interface_type_id || 0) || undefined, - app_name: originalApiConfig.app_name, - qimen_app_key: originalApiConfig.qimen_app_key, - qimen_customer_id: originalApiConfig.qimen_customer_id, - qimen_warehouse_code: originalApiConfig.qimen_warehouse_code, - contact_person: originalApiConfig.contact_person, - contact_phone: originalApiConfig.contact_phone, - email: originalApiConfig.email, - is_enabled: Number(originalApiConfig.is_enabled || 0), - }, token, EXTRA_HEADERS); + try { + if (originalApiConfig) { + await invokeSystemMethod(`${METHOD_PREFIX}.saveApiConfig`, { + id: Number(candidate.id), + interface_type_id: Number(originalApiConfig.interface_type_id || 0) || undefined, + app_name: originalApiConfig.app_name, + qimen_app_key: originalApiConfig.qimen_app_key, + qimen_customer_id: originalApiConfig.qimen_customer_id, + qimen_warehouse_code: originalApiConfig.qimen_warehouse_code, + contact_person: originalApiConfig.contact_person, + contact_phone: originalApiConfig.contact_phone, + email: originalApiConfig.email, + is_enabled: Number(originalApiConfig.is_enabled || 0), + }, token, EXTRA_HEADERS); + } + } finally { + if (createdRestoreQimenApp) { + await removeQimenAppRecord(restoreAppKey); + } + + if (createdQimenApp) { + await removeQimenAppRecord(createPayload.qimen_app_key); + } } } }); + it('should fail to save api config when qimen_app_key has no matching qimen app record', async function() { + const listRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + page: 1, + page_size: 30, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const currentRole = String(listRes.body?.data?.current_subject?.role || ''); + if (currentRole !== 'warehouse') { + this.skip(); + } + + const candidates = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list : []; + const candidate = pickFixedTestRelation(candidates); + assert.ok(candidate, '未找到固定测试仓/测试货主对应关系,无法做接口配置失败回归'); + + const originalApiConfig = candidate.api_config || candidate.apiConfig || null; + const seed = Date.now(); + const payload = { + id: Number(candidate.id), + interface_type_id: Number((originalApiConfig && originalApiConfig.interface_type_id) || 0) || undefined, + app_name: `autotest_missing_qimen_app_${seed}`, + qimen_app_key: `autotest_missing_qimen_app_key_${seed}`, + qimen_warehouse_code: `autotest_missing_wh_${seed}`, + contact_person: 'autotest', + contact_phone: '13800138000', + email: `autotest_missing_${seed}@example.com`, + is_enabled: 1, + }; + + const res = await invokeSystemMethod(`${METHOD_PREFIX}.saveApiConfig`, payload, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /qimen_app_key|奇门应用配置/); + }); + it('should reject sign when counterparty is missing', async () => { const res = await invokeSystemMethod(`${METHOD_PREFIX}.sign`, { print_quantity: 0, diff --git a/test/app/controller/system.storeWarehouse.test.js b/test/app/controller/system.storeWarehouse.test.js index 5979154..7b9ae60 100644 --- a/test/app/controller/system.storeWarehouse.test.js +++ b/test/app/controller/system.storeWarehouse.test.js @@ -240,7 +240,7 @@ describe('test/app/controller/system.storeWarehouse.test.js', () => { assert.equal(res.status, 200); assert.equal(res.body.flag, 'failure'); assert.equal(Number(res.body.code), 400); - assert.match(String(res.body.message || ''), /interface_type_id|id|counterparty_id|store_id|warehouse_id|qimen_app_key|qimen_customer_id|qimen_warehouse_code/); + assert.match(String(res.body.message || ''), /interface_type_id|id|counterparty_id|store_id|warehouse_id|qimen_app_key|qimen_warehouse_code/); }); it('should expose standalone storeWarehouse.store.deleteQimenConfig parameter validation', async () => { diff --git a/test/app/lib/pdd_client.test.js b/test/app/lib/pdd_client.test.js new file mode 100644 index 0000000..d25037b --- /dev/null +++ b/test/app/lib/pdd_client.test.js @@ -0,0 +1,92 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const PddClient = require('../../../app/lib/pdd_client'); + +describe('test/app/lib/pdd_client.test.js', () => { + it('应从 config.pdd 读取凭据并发送签名后的 JSON 请求', async () => { + let requestOptions = null; + + const ctx = { + app: { + config: { + pdd: { + client_id: '1', + client_secret: 'testSecret', + }, + }, + }, + async curl(url, options) { + requestOptions = { url, options }; + return { + data: { + code: 0, + msg: 'ok', + }, + }; + }, + }; + + const client = new PddClient(ctx); + const result = await client.syncInvoke({ + type: 'pdd.order.number.list.get', + timestamp: '1480411125', + dataType: 'XML', + accessToken: 'asd78172s8ds9a921j9qqwda12312w1w21211', + bizParams: { + order_status: '1', + page: '1', + page_size: '10', + }, + }); + + assert.deepEqual(result, { code: 0, msg: 'ok' }); + assert.equal(requestOptions.url, 'https://gw-api.pinduoduo.com/api/router'); + assert.equal(requestOptions.options.method, 'POST'); + assert.equal(requestOptions.options.headers['Content-Type'], 'application/json'); + assert.equal(requestOptions.options.data.type, 'pdd.order.number.list.get'); + assert.equal(requestOptions.options.data.client_id, '1'); + assert.equal(requestOptions.options.data.sign, 'E4DE3ED21002510DED352819E7AE6775'); + }); + + it('request 入参中的 clientId 和 clientSecret 应覆盖默认配置', async () => { + let requestOptions = null; + + const ctx = { + app: { + config: { + pdd: { + client_id: 'default-client-id', + client_secret: 'default-secret', + }, + }, + }, + async curl(url, options) { + requestOptions = { url, options }; + return { + data: { + success: true, + }, + }; + }, + }; + + const client = new PddClient(ctx); + await client.asyncInvoke({ + type: 'pdd.order.number.list.get', + clientId: 'override-client-id', + clientSecret: 'override-secret', + timestamp: '1480411125', + dataType: 'XML', + accessToken: 'token-1', + bizParams: { + order_status: '1', + page: '1', + page_size: '10', + }, + }); + + 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 new file mode 100644 index 0000000..9c60d5e --- /dev/null +++ b/test/app/lib/pdd_sign.test.js @@ -0,0 +1,46 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const pddSign = require('../../../app/lib/pdd_sign'); + +describe('test/app/lib/pdd_sign.test.js', () => { + it('应按拼多多官方示例生成 sign', () => { + const result = pddSign.sign({ + access_token: 'asd78172s8ds9a921j9qqwda12312w1w21211', + client_id: '1', + data_type: 'XML', + type: 'pdd.order.number.list.get', + timestamp: '1480411125', + order_status: '1', + page: '1', + page_size: '10', + }, 'testSecret'); + + assert.equal(result.sign, 'E4DE3ED21002510DED352819E7AE6775'); + assert.equal( + result.signText, + 'testSecretaccess_tokenasd78172s8ds9a921j9qqwda12312w1w21211client_id1data_typeXMLorder_status1page1page_size10timestamp1480411125typepdd.order.number.list.gettestSecret' + ); + }); + + it('buildRequestBody 应自动补充 sign 并保留业务参数', () => { + const result = pddSign.buildRequestBody({ + type: 'pdd.order.number.list.get', + clientId: 1, + timestamp: 1480411125, + dataType: 'XML', + accessToken: 'asd78172s8ds9a921j9qqwda12312w1w21211', + bizParams: { + order_status: 1, + page: 1, + page_size: 10, + }, + clientSecret: 'testSecret', + }); + + assert.equal(result.requestBody.sign, 'E4DE3ED21002510DED352819E7AE6775'); + assert.equal(result.requestBody.client_id, 1); + 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/model/store_warehouse_print_quantity_log.test.js b/test/app/model/store_warehouse_print_quantity_log.test.js new file mode 100644 index 0000000..52c6622 --- /dev/null +++ b/test/app/model/store_warehouse_print_quantity_log.test.js @@ -0,0 +1,83 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +/** + * 创建可用于断言的 Sequelize 类型对象。 + * + * @param {string} sql SQL 类型描述 + * @return {{ sql: string, UNSIGNED?: { sql: string, toSql: Function }, toSql: Function }} 类型对象 + */ +function makeType(sql) { + return { + sql, + get UNSIGNED() { + return makeType(`${sql} UNSIGNED`); + }, + toSql() { + return this.sql; + }, + }; +} + +/** + * 创建加载模型所需的最小 Sequelize mock。 + * + * @return {{ BIGINT: Function, STRING: Function, TEXT: object, DATE: object, INTEGER: Function, literal: Function }} Sequelize mock + */ +function createSequelizeTypes() { + return { + BIGINT: length => makeType(`BIGINT(${length})`), + STRING: length => makeType(`VARCHAR(${length})`), + TEXT: makeType('TEXT'), + DATE: makeType('DATETIME'), + INTEGER: length => makeType(`INTEGER(${length})`), + literal: value => ({ value, type: 'literal' }), + }; +} + +/** + * 创建用于加载模型定义的最小 app mock。 + * + * @return {{ Sequelize: object, model: { define: Function } }} app mock + */ +function createApp() { + return { + Sequelize: createSequelizeTypes(), + model: { + define(name, attributes, options) { + return { + name, + rawAttributes: attributes, + options, + belongsTo() {}, + }; + }, + }, + }; +} + +describe('test/app/model/store_warehouse_print_quantity_log.test.js', () => { + it('should define print quantity log model options without paranoid mode', () => { + const app = createApp(); + const StoreWarehousePrintQuantityLog = require('../../../app/model/store_warehouse_print_quantity_log')(app); + + assert.equal(StoreWarehousePrintQuantityLog.options.tableName, 'wms_store_warehouse_print_quantity_log'); + assert.equal(StoreWarehousePrintQuantityLog.options.freezeTableName, true); + assert.equal(StoreWarehousePrintQuantityLog.options.timestamps, true); + assert.equal(StoreWarehousePrintQuantityLog.options.underscored, true); + assert.equal(StoreWarehousePrintQuantityLog.options.paranoid, false); + assert.equal(StoreWarehousePrintQuantityLog.options.createdAt, 'created_at'); + assert.equal(StoreWarehousePrintQuantityLog.options.updatedAt, 'updated_at'); + + assert.equal(StoreWarehousePrintQuantityLog.rawAttributes.id.type.toSql(), 'BIGINT(20) UNSIGNED'); + assert.equal(StoreWarehousePrintQuantityLog.rawAttributes.change_type.type.toSql(), 'VARCHAR(50)'); + assert.equal(StoreWarehousePrintQuantityLog.rawAttributes.reason.type.toSql(), 'TEXT'); + assert.equal(StoreWarehousePrintQuantityLog.rawAttributes.created_at.type.toSql(), 'DATETIME'); + assert.equal(StoreWarehousePrintQuantityLog.rawAttributes.balance_before.type.toSql(), 'INTEGER(11)'); + assert.deepEqual(StoreWarehousePrintQuantityLog.rawAttributes.created_at.defaultValue, { + value: 'CURRENT_TIMESTAMP', + type: 'literal', + }); + }); +}); diff --git a/test/app/service/systemMethods/index.test.js b/test/app/service/systemMethods/index.test.js new file mode 100644 index 0000000..9fb5bd1 --- /dev/null +++ b/test/app/service/systemMethods/index.test.js @@ -0,0 +1,103 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const IndexMethodService = require('../../../../app/service/systemMethods/index'); + +function createHarness() { + const calls = { + curl: 0, + }; + + const ctx = { + app: { + config: { + pdd: { + client_id: '1', + client_secret: 'testSecret', + }, + }, + }, + logger: { + error() {}, + }, + async curl(url, options) { + calls.curl += 1; + calls.request = { url, options }; + return { + data: { + success: true, + code: 0, + }, + }; + }, + }; + + const service = Object.create(IndexMethodService.prototype); + service.ctx = ctx; + service.app = ctx.app; + + return { + service, + ctx, + calls, + }; +} + +describe('test/app/service/systemMethods/index.test.js', () => { + it('应按拼多多官方示例参数生成签名并发起请求', async () => { + const { service, calls } = createHarness(); + + const result = await service.test({ + type: 'pdd.order.number.list.get', + timestamp: '1480411125', + dataType: 'XML', + accessToken: 'asd78172s8ds9a921j9qqwda12312w1w21211', + order_status: '1', + page: '1', + page_size: '10', + }); + + assert.equal(calls.curl, 1); + assert.equal(calls.request.url, 'https://gw-api.pinduoduo.com/api/router'); + assert.equal(calls.request.options.method, 'POST'); + assert.equal(calls.request.options.headers['Content-Type'], 'application/json'); + assert.equal(calls.request.options.data.sign, 'E4DE3ED21002510DED352819E7AE6775'); + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(result.data.requestBody.sign, 'E4DE3ED21002510DED352819E7AE6775'); + assert.deepEqual(result.data.response, { success: true, code: 0 }); + }); + + it('缺少 type 时应直接返回参数错误', async () => { + const { service, calls } = createHarness(); + + const result = await service.test({ + page: '1', + }); + + assert.equal(calls.curl, 0); + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 400); + assert.equal(result.message, 'type 不能为空'); + }); + + it('应兼容 access_token 等下划线参数命名', async () => { + const { service, calls } = createHarness(); + + const result = await service.test({ + type: 'pdd.order.number.list.get', + timestamp: '1480411125', + data_type: 'XML', + access_token: 'asd78172s8ds9a921j9qqwda12312w1w21211', + order_status: '1', + page: '1', + page_size: '10', + }); + + assert.equal(calls.curl, 1); + assert.equal(calls.request.options.data.access_token, 'asd78172s8ds9a921j9qqwda12312w1w21211'); + assert.equal(calls.request.options.data.sign, 'E4DE3ED21002510DED352819E7AE6775'); + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + }); +}); \ No newline at end of file diff --git a/test/app/service/systemMethods/order/pendingOrder.allocateExpressCode.test.js b/test/app/service/systemMethods/order/pendingOrder.allocateExpressCode.test.js index 35b8d4c..484bd12 100644 --- a/test/app/service/systemMethods/order/pendingOrder.allocateExpressCode.test.js +++ b/test/app/service/systemMethods/order/pendingOrder.allocateExpressCode.test.js @@ -16,6 +16,21 @@ function createAllocateExpressHarness(options = {}) { const orderDeliveryRows = Array.isArray(options.orderDeliveryRows) ? options.orderDeliveryRows : []; const calls = { operationLogs: [], + orderDeliveryUpdatePayload: null, + orderDeliveryUpdateWhere: null, + markWaybillAsyncOrdersAsErrorArgs: null, + }; + const orderDeliveryModel = { + async findAll() { + return orderDeliveryRows; + }, + async update(payload = {}, query = {}) { + calls.orderDeliveryUpdatePayload = payload; + calls.orderDeliveryUpdateWhere = query.where || null; + const ids = query && query.where && query.where.id && query.where.id[Sequelize.Op.in]; + const affectedRows = Array.isArray(ids) ? ids.length : 0; + return [ affectedRows ]; + }, }; const ctx = { app: { @@ -28,11 +43,7 @@ function createAllocateExpressHarness(options = {}) { model: { OrderDeliveryFactory: { async getCurrentModel() { - return { - async findAll() { - return orderDeliveryRows; - }, - }; + return orderDeliveryModel; }, }, }, @@ -61,6 +72,11 @@ function createAllocateExpressHarness(options = {}) { const pendingService = new PendingOrderService(ctx); const expressService = new ExpressService(ctx); + const originalMarkWaybillAsyncOrdersAsError = expressService.markWaybillAsyncOrdersAsError.bind(expressService); + expressService.markWaybillAsyncOrdersAsError = async (...args) => { + calls.markWaybillAsyncOrdersAsErrorArgs = args; + return await originalMarkWaybillAsyncOrdersAsError(...args); + }; ctx.service.systems.express = expressService; return { @@ -181,7 +197,7 @@ describe('test/app/service/systemMethods/order/pendingOrder.allocateExpressCode. ); }); - it('should only write failure logs when allocate pipeline throws', async () => { + it('should only rollback post_status for business_key=1 orders when allocate pipeline throws', async () => { const { pendingService, expressService, calls } = createAllocateExpressHarness(); expressService.createWaybillCodePipeline = async () => { @@ -191,18 +207,36 @@ describe('test/app/service/systemMethods/order/pendingOrder.allocateExpressCode. await assert.rejects( async () => await pendingService.allocateExpressCode({ orders: [ - { order_id: 201, business_key: 9901 }, + { order_id: 201, business_key: 1 }, { order_id: 202, business_key: 9902 }, + { order_id: 203, business_key: '1' }, + { order_id: 204, business_key: [ 2, '1' ] }, ], }), /平台接口异常/ ); - assert.equal(calls.operationLogs.length, 2); + assert.equal(calls.operationLogs.length, 4); assert.equal(calls.operationLogs[0].operationCode, 'ORDER_EXPRESS_ALLOCATE_FAILED'); assert.equal(calls.operationLogs[0].extras.message, '分配快递失败:平台接口异常'); assert.equal(calls.operationLogs[0].operator.id, null); assert.equal(calls.operationLogs[0].operator.name, 'system'); assert.equal(calls.operationLogs[1].businessId, '202'); + assert.equal(calls.operationLogs[2].businessId, '203'); + assert.equal(calls.operationLogs[3].businessId, '204'); + assert.ok(calls.markWaybillAsyncOrdersAsErrorArgs); + assert.deepEqual(calls.markWaybillAsyncOrdersAsErrorArgs[1], [ 201, 203, 204 ]); + assert.equal(calls.markWaybillAsyncOrdersAsErrorArgs[2], '平台接口异常'); + assert.deepEqual(calls.orderDeliveryUpdatePayload, { + post_status: 'error', + step: 3, + order_flag: '平台接口异常', + updated_at: calls.orderDeliveryUpdatePayload.updated_at, + }); + assert.deepEqual(calls.orderDeliveryUpdateWhere, { + id: { + [Sequelize.Op.in]: [ 201, 203, 204 ], + }, + }); }); }); diff --git a/test/app/service/systemMethods/order/wave.batchAllocateExpress.test.js b/test/app/service/systemMethods/order/wave.batchAllocateExpress.test.js index 3ccd985..d0a904e 100644 --- a/test/app/service/systemMethods/order/wave.batchAllocateExpress.test.js +++ b/test/app/service/systemMethods/order/wave.batchAllocateExpress.test.js @@ -1,6 +1,7 @@ 'use strict'; const assert = require('node:assert/strict'); +const { Op } = require('sequelize'); const WaveService = require('../../../../../app/service/systemMethods/order/wave'); @@ -14,9 +15,18 @@ const WaveService = require('../../../../../app/service/systemMethods/order/wave function createHarness(options = {}) { const cacheStore = new Map(); const orderIds = Array.isArray(options.orderIds) ? options.orderIds : []; + const missingBusinessKeyColumn = Boolean(options.missingBusinessKeyColumn); + const configuredOrderRows = Array.isArray(options.orderRows) ? options.orderRows : []; + const orderRows = configuredOrderRows.length > 0 + ? configuredOrderRows + : orderIds.map(id => ({ id, business_key: 1 })); + const pipelineError = options.pipelineError || null; const capture = { orderFindAllAttributes: [], pipelineOrders: [], + orderUpdatePayload: null, + orderUpdateWhere: null, + markWaybillAsyncOrdersAsErrorArgs: null, }; const ctx = { @@ -43,11 +53,31 @@ function createHarness(options = {}) { express: { async createWaybillCodePipeline(orders) { capture.pipelineOrders = Array.isArray(orders) ? orders : []; + if (pipelineError) { + throw pipelineError; + } return { code: 200, message: '分配完成', }; }, + async markWaybillAsyncOrdersAsError(orderModel, orderIds, errorMessage, extraWhere = {}) { + capture.markWaybillAsyncOrdersAsErrorArgs = { + orderIds, + errorMessage, + extraWhere, + }; + await orderModel.update({ + post_status: 'error', + }, { + where: { + ...extraWhere, + id: { + [Op.in]: orderIds, + }, + }, + }); + }, }, }, }, @@ -58,11 +88,24 @@ function createHarness(options = {}) { async findAll(query = {}) { const attributes = Array.isArray(query.attributes) ? query.attributes : []; capture.orderFindAllAttributes.push(attributes); - if (attributes.includes('business_key')) { + if (attributes.includes('business_key') && missingBusinessKeyColumn) { throw new Error("Unknown column 'business_key' in 'field list'"); } - return orderIds.map(id => ({ id })); + if (attributes.includes('business_key')) { + return orderRows.map(row => ({ + id: Number(row && row.id || 0), + business_key: row && row.business_key, + })); + } + + return orderRows.map(row => ({ id: Number(row && row.id || 0) })); + }, + async update(payload = {}, query = {}) { + capture.orderUpdatePayload = payload; + capture.orderUpdateWhere = query.where || null; + const rollbackOrderIds = query && query.where && query.where.id && query.where.id[Op.in]; + return [ Array.isArray(rollbackOrderIds) ? rollbackOrderIds.length : 0 ]; }, }); @@ -73,9 +116,11 @@ function createHarness(options = {}) { } describe('test/app/service/systemMethods/order/wave.batchAllocateExpress.test.js', () => { - it('should fallback to id-only query when business_key column is missing and keep task success', async () => { + it('should skip post_status rollback when business_key column is missing and pipeline fails', async () => { const { service, capture } = createHarness({ orderIds: [ 101, 102 ], + missingBusinessKeyColumn: true, + pipelineError: new Error('connect ECONNREFUSED 127.0.0.1:9100'), }); await service.runBatchAllocateExpressTask({ @@ -85,18 +130,69 @@ describe('test/app/service/systemMethods/order/wave.batchAllocateExpress.test.js }); const progress = await service.getBatchAllocateExpressTaskProgress('task_missing_business_key_column'); - assert.equal(progress.state, 'success'); - assert.equal(progress.error, ''); - assert.equal(progress.error_code, ''); + assert.equal(progress.state, 'failed'); + assert.equal(progress.error_code, 'WAVE_BATCH_ALLOCATE_EXPRESS_FAILED'); assert.equal(progress.total_order_count, 2); - assert.equal(progress.success_order_count, 2); + assert.equal(progress.success_order_count, 0); + assert.equal(progress.failed_order_count, 2); assert.equal(capture.orderFindAllAttributes.length, 2); assert.deepEqual(capture.orderFindAllAttributes[0], [ 'id', 'business_key' ]); assert.deepEqual(capture.orderFindAllAttributes[1], [ 'id' ]); assert.deepEqual(capture.pipelineOrders, [ - { order_id: 101, business_key: 1 }, - { order_id: 102, business_key: 1 }, + { order_id: 101, business_key: 0 }, + { order_id: 102, business_key: 0 }, ]); + assert.equal(capture.markWaybillAsyncOrdersAsErrorArgs, null); + assert.equal(capture.orderUpdatePayload, null); + assert.equal(capture.orderUpdateWhere, null); + }); + + it('should only rollback business_key=1 orders when pipeline throws', async () => { + const { service, capture } = createHarness({ + orderRows: [ + { id: 301, business_key: 1 }, + { id: 302, business_key: 2 }, + { id: 303, business_key: '1' }, + ], + pipelineError: new Error('connect ECONNREFUSED 127.0.0.1:9100'), + }); + + await service.runBatchAllocateExpressTask({ + taskId: 'task_pipeline_error', + warehouseId: 100000, + waveIds: [ 99 ], + }); + + const progress = await service.getBatchAllocateExpressTaskProgress('task_pipeline_error'); + assert.equal(progress.state, 'failed'); + assert.equal(progress.total_order_count, 3); + assert.equal(progress.processed_order_count, 3); + assert.equal(progress.success_order_count, 0); + assert.equal(progress.failed_order_count, 3); + assert.equal(progress.progress_percent, 100); + assert.equal(progress.error_code, 'WAVE_BATCH_ALLOCATE_EXPRESS_FAILED'); + + assert.ok(capture.markWaybillAsyncOrdersAsErrorArgs); + assert.deepEqual(capture.markWaybillAsyncOrdersAsErrorArgs.orderIds, [ 301, 303 ]); + assert.equal(capture.markWaybillAsyncOrdersAsErrorArgs.errorMessage, 'connect ECONNREFUSED 127.0.0.1:9100'); + assert.deepEqual(capture.markWaybillAsyncOrdersAsErrorArgs.extraWhere, { + warehouse_id: 100000, + wave_id: { + [Op.in]: [ 99 ], + }, + }); + + assert.deepEqual(capture.orderUpdatePayload, { + post_status: 'error', + }); + assert.ok(capture.orderUpdateWhere); + assert.equal(capture.orderUpdateWhere.warehouse_id, 100000); + assert.deepEqual(capture.orderUpdateWhere.wave_id, { + [Op.in]: [ 99 ], + }); + assert.deepEqual(capture.orderUpdateWhere.id, { + [Op.in]: [ 301, 303 ], + }); }); }); diff --git a/test/app/service/systemMethods/setting/expressInterface.test.js b/test/app/service/systemMethods/setting/expressInterface.test.js index a04bedd..9da9f95 100644 --- a/test/app/service/systemMethods/setting/expressInterface.test.js +++ b/test/app/service/systemMethods/setting/expressInterface.test.js @@ -180,6 +180,9 @@ describe('test/app/service/systemMethods/setting/expressInterface.test.js', () = townName: '张江镇', isPickup: 1, shipperNo: 'SHIP-001', + extData: { + mode: 'A4', + }, extra: { keep: true, }, @@ -194,6 +197,9 @@ describe('test/app/service/systemMethods/setting/expressInterface.test.js', () = town_name: '粤海街道', ispickup: 0, shipperno: 'SHIP-002', + ext_data: { + mode: 'thermal', + }, }); const deleteResult = await service.delete({ id: 11, @@ -215,6 +221,9 @@ describe('test/app/service/systemMethods/setting/expressInterface.test.js', () = town_name: '张江镇', ispickup: 1, shipperno: 'SHIP-001', + ext_data: { + mode: 'A4', + }, extra: { keep: true, }, @@ -230,6 +239,9 @@ describe('test/app/service/systemMethods/setting/expressInterface.test.js', () = town_name: '粤海街道', ispickup: 0, shipperno: 'SHIP-002', + ext_data: { + mode: 'thermal', + }, touched: true, }); assert.deepEqual(calls.delete[0], { diff --git a/test/app/service/systemMethods/storeWarehouse/store.test.js b/test/app/service/systemMethods/storeWarehouse/store.test.js index 90ea02d..1824e27 100644 --- a/test/app/service/systemMethods/storeWarehouse/store.test.js +++ b/test/app/service/systemMethods/storeWarehouse/store.test.js @@ -1,17 +1,21 @@ 'use strict'; const assert = require('node:assert/strict'); +const { Op } = require('sequelize'); const StoreWarehouseStoreService = require('../../../../../app/service/systemMethods/storeWarehouse/store'); function createContext(options = {}) { const { includeList = true, includeSign = true, + includeQueryPrintQuantityLogs = true, } = options; const actionCalls = { list: [], sign: [], + queryPrintQuantityLogs: [], + prepareWhereContext: 0, }; const storeWarehouse = {}; @@ -36,9 +40,27 @@ function createContext(options = {}) { }; } + if (includeQueryPrintQuantityLogs) { + storeWarehouse.queryPrintQuantityLogs = async function queryPrintQuantityLogs(data) { + actionCalls.queryPrintQuantityLogs.push(data); + return { + code: 200, + data: { + list: [{ id: 1 }], + total: 1, + page: Number((data.pagination && data.pagination.page) || 1), + page_size: Number((data.pagination && data.pagination.page_size) || 20), + }, + }; + }; + } + const ctx = { app: { config: {}, + Sequelize: { + Op, + }, }, service: { systems: { @@ -154,4 +176,88 @@ describe('test/app/service/systemMethods/storeWarehouse/store.test.js', () => { assert.equal(actionCalls.list.length, 0); assert.equal(actionCalls.sign.length, 0); }); + + it('should normalize where and call queryPrintQuantityLogs', async () => { + const { actionCalls, ctx } = createContext(); + const service = new StoreWarehouseStoreService(ctx); + const originalPrepareWhereContext = service.prepareWhereContext; + service.prepareWhereContext = function prepareWhereContext(data, options) { + actionCalls.prepareWhereContext += 1; + return originalPrepareWhereContext.call(this, data, options); + }; + + const result = await service.queryPrintQuantityLogs({ + store_id: 1000001, + where: { + change_type: 'manual_adjust', + }, + pagination: { + page: 2, + page_size: 30, + }, + unrelated_field: 'ignored', + }); + + assert.equal(actionCalls.queryPrintQuantityLogs.length, 1); + assert.deepEqual(actionCalls.queryPrintQuantityLogs[0], { + store_id: 1000001, + where: { + change_type: { + operator: 'eq', + value: 'manual_adjust', + }, + }, + pagination: { + page: 2, + page_size: 30, + }, + }); + assert.equal(actionCalls.prepareWhereContext, 1); + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(Number(result.code), 200); + assert.deepEqual(result.data, { + list: [{ id: 1 }], + total: 1, + page: 2, + page_size: 30, + }); + }); + + it('should ignore top-level page fields without pagination object', async () => { + const { actionCalls, ctx } = createContext(); + const service = new StoreWarehouseStoreService(ctx); + + await service.queryPrintQuantityLogs({ + store_id: 1000001, + page: 9, + page_size: 99, + }); + + assert.equal(actionCalls.queryPrintQuantityLogs.length, 1); + assert.deepEqual(actionCalls.queryPrintQuantityLogs[0], { + store_id: 1000001, + where: {}, + pagination: { + page: undefined, + page_size: undefined, + }, + }); + }); + + it('should keep the failure fallback for missing queryPrintQuantityLogs method', async () => { + const { actionCalls, ctx } = createContext({ + includeQueryPrintQuantityLogs: false, + }); + const service = new StoreWarehouseStoreService(ctx); + + const result = await service.queryPrintQuantityLogs({ + store_id: 1000001, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '查询面单余额变更日志失败'); + assert.equal(Number(result.code), 500); + assert.equal(actionCalls.queryPrintQuantityLogs.length, 0); + }); }); diff --git a/test/app/service/systems/order_print.getWavePlatformPrintData.test.js b/test/app/service/systems/order_print.getWavePlatformPrintData.test.js index 290a319..d1beb00 100644 --- a/test/app/service/systems/order_print.getWavePlatformPrintData.test.js +++ b/test/app/service/systems/order_print.getWavePlatformPrintData.test.js @@ -889,6 +889,8 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' total_waves: 2, total_orders: 3, total_platforms: 3, + locked_count: 0, + total_locked_orders: 0, }); assert.equal(result.waveGroups.length, 2); @@ -1418,7 +1420,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' assert.ok(!printText.includes('旧商品名-不应展示')); }); - it('should return locked result when any order print_lock_status is not none', async () => { + it('should return locked_wave_groups when all orders are locked', async () => { const service = createOrderPrintServiceHarness(); service.queryWavesByIds = async () => ([ @@ -1448,10 +1450,107 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' }); assert.equal(result.summary.total_orders, 0); + assert.equal(result.summary.total_locked_orders, 1); assert.equal(result.summary.locked_count, 1); assert.equal(result.locked_count, 1); assert.deepEqual(result.waveGroups, []); + assert.equal(result.locked_wave_groups.length, 1); + assert.equal(result.locked_wave_groups[0].wave_id, 50); + assert.equal(result.locked_wave_groups[0].order_count, 1); + assert.equal(result.locked_wave_groups[0].platforms.length, 1); + assert.equal(result.locked_wave_groups[0].platforms[0].order_count, 1); + assert.equal(result.locked_wave_groups[0].platforms[0].orders[0].status, 'locked'); + assert.equal(result.locked_wave_groups[0].platforms[0].orders[0].status_text, '已锁定'); assert.equal(result.locked_orders[0].order_id, 501); assert.equal(result.locked_orders[0].print_lock_status, 'warehouse'); + assert.equal(result.locked_orders[0].status, 'locked'); + assert.equal(result.locked_orders[0].status_text, '已锁定'); + }); + + it('should separate locked and unlocked orders into waveGroups and locked_wave_groups', async () => { + const service = createOrderPrintServiceHarness(); + + service.queryWavesByIds = async () => ([ + { wave_id: 60, wave_no: 'W060' }, + ]); + service.queryOrdersByWaveIds = async () => ([ + { + id: 601, + wave_id: 60, + wave_no: 'W060', + warehouse_id: 100000, + store_id: 1, + delivery_order_code: 'O601', + post_status: 'fin', + print_lock_status: 'warehouse', + sys_platform_code: 'jd', + }, + { + id: 602, + wave_id: 60, + wave_no: 'W060', + warehouse_id: 100000, + store_id: 1, + delivery_order_code: 'O602', + post_status: 'fin', + print_lock_status: 'none', + sys_platform_code: 'jd', + }, + ]); + service.filterFullyAssignedExpressWaves = () => ({ + validWaveIds: [ 60 ], + filteredWaveIds: [], + }); + service.queryOrderExpressByOrderIds = async orderIds => { + assert.deepEqual(orderIds, [ 602 ]); + return [ + { + order_id: 602, + business_key: 1, + waybill_code: 'WB602', + }, + ]; + }; + 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.resolvePrintPlatformCode = orderRow => String(orderRow && orderRow.sys_platform_code || '').trim(); + 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: '京东', + print_data: { + order_id: Number(orderRow.id), + status: 'ready', + }, + }); + + const result = await service.getWavePlatformPrintData({ + waveIds: [ 60 ], + warehouseId: 100000, + }); + + assert.equal(result.waveGroups.length, 1); + assert.deepEqual(result.waveGroups[0].platforms[0].order_ids, [ 602 ]); + assert.equal(result.waveGroups[0].platforms[0].orders[0].status, 'ready'); + + assert.equal(result.locked_wave_groups.length, 1); + assert.deepEqual(result.locked_wave_groups[0].platforms[0].order_ids, [ 601 ]); + assert.equal(result.locked_wave_groups[0].platforms[0].orders[0].status, 'locked'); + assert.equal(result.locked_wave_groups[0].platforms[0].orders[0].status_text, '已锁定'); + + assert.equal(result.locked_count, 1); + assert.equal(result.locked_orders.length, 1); + assert.equal(result.locked_orders[0].order_id, 601); + assert.equal(result.summary.total_orders, 1); + assert.equal(result.summary.locked_count, 1); + assert.equal(result.summary.total_locked_orders, 1); }); }); diff --git a/test/app/service/systems/platform.test.js b/test/app/service/systems/platform.test.js index 961975a..8ea6b49 100644 --- a/test/app/service/systems/platform.test.js +++ b/test/app/service/systems/platform.test.js @@ -15,6 +15,7 @@ function createPlatformServiceHarness(options = {}) { findAll: 0, platformFindAll: 0, platformSettingFindAll: 0, + qimenAppFindAll: 0, getCache: 0, setCache: 0, }; @@ -62,6 +63,17 @@ function createPlatformServiceHarness(options = {}) { ]; }, }, + QimenApp: { + async findAll(query) { + calls.findAll += 1; + calls.qimenAppFindAll += 1; + calls.qimenAppFindAllQuery = query; + return options.qimenAppRows || [ + { id: 1, name: '奇门应用A', app_key: 'app-key-a' }, + { id: 2, name: '奇门应用B', app_key: 'app-key-b' }, + ]; + }, + }, }, logger: { info() {}, @@ -276,4 +288,79 @@ describe('test/app/service/systems/platform.test.js', () => { { 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' }, + ]; + const { ctx, calls } = createPlatformServiceHarness({ + cachedValue, + }); + const methodService = new IndexMethodService(ctx); + + const result = await methodService.getQimenAppList(); + + assert.equal(calls.getCache, 1); + assert.equal(calls.qimenAppFindAll, 0); + assert.equal(calls.setCache, 0); + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(result.code, 200); + assert.deepEqual({ + list: result.list, + total: result.total, + code: result.code, + }, { + list: cachedValue, + total: 1, + code: 200, + }); + }); + + it('should query qimen app list and cache it for 300 seconds on cache miss', async () => { + const qimenAppRows = [ + { + get() { + return { id: 2, name: '奇门应用B', app_key: 'app-key-b', created_at: '2024-01-01', updated_at: '2024-01-02' }; + }, + }, + { + get() { + return { id: 3, name: '奇门应用C', app_key: 'app-key-c', created_at: '2024-01-03', updated_at: '2024-01-04' }; + }, + }, + ]; + const { ctx, calls } = createPlatformServiceHarness({ qimenAppRows }); + const methodService = new IndexMethodService(ctx); + + const result = await methodService.getQimenAppList(); + + assert.equal(calls.getCache, 1); + assert.equal(calls.qimenAppFindAll, 1); + assert.equal(calls.setCache, 1); + assert.deepEqual(calls.qimenAppFindAllQuery, { + attributes: [ 'id', 'name', 'app_key' ], + order: [[ 'id', 'ASC' ]], + }); + assert.deepEqual(calls.cachePayload, { + cacheKey: 'index:qimenAppList', + value: [ + { id: 2, name: '奇门应用B', app_key: 'app-key-b' }, + { id: 3, name: '奇门应用C', app_key: 'app-key-c' }, + ], + ttl: 300, + }); + assert.deepEqual({ + list: result.list, + total: result.total, + code: result.code, + }, { + list: [ + { id: 2, name: '奇门应用B', app_key: 'app-key-b' }, + { id: 3, name: '奇门应用C', app_key: 'app-key-c' }, + ], + total: 2, + code: 200, + }); + }); }); diff --git a/test/app/service/systems/setting/expressInterface.test.js b/test/app/service/systems/setting/expressInterface.test.js index 7e07f38..10aa213 100644 --- a/test/app/service/systems/setting/expressInterface.test.js +++ b/test/app/service/systems/setting/expressInterface.test.js @@ -160,6 +160,7 @@ function createHarness(options = {}) { town_name: {}, ispickup: {}, shipperno: {}, + ext_data: {}, }; const expressRows = options.expressRows || [ @@ -340,6 +341,10 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { site_code: 'SITE-01', product_type: 'STD', shop_name: '旗舰店', + ext_data: { + print_mode: 'A4', + enabled: true, + }, }, ], count: 1, @@ -365,6 +370,10 @@ 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.deepEqual(result.data.list[0].ext_data, { + print_mode: 'A4', + enabled: true, + }); assert.equal(Array.isArray(calls.findAndCountAllQuery.include), true); assert.equal(calls.findAndCountAllQuery.include.length, 1); assert.equal(result.data.list[0].express.name, '顺丰'); @@ -555,6 +564,10 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { town_name: '望京街道', ispickup: 1, shipperno: 'SNO-001', + extData: { + retry: 2, + channel: 'polyapi', + }, }); assert.equal(calls.createPayload.warehouse_id, 100000); @@ -571,6 +584,14 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(result.data.town_name, '望京街道'); assert.equal(result.data.ispickup, 1); assert.equal(result.data.shipperno, 'SNO-001'); + assert.deepEqual(calls.createPayload.ext_data, { + retry: 2, + channel: 'polyapi', + }); + assert.deepEqual(result.data.ext_data, { + retry: 2, + channel: 'polyapi', + }); assert.equal(result.data.express.name, '京东快递'); assert.equal(Object.prototype.hasOwnProperty.call(result.data, 'express_platform'), false); assert.equal(calls.cacheDeletes.includes('express_interface:warehouse:100000:platform:TB'), true); @@ -631,6 +652,9 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { town_name: '张江镇', ispickup: 0, shipperno: 'SHIPPER-NEW', + ext_data: { + print_mode: 'thermal', + }, }); assert.equal(calls.findOneCalls.length >= 1, true); @@ -646,7 +670,13 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(calls.updatePayload.updates.town_name, '张江镇'); assert.equal(calls.updatePayload.updates.ispickup, 0); assert.equal(calls.updatePayload.updates.shipperno, 'SHIPPER-NEW'); + assert.deepEqual(calls.updatePayload.updates.ext_data, { + print_mode: 'thermal', + }); assert.equal(result.data.name, '顺丰接口-更新'); + assert.deepEqual(result.data.ext_data, { + print_mode: 'thermal', + }); assert.equal(result.data.express.name, '顺丰'); assert.equal(Object.prototype.hasOwnProperty.call(result.data, 'express_platform'), false); assert.equal(calls.cacheDeletes.includes('express_interface:warehouse:100000:platform:TB'), true); @@ -666,6 +696,25 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(calls.cacheDeletes.includes('express_interface:warehouse:100000:platform:WX'), true); }); + it('should allow updating ext_data only', async () => { + const { ctx, calls } = createHarness(); + const service = new SettingExpressInterfaceService(ctx); + + const result = await service.update({ + id: 11, + extData: { + custom: 'value', + level: 1, + }, + }); + + assert.equal(result.code, 200); + assert.deepEqual(calls.updatePayload.updates.ext_data, { + custom: 'value', + level: 1, + }); + }); + 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/stock_store.exportWarehouseStock.test.js b/test/app/service/systems/stock_store.exportWarehouseStock.test.js index 3b6ebd2..2a0618c 100644 --- a/test/app/service/systems/stock_store.exportWarehouseStock.test.js +++ b/test/app/service/systems/stock_store.exportWarehouseStock.test.js @@ -52,41 +52,41 @@ function createHarness() { const service = new StockStoreService(ctx); - service.getWarehouseStock = async function getWarehouseStock(where, pageParams, sortParams) { - captured.getWarehouseStockCalls.push({ where, pageParams, sortParams }); - return { - code: 200, - data: { - list: [ - { - id: 1, - item_code: 'SKU-001', - goods_code: 'GC-001', - item_name: '测试商品', - brand_name: '测试品牌', - sku_property: '10kg/箱', - stock_unit: '箱', - tag_price: '99.90', - retail_price: '89.90', - gross_weight: '12.5', - store_id: 100000, - barcodes: [ '690000000001' ], - quantity: 10, - locked_quantity: 2, - available_quantity: 8, - lock_rate_display: '20%', - create_at_display: '2026-05-17 10:00:00', - update_at_display: '2026-05-17 11:00:00', - }, - ], - pagination: { - hasNext: false, - }, - }, - }; - }; - + service.getWarehouseStock = async function getWarehouseStock(where, pageParams, sortParams) { + captured.getWarehouseStockCalls.push({ where, pageParams, sortParams }); return { + code: 200, + data: { + list: [ + { + id: 1, + item_code: 'SKU-001', + goods_code: 'GC-001', + item_name: '测试商品', + brand_name: '测试品牌', + sku_property: '10kg/箱', + stock_unit: '箱', + tag_price: '99.90', + retail_price: '89.90', + gross_weight: '12.5', + store_id: 100000, + barcodes: [ '690000000001' ], + quantity: 10, + locked_quantity: 2, + available_quantity: 8, + lock_rate_display: '20%', + create_at_display: '2026-05-17 10:00:00', + update_at_display: '2026-05-17 11:00:00', + }, + ], + pagination: { + hasNext: false, + }, + }, + }; + }; + + return { service, captured, }; @@ -119,4 +119,4 @@ describe('test/app/service/systems/stock_store.exportWarehouseStock.test.js', () assert.equal(captured.uploadOptions.sheets[0].columns[0].header, 'SKU'); assert.equal(captured.uploadOptions.sheets[0].columns[2].header, '货物编码'); }); -}); \ No newline at end of file +}); diff --git a/test/app/service/systems/store_warehouse.listApiConfig.test.js b/test/app/service/systems/store_warehouse.listApiConfig.test.js new file mode 100644 index 0000000..2348d7a --- /dev/null +++ b/test/app/service/systems/store_warehouse.listApiConfig.test.js @@ -0,0 +1,132 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StoreWarehouseService = require('../../../../app/service/systems/store_warehouse'); + +/** + * 构造 listApiConfig 测试上下文。 + * + * @param {Object} [options={}] 测试选项。 + * @return {{service: StoreWarehouseService, capture: object}} 服务实例与埋点数据。 + */ +function createListApiConfigHarness(options = {}) { + const relation = { + id: Number(options.relationId || 88), + warehouse_id: Number(options.warehouseId || 100000), + }; + const capture = { + apiAppFindAllArgs: [], + qimenAppFindAllArgs: [], + }; + + const rows = options.rows || []; + const qimenApps = options.qimenApps || []; + + const ctx = { + app: { + config: {}, + }, + model: { + ApiApp: { + async findAll(args = {}) { + capture.apiAppFindAllArgs.push(args); + return rows.map(item => ({ + ...item, + get({ plain } = {}) { + if (plain) { + return { + ...item, + }; + } + return this; + }, + })); + }, + }, + QimenApp: { + async findAll(args = {}) { + capture.qimenAppFindAllArgs.push(args); + const appKeys = Array.isArray(args.where?.app_key) ? args.where.app_key : []; + return qimenApps.filter(item => appKeys.includes(item.app_key)); + }, + }, + InterfaceType: {}, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + const service = new StoreWarehouseService(ctx); + service.getCurrentSubject = async () => ({ role: 'warehouse' }); + service.findScopedRelation = async () => relation; + service.serializeRelation = result => ({ + id: Number(result.id || relation.id), + warehouse_id: Number(result.warehouse_id || relation.warehouse_id), + }); + + return { + service, + capture, + }; +} + +describe('test/app/service/systems/store_warehouse.listApiConfig.test.js', () => { + it('should return erp_name for qimen api config items only', async () => { + const { service, capture } = createListApiConfigHarness({ + rows: [ + { + id: 321, + interface_type_id: 7, + contract_id: 88, + app_name: '奇门接口配置', + qimen_app_key: 'qm-app-key-1', + qimen_customer_id: 'customer-1', + qimen_warehouse_code: 'QM_WH_1', + is_enabled: 1, + interface_type: { + id: 7, + interface_code: 'qimen_wms', + interface_name: '奇门 WMS', + interface_category: 'QM_WMS', + }, + }, + { + id: 322, + interface_type_id: 8, + contract_id: 88, + app_name: '开放接口配置', + self_app_key: 'open-app-key-1', + is_enabled: 1, + interface_type: { + id: 8, + interface_code: 'open_api', + interface_name: '开放接口', + interface_category: 'OPEN_API', + }, + }, + ], + qimenApps: [ + { + app_key: 'qm-app-key-1', + name: '聚水潭', + }, + ], + }); + + const result = await service.listApiConfig({ + id: 88, + }); + + assert.equal(Number(result.code), 200); + assert.equal(Array.isArray(result.data?.list), true); + assert.equal(String(result.data.list[0]?.erp_name || ''), '聚水潭'); + assert.equal(String(result.data.list[1]?.erp_name || ''), ''); + assert.equal(capture.qimenAppFindAllArgs.length, 1); + assert.deepEqual(capture.qimenAppFindAllArgs[0].where, { + app_key: [ 'qm-app-key-1' ], + }); + }); +}); \ No newline at end of file diff --git a/test/app/service/systems/store_warehouse.queryPrintQuantityLogs.test.js b/test/app/service/systems/store_warehouse.queryPrintQuantityLogs.test.js new file mode 100644 index 0000000..b87afe8 --- /dev/null +++ b/test/app/service/systems/store_warehouse.queryPrintQuantityLogs.test.js @@ -0,0 +1,196 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StoreWarehouseService = require('../../../../app/service/systems/store_warehouse'); +const { Op } = require('sequelize'); +const { parseWhereConditions } = require('../../../../app/lib/query_condition_parser'); + +function createHarness(options = {}) { + const { + currentSubjectStoreId = 100000, + currentSubjectProject = 'warehouse', + count = 3, + rows = [], + } = options; + + const calls = { + findAndCountAllArgs: null, + }; + + const defaultRows = rows.length ? rows : [ + { + id: 11, + contract_id: 88, + store_id: 1000001, + warehouse_id: 100000, + change_type: 'manual_adjust', + business_type: 'order_express', + business_id: 123, + change_quantity: -5, + balance_before: 20, + balance_after: 15, + reason: '测试扣减', + operator_id: 9001, + created_by: 9001, + created_at: '2026-05-20 10:00:00', + updated_at: '2026-05-20 10:00:00', + }, + ]; + + const ctx = { + app: { + config: {}, + Sequelize: { + Op, + }, + }, + user: { + store_id: currentSubjectStoreId, + id: 10001, + }, + model: { + Store: { + async findOne({ where }) { + if (Number(where.id) !== Number(currentSubjectStoreId)) { + return null; + } + return { + id: currentSubjectStoreId, + company_name: '当前主体', + project: currentSubjectProject, + status: 1, + }; + }, + }, + StoreWarehousePrintQuantityLog: { + async findAndCountAll(args = {}) { + calls.findAndCountAllArgs = args; + return { + rows: defaultRows, + count, + }; + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + ctx.app.model = ctx.model; + + return { + service: new StoreWarehouseService(ctx), + calls, + }; +} + +describe('test/app/service/systems/store_warehouse.queryPrintQuantityLogs.test.js', () => { + it('should query print quantity logs by store_id with pagination for warehouse subject', async () => { + const { service, calls } = createHarness({ + currentSubjectStoreId: 100000, + currentSubjectProject: 'warehouse', + count: 3, + }); + + const result = await service.queryPrintQuantityLogs({ + store_id: 1000001, + pagination: { + page: 2, + page_size: 1, + }, + }); + + assert.deepEqual(calls.findAndCountAllArgs.where, { + store_id: 1000001, + warehouse_id: 100000, + }); + assert.deepEqual(calls.findAndCountAllArgs.order, [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]]); + assert.equal(calls.findAndCountAllArgs.offset, 1); + assert.equal(calls.findAndCountAllArgs.limit, 1); + + assert.equal(result.code, 200); + assert.equal(result.data.pagination.total, 3); + assert.equal(result.data.pagination.page, 2); + assert.equal(result.data.pagination.pageSize, 1); + assert.equal(result.data.pagination.totalPages, 3); + assert.equal(result.data.pagination.hasNext, true); + assert.equal(result.data.pagination.hasPrevious, true); + assert.equal(result.data.list.length, 1); + assert.equal(result.data.list[0].id, 11); + assert.equal(result.data.list[0].store_id, 1000001); + }); + + it('should merge whereParsed dynamic conditions into findAndCountAll where', async () => { + const { service, calls } = createHarness({ + currentSubjectStoreId: 100000, + currentSubjectProject: 'warehouse', + count: 1, + }); + const where = { + created_at: { + operator: 'between', + type: 'daterange', + value: [ '2026-05-01', '2026-05-20' ], + }, + }; + + service.ctx.whereParsed = parseWhereConditions({ + where, + app: service.ctx.app, + }).result; + + await service.queryPrintQuantityLogs({ + store_id: 1000001, + where, + pagination: { + page: 1, + page_size: 20, + }, + }); + + assert.deepEqual(calls.findAndCountAllArgs.where, { + store_id: 1000001, + warehouse_id: 100000, + [Op.and]: [ + { + created_at: { + [Op.between]: [ '2026-05-01 00:00:00', '2026-05-20 23:59:59' ], + }, + }, + ], + }); + }); + + it('should ignore top-level page fields and fallback to default pagination', async () => { + const { service, calls } = createHarness({ + currentSubjectStoreId: 100000, + currentSubjectProject: 'warehouse', + count: 1, + }); + + await service.queryPrintQuantityLogs({ + store_id: 1000001, + page: 5, + page_size: 30, + }); + + assert.equal(calls.findAndCountAllArgs.offset, 0); + assert.equal(calls.findAndCountAllArgs.limit, 20); + }); + + it('should reject when store_id is invalid', async () => { + const { service } = createHarness({ + currentSubjectStoreId: 100000, + currentSubjectProject: 'warehouse', + }); + + await assert.rejects(async () => { + await service.queryPrintQuantityLogs({ + store_id: 0, + }); + }, /store_id 参数不能为空/); + }); +}); diff --git a/test/app/service/systems/store_warehouse.saveApiConfig.test.js b/test/app/service/systems/store_warehouse.saveApiConfig.test.js new file mode 100644 index 0000000..19dff93 --- /dev/null +++ b/test/app/service/systems/store_warehouse.saveApiConfig.test.js @@ -0,0 +1,261 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const StoreWarehouseService = require('../../../../app/service/systems/store_warehouse'); + +/** + * 构造 saveApiConfig 测试上下文。 + * + * @param {Object} [options={}] 测试选项。 + * @return {{service: StoreWarehouseService, capture: object, transaction: object}} 服务实例与埋点数据。 + */ +function createSaveApiConfigHarness(options = {}) { + const interfaceType = { + id: Number(options.interfaceTypeId || 7), + interface_category: options.interfaceCategory || 'QM_WMS', + }; + const relation = { + id: Number(options.relationId || 88), + warehouse_id: Number(options.warehouseId || 100000), + }; + const capture = { + qimenAppFindOneArgs: [], + apiAppFindOneArgs: [], + apiAppCreatePayload: null, + apiAppUpdatePayload: null, + operationLogPayload: null, + clearedConfigs: null, + }; + const transaction = { + committed: false, + rolledBack: false, + async commit() { + this.committed = true; + }, + async rollback() { + this.rolledBack = true; + }, + }; + + let persistedConfig = options.persistedConfig || null; + let existingConfig = null; + if (options.existingConfig) { + persistedConfig = { + ...options.existingConfig, + interface_type: { + id: interfaceType.id, + interface_category: interfaceType.interface_category, + }, + }; + existingConfig = { + ...options.existingConfig, + async update(payload) { + capture.apiAppUpdatePayload = payload; + persistedConfig = { + ...persistedConfig, + ...payload, + interface_type: { + id: interfaceType.id, + interface_category: interfaceType.interface_category, + }, + }; + return this; + }, + }; + } + + const ctx = { + app: { + config: {}, + Sequelize, + }, + user: { + id: 10001, + employees_id: 10001, + employees_name: '测试用户', + }, + model: { + transaction: async () => transaction, + QimenApp: { + async findOne(args = {}) { + capture.qimenAppFindOneArgs.push(args); + return options.qimenAppRecord || null; + }, + }, + ApiApp: { + async findOne(args = {}) { + capture.apiAppFindOneArgs.push(args); + if (Object.prototype.hasOwnProperty.call(args.where || {}, 'contract_id')) { + return existingConfig; + } + return options.duplicateConfig || null; + }, + async create(payload) { + capture.apiAppCreatePayload = payload; + persistedConfig = { + id: Number(options.createdConfigId || 321), + ...payload, + interface_type: { + id: interfaceType.id, + interface_category: interfaceType.interface_category, + }, + }; + return { + id: persistedConfig.id, + }; + }, + async findByPk(id) { + return { + id, + ...persistedConfig, + }; + }, + }, + InterfaceType: {}, + StoreWarehouse: { + async findByPk(id) { + return { + id, + warehouse_id: relation.warehouse_id, + }; + }, + }, + }, + service: { + systems: { + operationLog: { + async createOperationLog(payload) { + capture.operationLogPayload = payload; + }, + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + ctx.app.model = ctx.model; + + const service = new StoreWarehouseService(ctx); + service.getCurrentSubject = async () => ({ role: 'warehouse' }); + service.findScopedRelation = async () => relation; + service.ensureWarehouseSubject = () => {}; + service.getApiInterfaceType = async () => interfaceType; + service.getRelationIncludes = () => []; + service.serializeRelation = result => ({ + id: Number(result.id || relation.id), + warehouse_id: Number(result.warehouse_id || relation.warehouse_id), + }); + service.clearQimenContractCache = async configs => { + capture.clearedConfigs = configs; + }; + + return { + service, + capture, + transaction, + }; +} + +describe('test/app/service/systems/store_warehouse.saveApiConfig.test.js', () => { + it('should derive qimen_customer_id from QimenApp when request omits qimen_customer_id', async () => { + const { service, capture, transaction } = createSaveApiConfigHarness({ + qimenAppRecord: { + id: 11, + app_key: 'qm-app-key-create', + customer_id: 'db_customer_create', + }, + }); + + const result = await service.saveApiConfig({ + id: 88, + interface_type_id: 7, + app_name: '奇门配置创建', + qimen_app_key: 'qm-app-key-create', + qimen_warehouse_code: 'QM_WH_CREATE', + contact_person: '测试联系人', + contact_phone: '13800138000', + email: 'create@example.com', + is_enabled: 1, + }); + + assert.equal(capture.qimenAppFindOneArgs.length, 1); + assert.deepEqual(capture.qimenAppFindOneArgs[0].where, { + app_key: 'qm-app-key-create', + }); + assert.equal(String(capture.apiAppCreatePayload.qimen_customer_id || ''), 'db_customer_create'); + assert.equal(String(result.data.api_config.qimen_customer_id || ''), 'db_customer_create'); + assert.equal(transaction.committed, true); + assert.equal(transaction.rolledBack, false); + }); + + it('should use database customer_id instead of external qimen_customer_id on update', async () => { + const { service, capture, transaction } = createSaveApiConfigHarness({ + qimenAppRecord: { + id: 12, + app_key: 'qm-app-key-update', + customer_id: 'db_customer_update', + }, + existingConfig: { + id: 322, + app_name: '旧配置', + interface_type_id: 7, + contract_id: 88, + warehouse_id: 100000, + qimen_app_key: 'qm-app-key-update', + qimen_customer_id: 'legacy_customer', + qimen_warehouse_code: 'QM_WH_OLD', + api_version: '1.0', + sign_method: 'md5', + rate_limit: 1000, + timeout_seconds: 30, + is_enabled: 1, + }, + }); + + const result = await service.saveApiConfig({ + id: 88, + interface_type_id: 7, + app_name: '奇门配置更新', + qimen_app_key: 'qm-app-key-update', + qimen_customer_id: 'external_customer_should_be_ignored', + qimen_warehouse_code: 'QM_WH_NEW', + is_enabled: 0, + }); + + assert.equal(String(capture.apiAppUpdatePayload.qimen_customer_id || ''), 'db_customer_update'); + assert.notEqual(String(capture.apiAppUpdatePayload.qimen_customer_id || ''), 'external_customer_should_be_ignored'); + assert.equal(String(result.data.api_config.qimen_customer_id || ''), 'db_customer_update'); + assert.equal(transaction.committed, true); + assert.equal(transaction.rolledBack, false); + }); + + it('should fail when qimen_app_key has no matching qimen app record', async () => { + const { service, capture, transaction } = createSaveApiConfigHarness({ + qimenAppRecord: null, + }); + + await assert.rejects(async () => { + await service.saveApiConfig({ + id: 88, + interface_type_id: 7, + app_name: '奇门配置失败', + qimen_app_key: 'qm-app-key-missing', + qimen_warehouse_code: 'QM_WH_MISSING', + is_enabled: 1, + }); + }, error => { + assert.equal(Number(error.code), 400); + assert.match(String(error.message || ''), /qimen_app_key|奇门应用配置/); + return true; + }); + + assert.equal(capture.apiAppCreatePayload, null); + assert.equal(transaction.committed, false); + assert.equal(transaction.rolledBack, true); + }); +}); diff --git a/test/app/service/systems/upload.test.js b/test/app/service/systems/upload.test.js index 5ba80c1..7f18495 100644 --- a/test/app/service/systems/upload.test.js +++ b/test/app/service/systems/upload.test.js @@ -148,4 +148,25 @@ describe('test/app/service/systems/upload.test.js', () => { assert.equal(String(fileReferenceCreates[0].business_type), 'receivingReport'); assert.equal(String(fileReferenceCreates[0].business_id), '273'); }); + + it('should skip quota intercept when warehouse quota query returns empty rows', async () => { + const { service } = createService(); + service.app.model.query = async function() { + return []; + }; + + let result; + await assert.doesNotReject(async () => { + result = await service.getUploadParams({ + fileName: 'report.xlsx', + fileType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + fileSize: 2048, + type: 'document', + md5: 'c688dd719a7260404822d7dfebdc6115', + }); + }); + + assert.equal(result.isNew, true); + assert.ok(result.uploadUrl); + }); });