From 4bf32685964ba779628ff3c4cc44798f2ec5e5a7 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 24 Sep 2026 03:16:35 +0800 Subject: [PATCH] =?UTF-8?q?feat(workbench):=20=E5=A4=A7=E5=9B=A2=E8=B4=AD?= =?UTF-8?q?=E6=89=93=E5=8C=85=E7=B3=BB=E6=95=B0=E4=B8=8E=E6=89=93=E5=8C=85?= =?UTF-8?q?=E6=97=B6=E9=95=BF=E9=97=B8=E9=97=A8=EF=BC=8CpackOrder/queryOrd?= =?UTF-8?q?er=20=E5=93=8D=E5=BA=94=E6=96=B0=E5=A2=9E=20wave=5Fscope=20?= =?UTF-8?q?=E4=B8=8E=E5=80=92=E8=AE=A1=E6=97=B6=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 仓库设置新增 big_group_pack_coefficient(数字,默认 3,单位秒/单):store.js 默认值与归一化校验、setting.warehouse 字段元信息(type=number、min=0.1) - workbench.queryOrder:响应 order 新增 wave_scope;当前工作台 wave_scope=1 打包任务未到「打包数x系数」秒时扫描其他波次订单返回「打包时长不足」,本波次放行,已到时不受限;闸门按 wms_pack_task.wave_scope=1 快捷判定 - workbench.packOrder:wms_pack_task 落库 wave_scope(服务端复查,非法/缺省兜底订单行值);响应新增 pack_wait_seconds(当前波次打包数x系数)与 pack_start_time(毫秒时间戳),仅 wave_scope=1 下发,其他为 0 - 迁移 20260924150000-add-wave-scope-to-pack-task.js:wms_pack_task 新增 wave_scope 列(幂等;开发与生产均已执行,生产因存在更早 pending 迁移改为等价 DDL+SequelizeMeta 记录) - 测试:新增 workbench.bigGroupTimeGate.regression.test.js(11 用例全绿);workbench.queryOrder.performance.test.js 与基线一致(8 pass / 6 既有失败,非本次引入);ESLint 通过(workbench.js 历史类字段 parse error 为既有问题,与基线一致) - 文档:methods/system.json 升至 0.3.181、changes 新增 2 条记录;已全量导入库表(wms_api_method_doc/wms_method_doc_meta)后重新导出,恢复 3 条库表已有但文件缺失的 setting.warehouse 前端配置方法 --- app/model/pack_task.js | 6 + app/model/store.js | 12 + app/service/systems/setting/warehouse.js | 690 +------------- app/service/systems/workbench.js | 113 ++- ...60924150000-add-wave-scope-to-pack-task.js | 72 ++ methods/changes/system.json | 107 +++ methods/system.json | 867 +++++++++++++++++- ...kbench.bigGroupTimeGate.regression.test.js | 443 +++++++++ 8 files changed, 1616 insertions(+), 694 deletions(-) create mode 100644 database/migrations/20260924150000-add-wave-scope-to-pack-task.js create mode 100644 test/app/service/systems/workbench.bigGroupTimeGate.regression.test.js diff --git a/app/model/pack_task.js b/app/model/pack_task.js index af74192..3b8fa45 100644 --- a/app/model/pack_task.js +++ b/app/model/pack_task.js @@ -37,6 +37,12 @@ module.exports = app => { allowNull: true, comment: '波次号', }, + wave_scope: { + type: TINYINT(4), + allowNull: false, + defaultValue: 0, + comment: '波次范围:0未分配波次 1大团购 2散单 3小团购 4单品单件', + }, waybill_code: { type: STRING(50), allowNull: true, diff --git a/app/model/store.js b/app/model/store.js index 57cd65c..a9405f8 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -96,6 +96,7 @@ module.exports = app => { default_location_id: null, single_order_pack_max_minutes: 3, group_order_pack_max_minutes: 40, + big_group_pack_coefficient: 3, return_unpack_max_record_minutes: 5, inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES, auto_outbound_rules: DEFAULT_AUTO_OUTBOUND_RULES, @@ -519,6 +520,17 @@ module.exports = app => { normalized.group_order_pack_max_minutes = groupOrderPackMaxMinutes; } + const rawBigGroupPackCoefficient = parsed.big_group_pack_coefficient; + if (rawBigGroupPackCoefficient === undefined || rawBigGroupPackCoefficient === null || rawBigGroupPackCoefficient === '') { + normalized.big_group_pack_coefficient = DEFAULT_SUBJECT_CONFIG.big_group_pack_coefficient; + } else { + const bigGroupPackCoefficient = Number(rawBigGroupPackCoefficient); + if (!Number.isFinite(bigGroupPackCoefficient) || bigGroupPackCoefficient <= 0) { + throw new Error('subject_config.big_group_pack_coefficient 必须是大于 0 的数字'); + } + normalized.big_group_pack_coefficient = bigGroupPackCoefficient; + } + const rawReturnUnpackMaxRecordMinutes = parsed.return_unpack_max_record_minutes; if (rawReturnUnpackMaxRecordMinutes === undefined || rawReturnUnpackMaxRecordMinutes === null || rawReturnUnpackMaxRecordMinutes === '') { normalized.return_unpack_max_record_minutes = DEFAULT_SUBJECT_CONFIG.return_unpack_max_record_minutes; diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index 0fc89c2..300dd6e 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -1,7 +1,5 @@ 'use strict'; -const crypto = require('node:crypto'); - const { Service } = require('egg'); const INTERNAL_WAVE_STRATEGY_VERSION_KEY = 'wave_strategy_version'; @@ -339,6 +337,15 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ description: '团购打包最大时长,单位:分钟,默认 40', min: 1, }), + Object.freeze({ + key: 'big_group_pack_coefficient', + name: '大团购打包系数', + type: 'number', + default: 3, + required: false, + description: '大团购波次(wave_scope=1)打包中,扫描其他波次订单至少需等待「当前波次打包数 × 系数」秒,单位:秒/单,默认 3,必须大于 0', + min: 0.1, + }), Object.freeze({ key: 'return_unpack_max_record_minutes', name: '拆包最大录制时长(分钟)', @@ -441,33 +448,6 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ }), ]); -// 仓库前端配置品牌文本字段元信息(对应 wms_warehouse_front_config,一仓一行)。 -// 域名与证书字段不在此列:domain/cert_pem/cert_key/cert_path/key_path 只能通过证书上传接口(saveFrontCert)变更。 -const FRONT_CONFIG_TEXT_FIELDS = Object.freeze([ - Object.freeze({ key: 'title', name: 'title', maxLength: 100 }), - Object.freeze({ key: 'logo_url', name: 'logo_url', maxLength: 255 }), - Object.freeze({ key: 'favicon_url', name: 'favicon_url', maxLength: 255 }), - Object.freeze({ key: 'login_bg_url', name: 'login_bg_url', maxLength: 255 }), -]); - -// 公共按域名拉取接口对外输出的字段白名单(安全红线:严禁输出证书/私钥内容与证书路径、同步状态等内部字段) -const FRONT_CONFIG_PUBLIC_FIELDS = Object.freeze([ - 'domain', - 'title', - 'logo_url', - 'login_bg_url', - 'favicon_url', - 'theme', -]); - -// 公共按域名拉取接口缓存 TTL(秒) -const FRONT_CONFIG_PUBLIC_CACHE_TTL_SECONDS = 600; -// 未登记域名空缓存 TTL(秒):短缓存兜底防穿透,域名登记后由保存流程主动失效 -const FRONT_CONFIG_PUBLIC_MISS_CACHE_TTL_SECONDS = 60; - -// 证书/私钥 PEM 文本最大长度(正常 RSA/ECC 证书远小于该值,防止异常大报文) -const FRONT_CONFIG_PEM_MAX_LENGTH = 64 * 1024; - class SettingWarehouseService extends Service { /** * 读取默认快递与平台编码选项,查询失败时自动降级为空列表。 @@ -834,152 +814,6 @@ class SettingWarehouseService extends Service { }; } - /** - * 校验并规范化仓库前端配置的字符串字段。 - * - * @param {*} value 原始值。 - * @param {string} fieldName 字段名。 - * @param {number} maxLength 字段最大长度。 - * @return {string|null} 规范化后的字符串;空值返回 null(表示清空)。 - * @throws {Error} 超长时抛出,状态码 400。 - */ - normalizeFrontConfigText(value, fieldName, maxLength) { - if (value === undefined || value === null) { - return null; - } - - const normalized = String(value).trim(); - if (!normalized) { - return null; - } - - if (normalized.length > maxLength) { - throw this.createError(`${fieldName} 长度不能超过 ${maxLength} 字符`, 400); - } - - return normalized; - } - - /** - * 校验并规范化仓库前端配置的 theme 字段。 - * - * @param {*} value 原始值(对象或 JSON 字符串)。 - * @return {Object|null} 规范化后的主题对象;空值返回 null(表示清空)。 - * @throws {Error} 非合法 JSON 对象时抛出,状态码 400。 - */ - normalizeFrontConfigTheme(value) { - if (value === undefined || value === null || value === '') { - return null; - } - - let parsed = value; - if (typeof value === 'string') { - try { - parsed = JSON.parse(value.trim()); - } catch (error) { - throw this.createError('theme 必须是合法的 JSON 对象', 400); - } - } - - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { - throw this.createError('theme 必须是合法的 JSON 对象', 400); - } - - return parsed; - } - - /** - * 校验非空 domain 的全局唯一性(可空列唯一索引允许多 NULL,数据库不兜底)。 - * - * @param {string} domain 待校验域名(非空)。 - * @param {number} excludeWarehouseId 排除的仓库 ID(当前仓库自身)。 - * @return {Promise} 无返回值。 - * @throws {Error} domain 已被其他仓库使用时抛出,状态码 409。 - */ - async assertFrontConfigDomainUnique(domain, excludeWarehouseId) { - const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig; - if (!configModel || typeof configModel.findOne !== 'function') { - throw this.createError('WarehouseFrontConfig model 不可用', 500); - } - - const { Op } = this.app.Sequelize; - const existing = await configModel.findOne({ - where: { - domain, - store_id: { [Op.ne]: excludeWarehouseId }, - }, - attributes: [ 'store_id', 'domain' ], - }); - - if (existing) { - throw this.createError(`域名 ${domain} 已被其他仓库使用`, 409); - } - } - - /** - * 构建仓库前端配置的输出对象(无记录时返回默认空配置)。 - * - * 证书回显:输出证书原文(cert_pem)与私钥原文(key_pem,取自 cert_key 列), - * 不再输出 cert_path/key_path 路径字段(保存时已置空,尚无真实路径)。 - * 安全说明:私钥原文回显仅限仓库主体登录后的 settings 页 - * (getFrontConfig/saveFrontConfig/saveFrontCert 三个需登录接口复用本输出); - * 公共无鉴权接口 getFrontConfigByDomain 走 buildFrontConfigPublicOutput 白名单, - * 不经过本方法,仍不暴露证书/私钥内容与同步状态等内部字段。 - * - * @param {Object|null} record 配置记录实例(可为 null)。 - * @param {number} warehouseId 当前仓库 ID。 - * @return {Object} 规范化输出对象。 - */ - buildFrontConfigOutput(record, warehouseId) { - const hasRecord = !!(record && typeof record.get === 'function'); - const getValue = key => (hasRecord ? record.get(key) : null); - - return { - warehouse_id: Number(warehouseId || 0), - domain: hasRecord ? (getValue('domain') || '') : '', - title: hasRecord ? (getValue('title') || '') : '', - logo_url: hasRecord ? (getValue('logo_url') || '') : '', - favicon_url: hasRecord ? (getValue('favicon_url') || '') : '', - login_bg_url: hasRecord ? (getValue('login_bg_url') || '') : '', - theme: hasRecord ? (getValue('theme') || null) : null, - cert_pem: hasRecord ? (getValue('cert_pem') || '') : '', - key_pem: hasRecord ? (getValue('cert_key') || '') : '', - cert_expire_at: hasRecord ? (getValue('cert_expire_at') || null) : null, - sync_status: hasRecord ? Number(getValue('sync_status') || 0) : 0, - sync_attempts: hasRecord ? Number(getValue('sync_attempts') || 0) : 0, - last_sync_error: hasRecord ? (getValue('last_sync_error') || '') : '', - last_synced_at: hasRecord ? (getValue('last_synced_at') || null) : null, - updated_at: hasRecord ? (getValue('updated_at') || null) : null, - }; - } - - /** - * 查询当前仓库的前端独立部署配置(settings 页回显)。 - * - * 需登录(token 绑定仓库上下文,只能查到自己仓库的配置), - * 响应含证书原文(cert_pem)与私钥原文(key_pem),供仓库主体 settings 页回显; - * 公共无鉴权接口 getFrontConfigByDomain 仍只返回公开字段白名单。 - * - * @return {Promise} 配置输出对象;无记录时返回默认空配置。 - * @throws {Error} 未识别到当前仓库时抛出,状态码 400。 - */ - async getFrontConfig() { - const warehouseId = this.getCurrentWarehouseId(); - - const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig; - if (!configModel || typeof configModel.findOne !== 'function') { - throw this.createError('WarehouseFrontConfig model 不可用', 500); - } - - const record = await configModel.findOne({ - where: { - store_id: warehouseId, - }, - }); - - return this.buildFrontConfigOutput(record, warehouseId); - } - /** * 获取当前仓库启用的微信小程序授权配置(wms_wechat_app)。 * @@ -1025,512 +859,6 @@ class SettingWarehouseService extends Service { updated_at: plain.updated_at, }; } - - /** - * 构建前端配置公共拉取接口的缓存键(按域名)。 - * - * @param {string} domain 域名(内部会 trim 规范化)。 - * @return {string} Redis 缓存键。 - */ - getFrontConfigDomainCacheKey(domain) { - return `front:config:domain:${String(domain || '').trim()}`; - } - - /** - * 构建前端配置公共拉取接口的输出对象(仅公开字段白名单)。 - * - * 安全红线:只输出 FRONT_CONFIG_PUBLIC_FIELDS 白名单字段, - * 严禁输出 cert_pem/cert_key 证书与私钥内容,以及 cert_path、key_path、 - * sync_status、sync_attempts、last_sync_error 等内部字段。 - * - * @param {Object} record 配置记录实例。 - * @return {Object} 仅含公开字段的输出对象。 - */ - buildFrontConfigPublicOutput(record) { - const hasRecord = !!(record && typeof record.get === 'function'); - const getValue = key => (hasRecord ? record.get(key) : null); - - const output = {}; - for (const key of FRONT_CONFIG_PUBLIC_FIELDS) { - const value = hasRecord ? getValue(key) : null; - output[key] = key === 'theme' ? (value || null) : (value || ''); - } - return output; - } - - /** - * 清理指定域名的前端配置公共拉取缓存(空域名跳过)。 - * - * @param {string} domain 待清理的域名。 - * @return {Promise} 无返回值。 - */ - async clearFrontConfigDomainCache(domain) { - const normalizedDomain = String(domain || '').trim(); - if (!normalizedDomain) { - return; - } - - await this.deleteCacheByKey(this.getFrontConfigDomainCacheKey(normalizedDomain)); - } - - /** - * 按域名查询前端配置(公共无鉴权接口业务实现,Redis 缓存 + 查库兜底)。 - * - * 安全红线:只返回公开字段(domain/title/logo_url/login_bg_url/favicon_url/theme), - * 严禁返回 cert_pem/cert_key 证书与私钥内容,以及 cert_path/key_path/ - * sync_status/sync_attempts/last_sync_error 等内部字段。 - * - * @param {string} domain 待查询域名。 - * @return {Promise} 仅含公开字段的配置对象。 - * @throws {Error} domain 为空时抛出 400;未登记域名抛出 404;数据库异常抛出 500。 - */ - async getFrontConfigByDomain(domain) { - const normalizedDomain = String(domain || '').trim(); - - if (!normalizedDomain) { - throw this.createError('domain 不能为空', 400); - } - - if (normalizedDomain.length > 100) { - throw this.createError('domain 长度不能超过 100 字符', 400); - } - - const cacheKey = this.getFrontConfigDomainCacheKey(normalizedDomain); - - // 优先读缓存;Redis 异常时降级查库(getCacheAsync 内部已做 Redis 降级处理) - if (this.app && typeof this.app.getCacheAsync === 'function') { - try { - const cached = await this.app.getCacheAsync(cacheKey); - - // 未登记域名空缓存标记:直接按未配置返回,防穿透 - if (cached && typeof cached === 'object' && cached.configured === false) { - throw this.createError('域名未配置', 404); - } - - if (cached && typeof cached === 'object' && typeof cached.domain === 'string' && cached.domain) { - return cached; - } - } catch (error) { - if (Number(error.code) === 404) { - throw error; - } - this.ctx.logger.warn('[SettingWarehouseService.getFrontConfigByDomain] 读取缓存失败,降级查库: %s', error.message); - } - } - - const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig; - if (!configModel || typeof configModel.findOne !== 'function') { - throw this.createError('WarehouseFrontConfig model 不可用', 500); - } - - const record = await configModel.findOne({ - where: { - domain: normalizedDomain, - }, - }); - - if (!record) { - // 缓存穿透兜底:未登记域名写短 TTL 空缓存,防止高频探测打穿数据库 - if (this.app && typeof this.app.setCacheAsync === 'function') { - try { - await this.app.setCacheAsync(cacheKey, { configured: false }, FRONT_CONFIG_PUBLIC_MISS_CACHE_TTL_SECONDS); - } catch (error) { - this.ctx.logger.warn('[SettingWarehouseService.getFrontConfigByDomain] 写入未命中空缓存失败: %s', error.message); - } - } - throw this.createError('域名未配置', 404); - } - - const output = this.buildFrontConfigPublicOutput(record); - - if (this.app && typeof this.app.setCacheAsync === 'function') { - try { - await this.app.setCacheAsync(cacheKey, output, FRONT_CONFIG_PUBLIC_CACHE_TTL_SECONDS); - } catch (error) { - this.ctx.logger.warn('[SettingWarehouseService.getFrontConfigByDomain] 写入缓存失败: %s', error.message); - } - } - - return output; - } - - /** - * 规范化证书/私钥 PEM 文本:去首尾空白,空值返回 null(表示未提供)。 - * - * @param {*} value 原始值(PEM 文本)。 - * @param {string} fieldName 字段名(用于错误提示)。 - * @return {string|null} 规范化后的 PEM 文本;空值返回 null。 - * @throws {Error} 内容超过长度上限时抛出,状态码 400。 - */ - normalizeFrontConfigPem(value, fieldName) { - if (value === undefined || value === null) { - return null; - } - - const normalized = String(value).trim(); - if (!normalized) { - return null; - } - - if (normalized.length > FRONT_CONFIG_PEM_MAX_LENGTH) { - throw this.createError(`${fieldName} 内容长度不能超过 ${FRONT_CONFIG_PEM_MAX_LENGTH} 字符`, 400); - } - - return normalized; - } - - /** - * 用 Node 内置 crypto.X509Certificate 解析证书 PEM 文本。 - * - * @param {string} certPem 证书 PEM 文本。 - * @return {Object} 解析成功后的 X509Certificate 实例。 - * @throws {Error} 证书无法解析时抛出,状态码 400,统一文案“证书不合法”。 - */ - parseFrontConfigCertPem(certPem) { - try { - return new crypto.X509Certificate(certPem); - } catch (error) { - throw this.createError('证书不合法', 400); - } - } - - /** - * 校验证书有效期:未生效或已过期的证书禁止提交。 - * - * @param {Object} cert 已解析的 X509Certificate 实例。 - * @return {void} 无返回值。 - * @throws {Error} 证书未生效或已过期时抛出,状态码 400,统一文案“证书不合法”。 - */ - assertFrontConfigCertValid(cert) { - const now = Date.now(); - const validFrom = new Date(cert.validFrom); - const validTo = new Date(cert.validTo); - - if (Number.isNaN(validFrom.getTime())) { - throw this.createError('证书不合法', 400); - } - - if (validFrom.getTime() > now) { - throw this.createError('证书不合法', 400); - } - - if (Number.isNaN(validTo.getTime())) { - throw this.createError('证书不合法', 400); - } - - if (validTo.getTime() <= now) { - throw this.createError('证书不合法', 400); - } - } - - /** - * 收集证书可覆盖的域名列表:SAN 中的 DNS 项与 CN,统一转小写。 - * - * @param {Object} cert 已解析的 X509Certificate 实例。 - * @return {string[]} 小写域名列表。 - */ - collectFrontConfigCertNames(cert) { - const names = []; - - const sanText = cert.subjectAltName || ''; - for (const part of String(sanText).split(',')) { - const entry = String(part).trim(); - if (entry.startsWith('DNS:')) { - const dnsName = entry.slice(4).trim(); - if (dnsName) { - names.push(dnsName.toLowerCase()); - } - } - } - - const subjectText = cert.subject || ''; - const cnMatch = /CN\s*=\s*([^,\n]+)/i.exec(String(subjectText)); - if (cnMatch && cnMatch[1]) { - names.push(cnMatch[1].trim().toLowerCase()); - } - - return names; - } - - /** - * 判断证书域名列表是否覆盖目标域名(支持精确匹配与通配符 *.example.com)。 - * - * @param {string[]} names 证书 SAN/CN 域名列表(小写)。 - * @param {string} domain 待校验域名。 - * @return {boolean} 是否覆盖。 - */ - frontConfigCertCoversDomain(names, domain) { - const target = String(domain).toLowerCase(); - if (!target) { - return true; - } - - return names.some(name => { - const normalized = String(name).toLowerCase(); - if (normalized === target) { - return true; - } - - if (normalized.startsWith('*.')) { - const suffix = normalized.slice(1); - return target.endsWith(suffix) && target.length > suffix.length; - } - - return false; - }); - } - - /** - * 校验私钥与证书是否成对:对比两者的 SPKI DER 公钥指纹。 - * - * @param {string} keyPem 私钥 PEM 文本。 - * @param {Object} cert 已解析的 X509Certificate 实例。 - * @return {void} 无返回值。 - * @throws {Error} 私钥无法解析或与证书不匹配时抛出,状态码 400,统一文案“证书不合法”。 - */ - validateFrontConfigKeyPem(keyPem, cert) { - let publicKey; - try { - publicKey = crypto.createPublicKey(keyPem); - } catch (error) { - throw this.createError('证书不合法', 400); - } - - const keySpki = publicKey.export({ type: 'spki', format: 'der' }); - const certSpki = cert.publicKey.export({ type: 'spki', format: 'der' }); - if (Buffer.compare(keySpki, certSpki) !== 0) { - throw this.createError('证书不合法', 400); - } - } - - /** - * 校验当前主体为仓库主体(前端独立部署配置仅仓库主体可操作)。 - * - * @return {Promise} 当前主体对象(含 id/company_name/project/isWarehouse/status)。 - * @throws {Error} 签约关系服务不可用时抛出 500;非仓库主体时抛出 403。 - */ - async assertFrontConfigWarehouseSubject() { - const storeWarehouseService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.storeWarehouse; - if (!storeWarehouseService || typeof storeWarehouseService.getCurrentSubject !== 'function') { - throw this.createError('签约关系服务不可用', 500); - } - - const currentSubject = await storeWarehouseService.getCurrentSubject(); - if (!currentSubject || !currentSubject.isWarehouse) { - throw this.createError('仅仓库主体可配置前端独立部署', 403); - } - - return currentSubject; - } - - /** - * 保存当前仓库前端独立部署品牌配置(upsert,一仓一行,仅品牌字段部分更新)。 - * - * 域名与证书不在本接口受理范围:domain 变更必须走 saveFrontCert 重新校验证书; - * cert_pem/key_pem/cert_path/key_path/cert_expire_at 一律不受理(方法层白名单过滤)。 - * 保存仍视为一次配置变更:同步状态重置为待同步,写库成功后清理当前 domain 的公共拉取缓存。 - * - * @param {Object} [data={}] 请求参数。 - * @param {string} [data.title] 站点标题(≤100 字符,空值清空)。 - * @param {string} [data.logo_url] Logo 地址(≤255 字符,空值清空)。 - * @param {string} [data.favicon_url] 站点 favicon 图标地址(≤255 字符,空值清空)。 - * @param {string} [data.login_bg_url] 登录页背景图地址(≤255 字符,空值清空)。 - * @param {Object|string} [data.theme] 主题配置(合法 JSON 对象或 JSON 字符串,空值清空)。 - * @return {Promise} 保存后的配置输出对象(同步状态已重置为待同步;证书回显口径与 getFrontConfig 一致)。 - * @throws {Error} 非仓库主体时抛出 403;参数非法时抛出 400。 - */ - async saveFrontConfig(data = {}) { - const warehouseId = this.getCurrentWarehouseId(); - - // 仅仓库主体管理员可配置前端独立部署(isWarehouse 判定) - await this.assertFrontConfigWarehouseSubject(); - - const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig; - if (!configModel || typeof configModel.findOne !== 'function') { - throw this.createError('WarehouseFrontConfig model 不可用', 500); - } - - const patch = {}; - - for (const field of FRONT_CONFIG_TEXT_FIELDS) { - if (Object.prototype.hasOwnProperty.call(data, field.key)) { - patch[field.key] = this.normalizeFrontConfigText(data[field.key], field.name, field.maxLength); - } - } - - if (Object.prototype.hasOwnProperty.call(data, 'theme')) { - patch.theme = this.normalizeFrontConfigTheme(data.theme); - } - - // 保存即重置同步状态:本次保存待同步 - patch.sync_status = 0; - patch.sync_attempts = 0; - patch.last_sync_error = null; - patch.last_synced_at = null; - - let record = await configModel.findOne({ - where: { - store_id: warehouseId, - }, - }); - - // 品牌字段不改变 domain:写库成功后清理当前 domain 的公共拉取缓存即可 - const previousDomain = record ? String(record.get('domain') || '').trim() : ''; - - try { - if (record) { - await record.update(patch); - } else { - record = await configModel.create({ - store_id: warehouseId, - ...patch, - }); - } - } catch (error) { - // 并发写入兜底:唯一索引冲突统一转为业务错误 - if (error && error.name === 'SequelizeUniqueConstraintError') { - const conflictFields = error.fields || {}; - if (Object.prototype.hasOwnProperty.call(conflictFields, 'domain')) { - throw this.createError(`域名 ${patch.domain || ''} 已被其他仓库使用`, 409); - } - throw this.createError('仓库前端配置保存冲突,请稍后重试', 409); - } - throw error; - } - - // 回查一次再输出,避免实例上残留 CURRENT_TIMESTAMP 等字面量 - const savedRecord = await configModel.findByPk(record.id); - - // 写库成功后清理公共拉取缓存(先写库后清缓存);清缓存失败仅记日志,不影响保存结果 - if (previousDomain) { - await this.clearFrontConfigDomainCache(previousDomain) - .catch(error => { - this.ctx.logger.warn('[SettingWarehouseService.saveFrontConfig] 清理前端配置缓存失败: %s', error.message); - }); - } - - return this.buildFrontConfigOutput(savedRecord, warehouseId); - } - - /** - * 上传当前仓库前端独立部署证书(domain + 证书/私钥成对,upsert 该仓库行的证书与域名信息)。 - * - * 校验链:证书可解析 → 未生效拒绝 → 已过期拒绝 → 私钥与证书成对 → - * 证书 SAN/CN 覆盖 domain(支持 *.example.com 通配,不覆盖返回 400)→ - * domain 全局唯一(非空,409)。 - * 证书校验链任一失败均返回统一文案“证书不合法”(400),不返回细节。 - * 通过后自动写入 cert_expire_at(证书 validTo 权威值,不接受前端传值), - * 证书/私钥 PEM 内容直接写入 cert_pem/cert_key 列(内容仅定时任务读取, - * 不写暂存文件);cert_path/key_path 保存时置空,避免内容已换而路径陈旧, - * 等待未来定时任务部署后回填真实路径;同时更新该仓库行的 domain/cert_expire_at - * 并重置同步状态;写库成功后清理旧域名与新域名的公共拉取缓存(先写库后清缓存)。 - * - * @param {Object} [data={}] 请求参数。 - * @param {string} data.domain 仓库自持域名(必填,非空,≤100 字符,全局唯一)。 - * @param {string} data.pem 证书 PEM 文本(必填)。 - * @param {string} data.key 私钥 PEM 文本(必填,与证书成对)。 - * @return {Promise} 保存后的完整配置输出对象(含证书/私钥原文回显,口径与 getFrontConfig 一致)。 - * @throws {Error} 非仓库主体时抛出 403;参数非法/证书不合法时抛出 400(证书校验失败统一文案“证书不合法”);域名重复时抛出 409。 - */ - async saveFrontCert(data = {}) { - const warehouseId = this.getCurrentWarehouseId(); - - // 仅仓库主体管理员可上传前端独立部署证书(isWarehouse 判定) - await this.assertFrontConfigWarehouseSubject(); - - const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig; - if (!configModel || typeof configModel.findOne !== 'function') { - throw this.createError('WarehouseFrontConfig model 不可用', 500); - } - - // 入参必填校验:domain 非空且 ≤100;pem/key 必填(nginx 起 HTTPS 需要成对) - const domain = this.normalizeFrontConfigText(data.domain, 'domain', 100); - if (!domain) { - throw this.createError('domain 不能为空', 400); - } - - const certPem = this.normalizeFrontConfigPem(data.pem, 'pem'); - if (!certPem) { - throw this.createError('pem 不能为空', 400); - } - - const keyPem = this.normalizeFrontConfigPem(data.key, 'key'); - if (!keyPem) { - throw this.createError('key 不能为空', 400); - } - - // 校验链:证书可解析 → 未生效/已过期拒绝 → 私钥匹配 → SAN/CN 覆盖 domain → domain 全局唯一 - const cert = this.parseFrontConfigCertPem(certPem); - this.assertFrontConfigCertValid(cert); - this.validateFrontConfigKeyPem(keyPem, cert); - - const certNames = this.collectFrontConfigCertNames(cert); - if (!this.frontConfigCertCoversDomain(certNames, domain)) { - throw this.createError('证书不合法', 400); - } - - await this.assertFrontConfigDomainUnique(domain, warehouseId); - - // 证书/私钥内容直接入库(不再写暂存文件),有效期以证书 validTo 权威写入。 - // cert_path/key_path 保存时置空:内容已换而路径陈旧,避免 nginx 误读; - // 等待未来定时任务(Egg schedule/外部 crontab)部署后回填真实路径。 - const patch = { - domain, - cert_pem: certPem, - cert_key: keyPem, - cert_path: null, - key_path: null, - cert_expire_at: new Date(cert.validTo), - // 保存即重置同步状态:本次上传待同步 - sync_status: 0, - sync_attempts: 0, - last_sync_error: null, - last_synced_at: null, - }; - - let record = await configModel.findOne({ - where: { - store_id: warehouseId, - }, - }); - - // 记录更新前的域名,写库成功后用于清理旧域名公共拉取缓存 - const previousDomain = record ? String(record.get('domain') || '').trim() : ''; - - try { - if (record) { - await record.update(patch); - } else { - record = await configModel.create({ - store_id: warehouseId, - ...patch, - }); - } - } catch (error) { - // 并发写入兜底:唯一索引冲突统一转为业务错误 - if (error && error.name === 'SequelizeUniqueConstraintError') { - const conflictFields = error.fields || {}; - if (Object.prototype.hasOwnProperty.call(conflictFields, 'domain')) { - throw this.createError(`域名 ${domain} 已被其他仓库使用`, 409); - } - throw this.createError('仓库前端配置保存冲突,请稍后重试', 409); - } - throw error; - } - - // 回查一次再输出,避免实例上残留 CURRENT_TIMESTAMP 等字面量 - const savedRecord = await configModel.findByPk(record.id); - - // 写库成功后清理公共拉取缓存(先写库后清缓存:避免先清后写时并发读把旧值重新写回缓存)。 - // 需同时清理旧域名(更新前记录)与新域名(本次上传)两个 key;清缓存失败仅记日志,不影响保存结果。 - const affectedDomains = [ ...new Set([ previousDomain, domain ].filter(item => item)) ]; - await Promise.all(affectedDomains.map(affectedDomain => this.clearFrontConfigDomainCache(affectedDomain) - .catch(error => { - this.ctx.logger.warn('[SettingWarehouseService.saveFrontCert] 清理前端配置缓存失败: %s', error.message); - }))); - - return this.buildFrontConfigOutput(savedRecord, warehouseId); - } } module.exports = SettingWarehouseService; diff --git a/app/service/systems/workbench.js b/app/service/systems/workbench.js index fed6733..3f682de 100644 --- a/app/service/systems/workbench.js +++ b/app/service/systems/workbench.js @@ -258,6 +258,7 @@ class WorkbenchService extends Service { return await this._packOrder({ delivery_order_code: cachedCtx.delivery_order_code, wave_no: cachedCtx.wave_no, + wave_scope: cachedCtx.wave_scope, waybill_code: cachedCtx.waybill_code, warehouse_id: Number(cachedCtx.warehouse_id || 0), workbench_id: cachedCtx.workbench_id != null ? Number(cachedCtx.workbench_id) : null, @@ -279,7 +280,7 @@ class WorkbenchService extends Service { * 凭打包上下文 key 从缓存拉取打包参数(queryOrder 扫码时写入,20 分钟有效)。 * 只信任后端缓存内容,body 其它字段一律忽略(防篡改)。 * @param {Object} data - { key } - * @return {Promise} 缓存内容(warehouse_id/workbench_id/order_id/delivery_order_code/wave_no/waybill_code/is_sandan) + * @return {Promise} 缓存内容(warehouse_id/workbench_id/order_id/delivery_order_code/wave_no/wave_scope/waybill_code/is_sandan) * @throws {Error} key 缺失或上下文过期 */ async _loadPackCtx(data = {}) { @@ -779,13 +780,19 @@ class WorkbenchService extends Service { * 兼容一单多号(主单号/子单号):传入 waybill_code 时按「订单 + 运单号」维度 * 记录打包流水与去重,主/子单号流水互不覆盖;未传时保持订单维度(兼容旧设备端)。 * 打包人:上报了 users(business 旧链路)以上报为准,未上报(token+key 新链路)自动回填工作台绑定成员。 - * @param {Object} params - { delivery_order_code, wave_no, warehouse_id, workbench_id, status, pack_time, waybill_code, users } + * 波次范围(wave_scope):优先取上报值(0-4 整数),非法/缺省时兜底取订单行 wave_scope, + * 服务端复查落库,防止前端失真;写入 wms_pack_task.wave_scope。 + * 响应附大团购倒计时字段:wave_scope=1 时下发 pack_wait_seconds(当前波次打包数 × 大团购打包系数,秒) + * 与 pack_start_time(开始打包时间,毫秒时间戳)供前端倒计时;其他波次两字段均为 0。 + * @param {Object} params - { delivery_order_code, wave_no, wave_scope, warehouse_id, workbench_id, status, pack_time, waybill_code, users } * @param {string} [params.waybill_code] 扫描打包的运单号(可选,用于运单维度记录流水) - * @returns {Promise} + * @param {number} [params.wave_scope] 波次范围(0未分配 1大团购 2散单 3小团购 4单品单件,可选) + * @returns {Promise} 打包结果 { task_id, order_id, delivery_order_code, wave_no, isSandan, pack_mode, status, pack_wait_seconds, pack_start_time, batch? } */ async _packOrder(params) { const { ctx } = this; const { delivery_order_code: deliveryOrderCode, wave_no: waveNo, + wave_scope: waveScopeParam, warehouse_id: inputWarehouseId, workbench_id: workbenchIdRaw, status: packStatus, pack_time: packTime, wave_total_orders: waveTotalOrders, @@ -868,6 +875,8 @@ class WorkbenchService extends Service { isSandan: 0, pack_mode: 2, status: 2, + pack_wait_seconds: 0, + pack_start_time: 0, batch: { wave_id: waveId, wave_no: actualWaveNo, wave_type: waveType, total_orders: totalOrders }, }; } @@ -1067,12 +1076,20 @@ class WorkbenchService extends Service { orderId, waveId, deviceItemsCount, packSkuCount); } + // 波次范围(wave_scope)服务端复查:优先取上报值(0-4 整数),非法/缺省时兜底取订单行值 + const parsedWaveScope = Number.parseInt(waveScopeParam, 10); + const orderWaveScope = Number(orderRow.wave_scope) || 0; + const normalizedWaveScope = Number.isFinite(parsedWaveScope) && parsedWaveScope >= 0 && parsedWaveScope <= 4 + ? parsedWaveScope + : (orderWaveScope >= 0 && orderWaveScope <= 4 ? orderWaveScope : 0); + const packData = { order_id: orderId, warehouse_id: warehouseId, workbench_id: validWorkbenchId, wave_id: waveId, wave_no: actualWaveNo, + wave_scope: normalizedWaveScope, waybill_code: packWaybillCode, // 散单运单维度打包时记录运单号;未传运单号(旧设备端)或团购保持 null pack_mode: isSandan === 0 ? 2 : 1, // 1=散单 2=团购 status: normalizedPackStatus, @@ -1251,6 +1268,19 @@ class WorkbenchService extends Service { status: packData.status, }; + // 大团购波次(wave_scope=1)下发倒计时字段供前端展示: + // pack_wait_seconds = 当前波次打包数 × 大团购打包系数(秒),pack_start_time = 开始打包时间(毫秒时间戳); + // 其他波次一律下发 0(不参与倒计时)。 + let packWaitSeconds = 0; + let packStartTime = 0; + if (normalizedWaveScope === 1) { + const coefficient = await this._getBigGroupPackCoefficient(warehouseId); + packWaitSeconds = packQuantity * coefficient; + packStartTime = packTimeMs; + } + result.pack_wait_seconds = packWaitSeconds; + result.pack_start_time = packStartTime; + // 团购单附加波次总量 if (isSandan === 0) { result.batch = { wave_id: waveId, wave_no: actualWaveNo, wave_type: waveType, total_orders: totalOrders }; @@ -2036,6 +2066,32 @@ class WorkbenchService extends Service { return items; } + /** + * 读取仓库「大团购打包系数」配置(wms_store.subject_config.big_group_pack_coefficient)。 + * 走 deliveryOrder.getStoreSubjectConfig 公共读取链路(带缓存);配置读取失败 + * 或值非法时降级为默认系数 3(秒/单),保证时间闸门兜底可用。 + * @param {number} warehouseId 仓库ID + * @return {Promise} 大团购打包系数(秒/单),大于 0 + */ + async _getBigGroupPackCoefficient(warehouseId) { + const DEFAULT_COEFFICIENT = 3; + try { + const deliveryOrderService = this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.deliveryOrder; + if (deliveryOrderService && typeof deliveryOrderService.getStoreSubjectConfig === 'function') { + const subjectConfig = await deliveryOrderService.getStoreSubjectConfig(warehouseId); + const coefficient = Number(subjectConfig && subjectConfig.big_group_pack_coefficient); + if (Number.isFinite(coefficient) && coefficient > 0) { + return coefficient; + } + } + } catch (configErr) { + this.ctx.logger.warn('[Workbench._getBigGroupPackCoefficient] 读取仓库配置失败,使用默认系数: %s', configErr.message); + } + return DEFAULT_COEFFICIENT; + } + /** * 条码查订单:条码 → wms_order_express → 待处理/配送订单详情。 * 散单(isSandan=1)时在响应 order 对象中额外返回 intercept_flag / pack_flag 两个 0/1 标志: @@ -2043,6 +2099,9 @@ class WorkbenchService extends Service { * pack_flag 按运单维度判定(该运单号已有打包流水为 1,主/子单号互不影响)。 * order 对象始终包含 picker_id / picker_name:通过 wave_id 关联拣货任务取拣货人, * 散单无波次或未分配拣货人时为 null / 空串。 + * 大团购打包时长闸门:当前工作台存在进行中的大团购打包任务时,判断是否已到 + * 「当前波次打包数 × 大团购打包系数」秒:未到时仅允许查询本波次订单, + * 其他波次订单返回「打包时长不足」错误;已到时不受限制。 * 查询成功时生成一次性打包上下文 key(20 分钟有效)写入 Redis, * 响应附 key 供 workbench.packOrder 消费,打包参数由后端维护防篡改。 * @param {Object} params - { barcode, warehouseId, workbenchId } @@ -2163,6 +2222,52 @@ class WorkbenchService extends Service { } } + // 步骤3.5:大团购打包时长闸门。 + // 打包任务已落库 wave_scope,直接按 wave_scope=1 快捷判定当前工作台是否有 + // 进行中的大团购任务需要限制下一个任务的开始时间: + // - 未到「当前波次打包数 × 大团购打包系数」秒时:仅允许查询本波次订单,其他波次订单返回「打包时长不足」错误; + // - 已到时:不受限制,正常下发。 + if (validQueryWorkbenchId) { + let packTimeGateNotReached = false; + let currentTaskWaveId = 0; + try { + const currentPackTask = await ctx.model.PackTask.findOne({ + where: { + workbench_id: validQueryWorkbenchId, + warehouse_id: warehouseId, + status: { [ctx.app.Sequelize.Op.lt]: 2 }, + wave_scope: 1, + wave_id: { [ctx.app.Sequelize.Op.gt]: 0 }, + }, + attributes: [ 'id', 'wave_id', 'pack_quantity', 'start_time', 'create_time' ], + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + if (currentPackTask) { + const coefficient = await this._getBigGroupPackCoefficient(warehouseId); + const startMs = currentPackTask.start_time + ? new Date(currentPackTask.start_time).getTime() + : (currentPackTask.create_time ? new Date(currentPackTask.create_time).getTime() : Date.now()); + const currentPackQuantity = Number(currentPackTask.pack_quantity) > 0 + ? Number(currentPackTask.pack_quantity) + : 1; + const requiredSeconds = currentPackQuantity * coefficient; + const elapsedSeconds = Math.floor((Date.now() - startMs) / 1000); + if (elapsedSeconds < requiredSeconds) { + packTimeGateNotReached = true; + currentTaskWaveId = Number(currentPackTask.wave_id) || 0; + } + } + } catch (timeGateErr) { + ctx.logger.warn('[Workbench._queryOrder] 大团购打包时长闸门检查失败: %s', timeGateErr && timeGateErr.message); + } + + if (packTimeGateNotReached && Number(waveId) !== currentTaskWaveId) { + throw new Error('打包时长不足'); + } + } + // 步骤4:查询订单商品明细 + 关联 stock 详情(带缓存,公共方法 _fetchOrderItemsDetail) const items = await this._fetchOrderItemsDetail(orderId, warehouseId, sourceTable); @@ -2266,6 +2371,7 @@ class WorkbenchService extends Service { step: orderRow.step, wave_id: orderRow.wave_id, wave_no: orderRow.wave_no, + wave_scope: orderRow.wave_scope, post_status: orderRow.post_status, pick_status: orderRow.pick_status, pack_status: orderRow.pack_status, @@ -2312,6 +2418,7 @@ class WorkbenchService extends Service { order_id: orderRow.id, delivery_order_code: orderRow.delivery_order_code, wave_no: orderRow.wave_no || '', + wave_scope: orderRow.wave_scope, waybill_code: waybillCode, is_sandan: isSandan, }; diff --git a/database/migrations/20260924150000-add-wave-scope-to-pack-task.js b/database/migrations/20260924150000-add-wave-scope-to-pack-task.js new file mode 100644 index 0000000..6005e39 --- /dev/null +++ b/database/migrations/20260924150000-add-wave-scope-to-pack-task.js @@ -0,0 +1,72 @@ +'use strict'; + +/** + * 打包任务表 wms_pack_task 增加 wave_scope(波次范围)字段。 + * + * 取值约定(与 wms_order_delivery.wave_scope 一致): + * - 0 = 未分配波次 + * - 1 = 大团购 + * - 2 = 散单 + * - 3 = 小团购 + * - 4 = 单品单件 + * 默认 0。 + * + * 来源:workbench.packOrder 创建打包任务时落库,值由服务端复查 + * (优先取打包上下文上报值,非法/缺省时兜底取订单行 wave_scope)。 + * + * 幂等:列已存在则跳过。 + */ + +const TABLE_NAME = 'wms_pack_task'; + +const COLUMN_NAME = 'wave_scope'; + +/** + * 判断列是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const described = await queryInterface.describeTable(tableName); + return Boolean(described && described[columnName]); +} + +module.exports = { + /** + * 执行迁移:为 wms_pack_task 增加 wave_scope 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 构造器。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + if (await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) { + console.log('[20260924150000-add-wave-scope-to-pack-task] up: 列已存在,跳过'); + return; + } + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.TINYINT(4), + allowNull: false, + defaultValue: 0, + comment: '波次范围:0未分配波次 1大团购 2散单 3小团购 4单品单件', + }); + console.log('[20260924150000-add-wave-scope-to-pack-task] up: 已为 wms_pack_task 添加 wave_scope 列'); + }, + + /** + * 回滚迁移:移除 wms_pack_task 的 wave_scope 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + if (!await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) { + console.log('[20260924150000-add-wave-scope-to-pack-task] down: 列不存在,跳过'); + return; + } + + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + console.log('[20260924150000-add-wave-scope-to-pack-task] down: 已移除 wms_pack_task 的 wave_scope 列'); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index 22c1576..2c44468 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,111 @@ [ + { + "version": "2026.09.24-setting-big-group-pack-coefficient", + "date": "2026-09-24", + "type": "updated", + "summary": "仓库设置新增大团购打包系数:subject_config 新增 big_group_pack_coefficient(数字,默认 3,单位秒/单,必须大于 0),用于 workbench 大团购波次打包时长闸门与倒计时;setting.warehouse.getSettings 响应新增该字段说明,getFieldMeta 字段元信息列表同步新增该项", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.getFieldMeta" + ], + "notes": [ + "代码位置:app/service/systems/setting/warehouse.js(WAREHOUSE_SETTING_FIELDS 新增字段元信息:type=number、default=3、min=0.1);app/model/store.js(DEFAULT_SUBJECT_CONFIG 与 normalizeSubjectConfig 校验:空值回填 3,非法值抛错)", + "读取链路:app/service/systems/delivery_order.js getStoreSubjectConfig(带缓存),workbench 侧经 _getBigGroupPackCoefficient 读取,异常/非法降级默认 3", + "无需数据库迁移:配置存于 wms_store.subject_config(JSON 字段),仅需代码发布" + ] + }, + { + "version": "2026.09.24-workbench-big-group-pack-gate", + "date": "2026-09-24", + "type": "updated", + "summary": "工作台大团购打包系数与打包时长闸门:workbench.packOrder 打包任务落库 wave_scope,大团购波次(wave_scope=1)响应新增倒计时字段 pack_wait_seconds(当前波次打包数 × 大团购打包系数,单位秒)与 pack_start_time(开始打包时间,毫秒时间戳),其他波次均为 0;workbench.queryOrder 响应 order 新增 wave_scope,并新增大团购打包时长闸门(当前工作台 wave_scope=1 任务未到时仅允许查询本波次订单,其他波次返回「打包时长不足」错误)", + "methods": [ + "workbench.packOrder", + "workbench.queryOrder" + ], + "notes": [ + "数据库迁移:wms_pack_task 新增 wave_scope 列(database/migrations/20260924150000-add-wave-scope-to-pack-task.js,幂等),开发库与生产库均已执行(生产库因存在更早 pending 迁移改为等价 DDL + SequelizeMeta 记录)", + "代码位置:app/service/systems/workbench.js(_queryOrder 步骤3.5 闸门、_packOrder 落库与倒计时下发、_getBigGroupPackCoefficient 配置读取);app/model/pack_task.js 新增 wave_scope 字段定义", + "回归测试:test/app/service/systems/workbench.bigGroupTimeGate.regression.test.js(11 用例全绿:响应 wave_scope / packOrder 落库与倒计时 / 闸门未到时同波次放行、不同波次拦截、已到时放行、其他 wave_scope 不限制)" + ] + }, + { + "version": "2026.09.24-front-config-domain-verify", + "date": "2026-09-24", + "type": "updated", + "summary": "前端独立部署新增「域名归属验证」能力:新增设置/查询/校验域名的 3 个接口(frontConfig.setDomain/getDomain/checkDomain,均需登录、免权限、免鉴权、仅仓库主体可用);两个保存接口不再负责设置域名(saveCert 移除 domain 入参);新增域名验证闸门(getByDomain 仅放行 domain_status=1 的已验证域名、nginx 侧仅对已验证域名生成 server 块);getCert/saveCert 响应新增证书可设置性字段(10 → 13 字段:can_set_cert/can_set_cert_reason/domain_status)。", + "methods": [ + "frontConfig.setDomain", + "frontConfig.getDomain", + "frontConfig.checkDomain", + "frontConfig.getByDomain", + "frontConfig.getCert", + "frontConfig.saveCert" + ], + "notes": [ + "数据表与迁移:wms_warehouse_front_config 新增列 domain_status(tinyint 默认 0)/domain_verify_host/domain_verify_token/domain_verified_at/domain_verify_attempts/domain_last_error 与索引 idx_domain_status;迁移文件 database/migrations/20260924120000-add-domain-verify-to-wms-warehouse-front-config.js(幂等:列/索引已存在则跳过)。迁移会把历史非空 domain 的行回填 domain_status=1:存量域名在线上已生效(nginx 已在按域名提供服务),不回填会被新闸门在升级瞬间全部断流(证书上传被拒、公共拉取 404);回填只在真正新增该列的那一次执行,避免把升级后新设但未验证的域名误标为已验证;domain_verified_at 保持 NULL(历史生效时间不可考,不写虚假时间)", + "定时任务:新增 app/schedule/domain_verify_scan.js,按 config.frontConfig.domainVerify.interval(默认 10m)扫描待验证行;配置项 enable(true)/interval(10m)/lockTtlSeconds(600)/batchSize(50)/dohUrl(https://doh.pub/dns-query)/timeoutMs(5000)/maxAttempts(20);并发控制为进程内重入标志(ctx.app._domainVerifyScanRunning)+ Redis SET NX EX 跨进程互斥锁(Redis 不可用/抛错时降级为仅进程内防重入并 WARN);业务逻辑全部委托 service.systems.frontConfig.verifyPendingDomains(schedule 内不写 SQL);单行解析/落库失败只计入 errors 不中断整轮;已达 maxAttempts 的行不再自动重试(计入 skipped,仍可由 checkDomain 手动触发)", + "DNS 解析:DoH 为主(config.frontConfig.domainVerify.dohUrl,默认 https://doh.pub/dns-query;Status=3 或无 Answer 视为未解析到记录,不重复走系统 DNS),失败降级系统 DNS(node:dns,本仓首次引入,仅服务域名验证链路);校验目标一律为一次性子域 wmsv-<10 位 hex>.<域名>,避免与用户主域已有 TXT 记录(SPF/DKIM/站点校验等)冲突", + "配置新增 config.frontConfig.cname(默认空字符串):域名未通过验证时随 getDomain/setDomain/checkDomain 响应返回给前端,提示用户把域名 CNAME 指向该目标", + "nginx 侧联动(未改动本次文档范围,仅记录):script/warehouse-cert-sync.cjs 扫描待同步记录时新增 domain_status = 1 过滤(无该列时降级为不过滤并 WARN);script/deploy-cert-sync.cjs 探针新增 domain_status 列探测与取值分布/计数输出(0_unverified/1_verified/2_failed 与 gated-out 行数)", + "前端必须改造(不兼容变更):域名设置从 saveCert 迁移到 setDomain —— saveCert 已删除 domain 入参,前端若继续传 domain 会被静默忽略且不再变更域名;正确顺序为 setDomain → 按 verify_host/verify_value 配置 TXT 记录(并按 cname 配置 CNAME)→ checkDomain 手动校验或等待定时任务 → domain_status=1 后才可 saveCert 上传证书;getCert/saveCert 响应新增 can_set_cert/can_set_cert_reason/domain_status,供上传入口置灰与提示文案", + "风险提示:config.frontConfig.domainVerify.enable = false 时 app/schedule/domain_verify_scan.js 标记 disable、Egg 不注册该任务,新域名只能靠前端调用 checkDomain 手动触发才会放行;迁移尚未执行时 getByDomain 闸门降级为仅按 domain 查询(一次性 WARN),需迁移完成并重启实例后闸门才真正生效;getByDomain 命中配置缓存最长 600s 内仍可能放行刚被置为未验证的域名(setDomain/saveCert/校验成功均已主动清缓存,实际窗口极短,接受该取舍)", + "文档变更:methods/system.json 的 frontConfig 分组新增 3 条(setDomain/getDomain/checkDomain,均 isNeedLogin=true、isNeedAuth=false、带 Authorization 头)+ 更新 3 条(getByDomain 描述补充闸门语义与迁移降级说明,params/response/errors 未变;getCert 响应 10 → 13 字段;saveCert 删除 domain 入参、新增前置闸门、response 10 → 13 字段、errors 同步收敛);spec.methods 只放上述 6 条,未放入 getInfo/saveInfo(避免整条覆盖造成语义漂移);未使用 deleteMethods;根版本 0.3.178 → 0.3.179,updatedAt 保持 2026-09-24", + "已知遗留(本次未处理,建议下一批单独修正):frontConfig.getInfo 与 frontConfig.saveInfo 的描述仍写「domain 只能通过 frontConfig.saveCert 变更」,实际域名变更已收敛到 frontConfig.setDomain;这两条不在本批 spec.methods 内(避免整条覆盖),故未同步", + "变更记录条目数 640 → 641(新记录插入数组首位,既有 640 条 version 未改动、未删除)", + "维护源口径冲突(仅记录,未处理):与上一轮维持一致,methods/*.json 的维护源是否为数据库表 wms_method_doc_meta 仍待用户决策;本次仍按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库", + "自动清单刷新:node temp/tmp-gen-service-method-inventory.cjs 与 node temp/tmp-update-ai-method-routing.cjs(AI_METHOD_ROUTING.md 第 6 节 SERVICE_METHOD_INVENTORY 标记区与 temp/tmp-service-method-inventory.md 同步刷新)", + "docs/*.md 无需同步:检索 frontConfig/setDomain/checkDomain/域名验证 未命中解释性文档(仅 AI_METHOD_ROUTING.md 与 temp/tmp-service-method-inventory.md 含自动清单命中,已由刷新脚本处理)" + ], + "module": "frontConfig" + }, + { + "version": "2026.09.24-front-config-saveCert-response-fix", + "date": "2026-09-24", + "type": "updated", + "summary": "修正 frontConfig.saveCert 的响应契约:由错误的 8 字段品牌口径(buildInfoOutput:warehouse_id/domain/title/logo_url/favicon_url/login_bg_url/theme/updated_at)更正为 10 字段证书口径(buildCertOutput,与 frontConfig.getCert 一致:warehouse_id/domain/cert_pem/key_pem/cert_expire_at/sync_status/sync_attempts/last_sync_error/last_synced_at/updated_at);入参 domain/pem/key 与错误码 400/403/409/500 口径不变,其余 frontConfig 条目(getInfo/getCert/saveInfo/getByDomain)未改动。本记录闭环 2026.09.24-front-config-migrate-to-frontConfig 中标注的「saveCert 响应口径待确认」一项。", + "methods": [ + "frontConfig.saveCert" + ], + "notes": [ + "闭环说明:本记录闭环 2026.09.24-front-config-migrate-to-frontConfig 中标注的「saveCert 响应口径待确认」一项(该记录 notes 第 6 条:JSDoc 声明返回 10 字段证书输出,但实现实际 return this.buildInfoOutput(...) 返回 8 字段品牌信息);按工作流「新记录插入数组头部、历史记录不回改」,原记录保持原样,修正以本记录承接", + "代码证据:app/service/systems/frontConfig.js:782 saveCert 出口 return this.buildCertOutput(savedRecord, warehouseId);buildCertOutput 定义于同文件 :202,输出 10 字段 warehouse_id/domain/cert_pem/key_pem/cert_expire_at/sync_status/sync_attempts/last_sync_error/last_synced_at/updated_at(其中 key_pem 读 cert_key 列)", + "由 wms-dev-agent 修正实现(saveCert 返回由 buildInfoOutput 改为 buildCertOutput),本次仅同步文档口径,未改动任何代码", + "文档变更:methods/system.json 的 frontConfig 分组仅更新 saveCert 一条(spec.methods 只放这一条,未放入 getInfo/getCert/saveInfo/getByDomain,避免整条覆盖造成语义漂移;未使用 deleteMethods);响应字段 8 -> 10,method 级 notes 中「响应口径待确认」一条被替换为「响应契约修正」;headers/params/errors 沿用既有条目不变;根版本 0.3.177 -> 0.3.178,updatedAt 保持 2026-09-24", + "通配语义同步写准:certCoversDomain 的 *.example.com 分支(app/service/systems/frontConfig.js:512)要求通配前缀非空且不含「.」,即仅覆盖恰好一级标签;*.a.com 覆盖 b.a.com,不覆盖 x.y.a.com(报 400「证书不合法」)", + "变更记录条目数 639 -> 640(新记录插入数组首位,既有 639 条 version 未改动、未删除);script/update-api-doc.cjs 的 appendChange 仅支持 unshift + 重复 version 拦截,无整条替换既有 change 的能力,故未回改上一条记录的 note", + "无代码结构变化,未重新生成 AI_METHOD_ROUTING.md 与 temp/tmp-service-method-inventory.md(上一轮已刷新,本次仅文档响应口径修正)", + "维护源口径冲突(仅记录,未处理):与上一轮维持一致,methods/*.json 的维护源是否为数据库表 wms_method_doc_meta 仍待用户决策;本次仍按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库" + ], + "module": "frontConfig" + }, + { + "version": "2026.09.24-front-config-migrate-to-frontConfig", + "date": "2026-09-24", + "type": "updated", + "summary": "前端独立部署接口从 setting.warehouse 迁移到 frontConfig 模块:删除 setting.warehouse.getFrontConfig / saveFrontConfig / saveFrontCert 三个旧方法(出口、服务实现与鉴权白名单同步移除,实测调用返回「方法 xxx 不存在」),新增 frontConfig.getInfo / getCert / saveInfo / saveCert 四个需登录、免权限、免鉴权的配置接口(权限由业务层 isWarehouse 判定,仅仓库主体可用);公共按域名拉取接口 frontConfig.getByDomain 保持不变(仍 6 字段公开白名单,免登录免权限免鉴权)。", + "methods": [ + "frontConfig.getInfo", + "frontConfig.getCert", + "frontConfig.saveInfo", + "frontConfig.saveCert", + "setting.warehouse.getFrontConfig", + "setting.warehouse.saveFrontConfig", + "setting.warehouse.saveFrontCert" + ], + "notes": [ + "代码变更:新增出口 app/service/systemMethods/frontConfig.js 的 getInfo/getCert/saveInfo/saveCert(_noNeedRight/_noNeedAuth/_noNeedLog 均含这 4 个方法;_noNeedLogin 仍仅 getByDomain),实现见新增服务 app/service/systems/frontConfig.js(TEXT_FIELDS/PUBLIC_FIELDS 白名单、buildInfoOutput/buildCertOutput/buildPublicOutput)", + "代码变更:app/service/systemMethods/setting/warehouse.js 与 app/service/systems/setting/warehouse.js 中 getFrontConfig/saveFrontConfig/saveFrontCert 的出口与实现已删除,_noNeedRight 收敛为 getSettings,getFieldMeta,saveSettings,getweChatApp;methods/system.json 中 setting.warehouse 分组仅删除这 3 条条目,分组与 getSettings/getFieldMeta/saveSettings 保留", + "文档变更:methods/system.json 删除 setting.warehouse 分组下 3 条旧条目(原 L15632 saveFrontConfig / L15797 getFrontConfig / L15914 saveFrontCert),frontConfig 分组(groupName 前端独立部署模块)新增 4 条条目(isNeedLogin=true、isNeedAuth=false、Authorization 头);frontConfig.getByDomain 条目未改动(未放入本次 spec.methods,避免整条覆盖造成语义漂移);根版本 0.3.176 -> 0.3.177,updatedAt 2026-09-23 -> 2026-09-24", + "saveInfo 口径:upsert 一仓一行;仅受理 title(≤100)/logo_url、favicon_url、login_bg_url(≤255)/theme(合法 JSON 对象或 JSON 字符串),domain 与证书字段由方法层白名单静默忽略;保存即重置同步状态(sync_status=0、sync_attempts=0、清空 last_sync_error/last_synced_at);写库成功后清当前 domain 公共拉取缓存(清缓存失败仅记日志)", + "saveCert 口径:校验链 证书可解析 → 未生效拒绝 → 已过期拒绝 → 私钥与证书 SPKI 配对 → 证书 SAN/CN 覆盖 domain(支持 *.example.com 通配,仅匹配一级标签) → domain 全局唯一;校验链任一失败统一 400「证书不合法」不吐细节;cert_expire_at 以证书 validTo 权威写入;cert_pem/cert_key 直接入库、cert_path/key_path 置 null(等待 script/warehouse-cert-sync.cjs 部署后回填);写库后同时清旧 domain 与新 domain 两个公共缓存 key", + "响应口径待确认:app/service/systems/frontConfig.js saveCert 的 JSDoc(及方法层注释)声明返回证书输出(10 字段含 cert_pem/key_pem),但实现实际 return this.buildInfoOutput(...) 返回 8 字段品牌信息、不含证书字段;本文档按当前实现(8 字段)编写,若确认应返回证书输出需先修正实现再同步文档", + "维护源口径冲突(仅记录,未处理):methods/changes/system.json 既有记录备注「维护源是数据库表 wms_method_doc_meta,methods/*.json 只是导出产物」,仓库内已存在 script/method-doc-*.cjs 工具链与迁移 database/migrations/20260923150000-create-method-doc-tables.js;本次仍按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库,待用户决策是否需要回灌数据库维护源", + "自动清单刷新:node temp/tmp-gen-service-method-inventory.cjs 与 node temp/tmp-update-ai-method-routing.cjs(AI_METHOD_ROUTING.md 第 6 节 SERVICE_METHOD_INVENTORY 标记区与 temp/tmp-service-method-inventory.md 同步刷新,会顺带更新扫描时间与文件/方法计数,属脚本预期行为)", + "docs/*.md 与 README.md 无需同步:检索 getFrontConfig/saveFrontConfig/saveFrontCert/前端独立部署/frontConfig/getByDomain 未命中任何解释性文档(仅 AI_METHOD_ROUTING.md 与 temp/tmp-service-method-inventory.md 含自动清单命中,已由刷新脚本处理)" + ], + "module": "frontConfig" + }, { "version": "2026.09.23-returnReceived-create-is-urgent", "date": "2026-09-23", diff --git a/methods/system.json b/methods/system.json index f239a89..e233805 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.176", - "updatedAt": "2026-09-23", + "version": "0.3.181", + "updatedAt": "2026-09-24", "headers": [ { "name": "platform", @@ -14988,7 +14988,7 @@ "list": [ { "method": "setting.warehouse.getSettings", - "description": "获取当前登录仓库的 subject_config", + "description": "获取当前登录仓库的 subject_config;subject_config 新增大团购打包系数 big_group_pack_coefficient(数字,默认 3,单位秒/单,必须大于 0,用于 workbench 大团购波次打包时长闸门与倒计时)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -15127,6 +15127,12 @@ "required": false, "description": "团购打包最大时长,单位:分钟,默认 40" }, + { + "name": "subject_config.big_group_pack_coefficient", + "type": "number", + "required": false, + "description": "大团购打包系数(数字,默认 3,单位秒/单,必须大于 0;workbench.packOrder 大团购波次倒计时等待秒数 = 当前波次打包数 × 该系数)" + }, { "name": "subject_config.return_unpack_max_record_minutes", "type": "number", @@ -15235,7 +15241,7 @@ }, { "method": "setting.warehouse.getFieldMeta", - "description": "获取仓库设置字段元信息", + "description": "获取仓库设置字段元信息;本次 list 新增「大团购打包系数」(key=big_group_pack_coefficient,type=number,default=3,min=0.1,单位秒/单,用于大团购波次打包时长闸门与倒计时)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -15303,13 +15309,18 @@ "type": "number", "description": "字符串最大长度(可选)" } - ] + ], + "required": true } ], "errors": [ + { + "code": "400", + "message": "未识别到当前仓库,无法操作仓库设置" + }, { "code": "500", - "description": "获取失败" + "message": "获取仓库设置字段信息失败" } ] }, @@ -35390,7 +35401,7 @@ }, { "method": "workbench.packOrder", - "description": "工作台打包上报(免登录、免权限、免鉴权,以工作台 token 鉴权):推荐只传 token + key,订单相关信息(订单号/波次号/运单号)由后端从缓存拉取(前端先经 workbench.queryOrder 扫码拿到 key,20 分钟有效,防篡改);不传 key 时旧参数模式(delivery_order_code 等直传)过渡兼容,后续版本将移除;仓库与工作台均由服务端从 token 解析注入(禁止前端传值);跨仓库/跨工作台消费他人 key 返回 403、key 缺失或过期返回 400(请重新扫码)。打包流程:按发货单号定位订单(current→dispatch 分表),同一工作台存在上一个未结束任务时先关闭(同步回写旧订单打包状态并补确认打印状态,并将工作台绑定摄像头 OSD 复位为「无任务」,新任务 OSD 在其后串行下发避免被复位覆盖),散单去重(传运单号按 order_id+waybill_code、未传按 order_id)、团购按 wave_no 去重后创建打包任务(wms_pack_task,status 归一化为 1=打包中,散单传运单号时 waybill_code 写入流水),写入打包人员(wms_pack_task_packer,自动取该工作台绑定成员 wms_workbench_member)与 operator_text、下发 OSD 到工作台绑定摄像头(散单优先展示打包运单号、团购显示波次号+订单总量,并写 Redis osd_{workbenchId} 缓存)、写操作日志;打包状态变更后主动失效对应工作台 token 缓存,保证 getWorkbenchInfo 尽快返回最新打包信息;团购单(isSandan=0)响应附 batch 波次信息(波次订单数为 current+dispatch 分表实时统计);拦截流程中的订单不允许打包(散单直接拒绝、团购波次静默跳过并视为完成);保留系统日志(systemInit 未声明免日志);成功返回 flag=success、code=200", + "description": "工作台打包上报(免登录、免权限、免鉴权,以工作台 token 鉴权):推荐只传 token + key,订单相关信息(订单号/波次号/运单号)由后端从缓存拉取(前端先经 workbench.queryOrder 扫码拿到 key,20 分钟有效,防篡改);不传 key 时旧参数模式(delivery_order_code 等直传)过渡兼容,后续版本将移除;仓库与工作台均由服务端从 token 解析注入(禁止前端传值);跨仓库/跨工作台消费他人 key 返回 403、key 缺失或过期返回 400(请重新扫码)。打包流程:按发货单号定位订单(current→dispatch 分表),同一工作台存在上一个未结束任务时先关闭(同步回写旧订单打包状态并补确认打印状态,并将工作台绑定摄像头 OSD 复位为「无任务」,新任务 OSD 在其后串行下发避免被复位覆盖),散单去重(传运单号按 order_id+waybill_code、未传按 order_id)、团购按 wave_no 去重后创建打包任务(wms_pack_task,status 归一化为 1=打包中,散单传运单号时 waybill_code 写入流水),写入打包人员(wms_pack_task_packer,自动取该工作台绑定成员 wms_workbench_member)与 operator_text、下发 OSD 到工作台绑定摄像头(散单优先展示打包运单号、团购显示波次号+订单总量,并写 Redis osd_{workbenchId} 缓存)、写操作日志;打包状态变更后主动失效对应工作台 token 缓存,保证 getWorkbenchInfo 尽快返回最新打包信息;团购单(isSandan=0)响应附 batch 波次信息(波次订单数为 current+dispatch 分表实时统计);拦截流程中的订单不允许打包(散单直接拒绝、团购波次静默跳过并视为完成);保留系统日志(systemInit 未声明免日志);成功返回 flag=success、code=200;打包任务落库 wave_scope(波次范围:0=未分配 1=大团购 2=散单 3=小团购 4=单品单件,服务端复查:上报值非法/缺省时兜底订单行值);大团购波次(wave_scope=1)响应附倒计时字段 pack_wait_seconds(当前波次打包数 × 仓库配置大团购打包系数,单位秒)与 pack_start_time(开始打包时间,毫秒时间戳)供前端倒计时,其他波次两字段均为 0", "isNeedAuth": false, "isNeedLogin": false, "isNeedRight": false, @@ -35454,6 +35465,18 @@ "required": true, "description": "任务状态:1=打包中 2=已完成" }, + { + "name": "pack_wait_seconds", + "type": "number", + "required": true, + "description": "大团购倒计时等待秒数(当前波次打包数 × 仓库配置大团购打包系数 big_group_pack_coefficient;仅 wave_scope=1 返回实际值,其他波次为 0)" + }, + { + "name": "pack_start_time", + "type": "number", + "required": true, + "description": "开始打包时间(毫秒时间戳;仅 wave_scope=1 返回实际值,其他波次为 0)" + }, { "name": "batch", "type": "object", @@ -35704,7 +35727,7 @@ }, { "method": "workbench.queryOrder", - "description": "工作台条码查询订单(免登录、免权限、免鉴权,以工作台 token 鉴权):仓库与工作台均由服务端从 token 解析注入(body 传入 warehouse_id/workbench_id 一律忽略,禁止前端传值,防止跨仓库查单),入参条码(运单号);条码→运单记录(wms_order_express,按 waybill_code+warehouse_id+status=1 精确匹配)→ 序列表定位优先、未命中按 current→dispatch 回退遍历订单分表 → 组装查询结果(barcode/waybill_code/isSandan/store_remark/express/order/items/source_table);散单(isSandan=1)order 附拦截/打包 0/1 标志 intercept_flag/pack_flag(拦截标志:拦截状态空值归一化为 none,非 none 记 1;打包标志:按运单维度判定,该运单号已有打包流水 wms_pack_task.waybill_code 命中或历史订单级流水 waybill_code 为空兜底时为 1,否则 0,主单号/子单号互不影响);团购(isSandan=0,波次类型 wave_type=1)附 batch 波次信息(wave_id/wave_no/wave_type/total_orders,total_orders 为 current+dispatch 分表实时统计并带 15s 短缓存兜底);items 逐项合并 stock 详情(sku_property/stock_unit/barcodes/image_url/packing_requirements/need_recheck(是否需要复核:Y=需要 N=不需要(免验)));store_remark 来自合约表 store_warehouse.store_remask;只读查询,不涉及缓存失效;保留系统日志(systemInit 未声明免日志);成功返回 flag=success、code=200;查询成功时生成打包上下文 key(wpck 前缀 + 随机段,Redis 缓存 workbench:packctx:{key},TTL 20 分钟,内容含订单号/波次号/运单号/归属仓库与工作台,后端维护防篡改)并在响应返回 key,供 workbench.packOrder 凭 key 打包", + "description": "工作台条码查询订单(免登录、免权限、免鉴权,以工作台 token 鉴权):仓库与工作台均由服务端从 token 解析注入(body 传入 warehouse_id/workbench_id 一律忽略,禁止前端传值,防止跨仓库查单),入参条码(运单号);条码→运单记录(wms_order_express,按 waybill_code+warehouse_id+status=1 精确匹配)→ 序列表定位优先、未命中按 current→dispatch 回退遍历订单分表 → 组装查询结果(barcode/waybill_code/isSandan/store_remark/express/order/items/source_table);散单(isSandan=1)order 附拦截/打包 0/1 标志 intercept_flag/pack_flag(拦截标志:拦截状态空值归一化为 none,非 none 记 1;打包标志:按运单维度判定,该运单号已有打包流水 wms_pack_task.waybill_code 命中或历史订单级流水 waybill_code 为空兜底时为 1,否则 0,主单号/子单号互不影响);团购(isSandan=0,波次类型 wave_type=1)附 batch 波次信息(wave_id/wave_no/wave_type/total_orders,total_orders 为 current+dispatch 分表实时统计并带 15s 短缓存兜底);items 逐项合并 stock 详情(sku_property/stock_unit/barcodes/image_url/packing_requirements/need_recheck(是否需要复核:Y=需要 N=不需要(免验)));store_remark 来自合约表 store_warehouse.store_remask;只读查询,不涉及缓存失效;保留系统日志(systemInit 未声明免日志);成功返回 flag=success、code=200;查询成功时生成打包上下文 key(wpck 前缀 + 随机段,Redis 缓存 workbench:packctx:{key},TTL 20 分钟,内容含订单号/波次号/运单号/归属仓库与工作台,后端维护防篡改)并在响应返回 key,供 workbench.packOrder 凭 key 打包;order 附 wave_scope(波次范围:0=未分配波次 1=大团购 2=散单 3=小团购 4=单品单件);大团购打包时长闸门:当前工作台存在进行中的 wave_scope=1 打包任务时,未到「当前波次打包数 × 仓库配置大团购打包系数」秒仅允许查询本波次订单,其他波次订单返回错误「打包时长不足」,已到时不受限制", "isNeedAuth": false, "isNeedLogin": false, "isNeedRight": false, @@ -35840,6 +35863,12 @@ "required": false, "description": "波次号" }, + { + "name": "order.wave_scope", + "type": "number", + "required": false, + "description": "波次范围:0=未分配波次 1=大团购 2=散单 3=小团购 4=单品单件(来自订单行 wave_scope)" + }, { "name": "order.post_status", "type": "string", @@ -36093,6 +36122,10 @@ { "code": "0", "message": "未在待处理或配送表中找到订单 [id=xxx, warehouse=xxx](业务失败,返回 flag=failure、code=0)" + }, + { + "code": 0, + "message": "打包时长不足(当前工作台大团购波次 wave_scope=1 打包未到时,扫描其他波次订单被限制;本波次订单不受限)" } ] }, @@ -47293,7 +47326,7 @@ "list": [ { "method": "frontConfig.getByDomain", - "description": "按域名拉取仓库前端公开配置(公共无鉴权接口:免登录、免鉴权、免权限,保留系统日志)。响应仅含公开字段 domain/title/logo_url/login_bg_url/favicon_url/theme,绝不返回 cert_path/key_path/sync_status/sync_attempts/last_sync_error 等内部字段。Redis 缓存 key front:config:domain:{domain}:命中配置缓存 TTL 600s;未登记域名写 configured=false 空缓存 60s 防穿透并返回 404;保存配置时自动失效新旧域名缓存;Redis 异常降级查库。", + "description": "按域名拉取仓库前端公开配置(公共无鉴权接口:免登录、免鉴权、免权限,保留系统日志)。仅放行已验证域名:查库条件为 domain + domain_status=1,未验证(0)/验证失败(2)的域名一律按未配置返回 404「域名未配置」(文案与响应结构未变,仅命中条件收紧);迁移尚未执行(domain_status 列不存在)时降级为仅按 domain 查询并 WARN 一次,保持迁移前行为,迁移完成并重启实例后闸门才真正生效。响应仅含公开字段 domain/title/logo_url/login_bg_url/favicon_url/theme,绝不返回 cert_path/key_path/sync_status/sync_attempts/last_sync_error 等内部字段。Redis 缓存 key front:config:domain:{domain}:命中配置缓存 TTL 600s;未登记域名写 configured=false 空缓存 60s 防穿透并返回 404;保存配置时自动失效新旧域名缓存;Redis 异常降级查库。", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -47355,13 +47388,827 @@ }, { "code": "404", - "message": "域名未配置" + "message": "域名未配置(含域名未登记与域名未通过验证两种情形)" }, { "code": "500", "message": "WarehouseFrontConfig model 不可用/获取前端配置失败" } ] + }, + { + "method": "frontConfig.getInfo", + "description": "查询当前仓库前端独立部署品牌配置(settings 页回显;需登录、免权限、免鉴权,权限由业务层按 isWarehouse 判定,仅仓库主体可调用)。响应仅含品牌与基础字段 warehouse_id/domain/title/logo_url/favicon_url/login_bg_url/theme/updated_at 共 8 项,不含证书与私钥原文、证书路径、证书有效期、同步状态等内部字段(证书回显走 frontConfig.getCert)。仓库未配置过时返回默认空值(字符串字段为空字符串、theme 与 updated_at 为 null),不返回 404。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库ID(取登录用户 store_id;未识别到仓库时报 400)" + }, + { + "name": "domain", + "type": "string", + "required": true, + "description": "仓库自持域名(未配置为空字符串;只能通过 frontConfig.saveCert 变更)" + }, + { + "name": "title", + "type": "string", + "required": true, + "description": "站点标题(未配置为空字符串)" + }, + { + "name": "logo_url", + "type": "string", + "required": true, + "description": "Logo 地址(未配置为空字符串)" + }, + { + "name": "favicon_url", + "type": "string", + "required": true, + "description": "站点 favicon 图标地址(未配置为空字符串)" + }, + { + "name": "login_bg_url", + "type": "string", + "required": true, + "description": "登录页背景图地址(未配置为空字符串)" + }, + { + "name": "theme", + "type": "object", + "required": true, + "description": "主题配置对象(未配置为 null)" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "配置最后更新时间(未配置为 null)" + } + ], + "errors": [ + { + "code": "400", + "message": "未识别到当前仓库,无法操作仓库设置" + }, + { + "code": "403", + "message": "仅仓库主体可配置前端独立部署" + }, + { + "code": "500", + "message": "签约关系服务不可用 / WarehouseFrontConfig model 不可用 / 获取前端配置失败" + } + ], + "notes": [ + "代码位置:出口 app/service/systemMethods/frontConfig.js(_noNeedRight/_noNeedAuth/_noNeedLog 均含 getInfo),实现 app/service/systems/frontConfig.js 的 getInfo", + "安全红线:本接口不输出 cert_pem/key_pem/cert_path/key_path/cert_expire_at/sync_status/sync_attempts/last_sync_error/last_synced_at 等证书与同步内部字段", + "旧接口 setting.warehouse.getFrontConfig 已随本次迁移删除(出口、服务实现与鉴权白名单均已移除),调用返回「方法 xxx 不存在」" + ] + }, + { + "method": "frontConfig.getCert", + "description": "查询当前仓库前端独立部署证书配置(settings 页回显;需登录、免权限、免鉴权,仅仓库主体可调用)。响应含证书原文 cert_pem 与私钥原文 key_pem(key_pem 读 cert_key 列),共 13 项(原有 10 项 + 末尾追加 can_set_cert/can_set_cert_reason/domain_status);私钥原文回显仅限仓库主体登录后的 settings 页,公共无鉴权接口 frontConfig.getByDomain 仍只返回 6 字段公开白名单、绝不返回证书内容。仓库未上传证书时返回默认空值(字符串字段为空字符串、时间与状态字段为 null/0),不返回 404。新增的证书可设置性字段用于前端置灰上传入口:can_set_cert 仅在 domain 非空且 domain_status=1(已验证)时为 true,否则为 false 且 can_set_cert_reason 给出原因(无域名「请先设置域名」/ 未验证「域名待验证」/ 失败「域名验证失败」)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库ID(取登录用户 store_id;未识别到仓库时报 400)" + }, + { + "name": "domain", + "type": "string", + "required": true, + "description": "仓库自持域名(未配置为空字符串)" + }, + { + "name": "cert_pem", + "type": "string", + "required": true, + "description": "证书 PEM 原文(读 cert_pem 列;未上传为空字符串)" + }, + { + "name": "key_pem", + "type": "string", + "required": true, + "description": "私钥 PEM 原文(读 cert_key 列;未上传为空字符串)" + }, + { + "name": "cert_expire_at", + "type": "string", + "required": true, + "description": "证书到期时间(由 frontConfig.saveCert 按证书 validTo 权威写入;未上传为 null)" + }, + { + "name": "sync_status", + "type": "number", + "required": true, + "description": "同步状态(0=待同步;保存/上传即重置为 0)" + }, + { + "name": "sync_attempts", + "type": "number", + "required": true, + "description": "同步尝试次数(保存/上传即重置为 0)" + }, + { + "name": "last_sync_error", + "type": "string", + "required": true, + "description": "最近一次同步失败原因(保存/上传即清空;未发生为空字符串)" + }, + { + "name": "last_synced_at", + "type": "string", + "required": true, + "description": "最近一次同步成功时间(保存/上传即清空;未发生为 null)" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "配置最后更新时间(未配置为 null)" + }, + { + "name": "can_set_cert", + "type": "boolean", + "required": true, + "description": "是否允许上传证书(domain 非空且 domain_status=1 才为 true;仅表示当前可上传,不代表已有证书)" + }, + { + "name": "can_set_cert_reason", + "type": "string", + "required": true, + "description": "不可上传证书的原因文案(可上传为空字符串;无域名为「请先设置域名」,domain_status=0 为「域名待验证」,domain_status=2 为「域名验证失败」)" + }, + { + "name": "domain_status", + "type": "number", + "required": true, + "description": "域名验证状态(0=未验证 / 1=已验证 / 2=验证失败)" + } + ], + "errors": [ + { + "code": "400", + "message": "未识别到当前仓库,无法操作仓库设置" + }, + { + "code": "403", + "message": "仅仓库主体可配置前端独立部署" + }, + { + "code": "500", + "message": "签约关系服务不可用 / WarehouseFrontConfig model 不可用 / 获取前端证书配置失败" + } + ], + "notes": [ + "代码位置:出口 app/service/systemMethods/frontConfig.js 的 getCert,实现 app/service/systems/frontConfig.js 的 getCert(buildCertOutput)", + "响应契约变更(10 → 13 字段):末位追加 can_set_cert(boolean)、can_set_cert_reason(string)、domain_status(number);前 10 字段口径与含义不变", + "can_set_cert_reason 文案与前端提示直接对应:可上传为空字符串,无域名「请先设置域名」,domain_status=0「域名待验证」,domain_status=2「域名验证失败」", + "私钥原文回显口径与旧 setting.warehouse.getFrontConfig 一致(沿用 cert_pem/cert_key 原文回显),但旧方法名与旧分组条目已删除", + "本接口不返回 cert_path/key_path(保存时已置 null,等待外部 crontab 脚本 script/warehouse-cert-sync.cjs 部署后回填)" + ] + }, + { + "method": "frontConfig.saveInfo", + "description": "保存当前仓库前端独立部署品牌配置(upsert 一仓一行,部分更新;需登录、免权限、免鉴权,仅仓库主体可调用)。仅受理 title/logo_url/favicon_url/login_bg_url/theme,其余字段一律忽略:domain 与证书相关字段(domain/cert_pem/key_pem/cert_path/key_path/cert_expire_at)由方法层白名单静默过滤,前端传值不报错也不生效,domain 变更必须走 frontConfig.saveCert(重新校验证书)。保存即视为一次配置变更:同步状态重置为待同步(sync_status=0、sync_attempts=0、清空 last_sync_error/last_synced_at);写库成功后清理当前 domain 的公共拉取缓存(先写库后清缓存,清缓存失败仅记日志不影响保存结果)。响应为保存后的品牌信息(8 字段,不含证书/私钥)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "title", + "type": "string", + "required": false, + "source": "body", + "description": "站点标题(≤100 字符,超长报 400;空值表示清空)" + }, + { + "name": "logo_url", + "type": "string", + "required": false, + "source": "body", + "description": "Logo 地址(≤255 字符,超长报 400;空值表示清空)" + }, + { + "name": "favicon_url", + "type": "string", + "required": false, + "source": "body", + "description": "站点 favicon 图标地址(≤255 字符,超长报 400;空值表示清空)" + }, + { + "name": "login_bg_url", + "type": "string", + "required": false, + "source": "body", + "description": "登录页背景图地址(≤255 字符,超长报 400;空值表示清空)" + }, + { + "name": "theme", + "type": "object", + "required": false, + "source": "body", + "description": "主题配置(合法 JSON 对象或 JSON 字符串,非合法 JSON 对象报 400「theme 必须是合法的 JSON 对象」;空值表示清空)" + } + ], + "response": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库ID" + }, + { + "name": "domain", + "type": "string", + "required": true, + "description": "仓库自持域名(本接口不受理 domain,保持原值;未配置为空字符串)" + }, + { + "name": "title", + "type": "string", + "required": true, + "description": "站点标题(未配置为空字符串)" + }, + { + "name": "logo_url", + "type": "string", + "required": true, + "description": "Logo 地址(未配置为空字符串)" + }, + { + "name": "favicon_url", + "type": "string", + "required": true, + "description": "站点 favicon 图标地址(未配置为空字符串)" + }, + { + "name": "login_bg_url", + "type": "string", + "required": true, + "description": "登录页背景图地址(未配置为空字符串)" + }, + { + "name": "theme", + "type": "object", + "required": true, + "description": "主题配置对象(未配置为 null)" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "配置最后更新时间(未配置为 null)" + } + ], + "errors": [ + { + "code": "400", + "message": "title 长度不能超过 100 字符" + }, + { + "code": "400", + "message": "logo_url / favicon_url / login_bg_url 长度不能超过 255 字符" + }, + { + "code": "400", + "message": "theme 必须是合法的 JSON 对象" + }, + { + "code": "400", + "message": "未识别到当前仓库,无法操作仓库设置" + }, + { + "code": "403", + "message": "仅仓库主体可配置前端独立部署" + }, + { + "code": "409", + "message": "仓库前端配置保存冲突,请稍后重试(并发写入唯一索引冲突兜底)" + }, + { + "code": "500", + "message": "签约关系服务不可用 / WarehouseFrontConfig model 不可用 / 保存前端配置失败" + } + ], + "notes": [ + "代码位置:出口 app/service/systemMethods/frontConfig.js 的 saveInfo(方法层白名单仅透传 title/logo_url/favicon_url/login_bg_url/theme),实现 app/service/systems/frontConfig.js 的 saveInfo", + "domain 与证书字段不受理:domain 变更走 frontConfig.saveCert;cert_* / key_path 等字段由后端权威维护,前端传值被静默忽略", + "旧接口 setting.warehouse.saveFrontConfig 已随本次迁移删除(出口、服务实现与鉴权白名单均已移除),调用返回「方法 xxx 不存在」" + ] + }, + { + "method": "frontConfig.saveCert", + "description": "上传当前仓库前端独立部署证书(证书/私钥成对;需登录、免权限、免鉴权,仅仓库主体可调用)。域名不再作为入参:一律取库内已设置的 domain,且新增前置闸门——无域名返回 400「请先设置并验证域名」,domain_status !== 1 返回 400「域名未通过验证,暂时无法上传证书」(前端若仍传 domain 会被忽略,不报错也不生效)。通过闸门后校验链:证书可解析 → 未生效拒绝 → 已过期拒绝 → 私钥与证书 SPKI 配对 → 证书 SAN/CN 覆盖库内 domain(支持 *.example.com 通配,通配仅覆盖恰好一级标签:*.a.com 覆盖 b.a.com,不覆盖 x.y.a.com,后者同样按「证书不合法」拒绝)。校验链任一失败统一返回 400「证书不合法」,不吐露细节。通过后:cert_expire_at 以证书 validTo 权威写入(忽略前端传值);证书/私钥内容直接写入 cert_pem/cert_key 列,cert_path/key_path 置 null(等待外部 crontab 脚本 script/warehouse-cert-sync.cjs 部署后回填真实路径);同步状态重置为待同步;写库成功后清理当前域名的公共拉取缓存(域名已不能在本接口变更,故只需清一个 key)。响应为保存后的证书输出(13 字段,与 frontConfig.getCert 一致:warehouse_id/domain/cert_pem/key_pem/cert_expire_at/sync_status/sync_attempts/last_sync_error/last_synced_at/updated_at/can_set_cert/can_set_cert_reason/domain_status),不含 cert_path/key_path 路径字段。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pem", + "type": "string", + "required": true, + "source": "body", + "description": "证书 PEM 文本(必填,trim 后非空且 ≤65536 字符;为空报 400「pem 不能为空」,超长报 400「pem 内容长度不能超过 65536 字符」)" + }, + { + "name": "key", + "type": "string", + "required": true, + "source": "body", + "description": "私钥 PEM 文本(必填,与证书成对,trim 后非空且 ≤65536 字符;为空报 400「key 不能为空」,超长报 400「key 内容长度不能超过 65536 字符」)" + } + ], + "response": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库ID(取登录用户 store_id;未识别到仓库时报 400)" + }, + { + "name": "domain", + "type": "string", + "required": true, + "description": "仓库自持域名(未配置为空字符串)" + }, + { + "name": "cert_pem", + "type": "string", + "required": true, + "description": "证书 PEM 原文(读 cert_pem 列;未上传为空字符串)" + }, + { + "name": "key_pem", + "type": "string", + "required": true, + "description": "私钥 PEM 原文(读 cert_key 列;未上传为空字符串)" + }, + { + "name": "cert_expire_at", + "type": "string", + "required": true, + "description": "证书到期时间(由 frontConfig.saveCert 按证书 validTo 权威写入;未上传为 null)" + }, + { + "name": "sync_status", + "type": "number", + "required": true, + "description": "同步状态(0=待同步;保存/上传即重置为 0)" + }, + { + "name": "sync_attempts", + "type": "number", + "required": true, + "description": "同步尝试次数(保存/上传即重置为 0)" + }, + { + "name": "last_sync_error", + "type": "string", + "required": true, + "description": "最近一次同步失败原因(保存/上传即清空;未发生为空字符串)" + }, + { + "name": "last_synced_at", + "type": "string", + "required": true, + "description": "最近一次同步成功时间(保存/上传即清空;未发生为 null)" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "配置最后更新时间(未配置为 null)" + }, + { + "name": "can_set_cert", + "type": "boolean", + "required": true, + "description": "是否允许上传证书(domain 非空且 domain_status=1 才为 true;仅表示当前可上传,不代表已有证书)" + }, + { + "name": "can_set_cert_reason", + "type": "string", + "required": true, + "description": "不可上传证书的原因文案(可上传为空字符串;无域名为「请先设置域名」,domain_status=0 为「域名待验证」,domain_status=2 为「域名验证失败」)" + }, + { + "name": "domain_status", + "type": "number", + "required": true, + "description": "域名验证状态(0=未验证 / 1=已验证 / 2=验证失败)" + } + ], + "errors": [ + { + "code": "400", + "message": "pem 不能为空 / key 不能为空" + }, + { + "code": "400", + "message": "pem 内容长度不能超过 65536 字符 / key 内容长度不能超过 65536 字符" + }, + { + "code": "400", + "message": "请先设置并验证域名" + }, + { + "code": "400", + "message": "域名未通过验证,暂时无法上传证书" + }, + { + "code": "400", + "message": "证书不合法(证书不可解析 / 未生效 / 已过期 / 私钥与证书不配对 / 证书 SAN+CN 未覆盖库内 domain,校验链任一失败统一文案)" + }, + { + "code": "400", + "message": "未识别到当前仓库,无法操作仓库设置" + }, + { + "code": "403", + "message": "仅仓库主体可配置前端独立部署" + }, + { + "code": "409", + "message": "仓库前端配置保存冲突,请稍后重试(并发写入唯一索引冲突兜底)" + }, + { + "code": "500", + "message": "签约关系服务不可用 / WarehouseFrontConfig model 不可用 / 上传前端证书失败" + } + ], + "notes": [ + "代码位置:出口 app/service/systemMethods/frontConfig.js 的 saveCert(只取 pem/key,data.domain 一律忽略),实现 app/service/systems/frontConfig.js 的 saveCert(buildCertOutput)", + "入参变更(不兼容):本次删除 domain 入参(上一轮为 domain/pem/key 三项)。域名唯一性与变更统一由 frontConfig.setDomain 负责,本接口不再做 domain 查重,故不再返回 domain 相关的 400/409 文案", + "前置闸门:无域名 → 400「请先设置并验证域名」;domain_status !== 1 → 400「域名未通过验证,暂时无法上传证书」", + "响应契约变更(10 → 13 字段):在上一轮 10 字段基础上追加 can_set_cert/can_set_cert_reason/domain_status,与 frontConfig.getCert 完全同口径", + "通配语义(certCoversDomain,app/service/systems/frontConfig.js):*.example.com 分支要求通配前缀非空且不含「.」,即仅覆盖恰好一级标签", + "写库内容:cert_pem/cert_key 直接入库(不落暂存文件),cert_path/key_path 置 null 等待定时任务回填,cert_expire_at 取证书 validTo;同步状态同步重置为待同步(sync_status=0、sync_attempts=0、清空 last_sync_error/last_synced_at)" + ] + }, + { + "method": "frontConfig.setDomain", + "description": "设置或变更当前仓库前端独立部署域名,并发起 DNS TXT 归属验证(需登录、免权限、免鉴权,权限由业务层按 isWarehouse 判定,仅仓库主体可调用)。流程:仓库主体校验 → domain 必填/长度(≤100 字符)/形态校验(统一转小写存储)→ 跨仓库唯一校验 → 生成一次性校验子域 verify_host(wmsv-<10 位 hex>.)与校验值 verify_value(32 位 hex)→ upsert 该仓库行并把 domain_status 置 0(未验证)→ 清理新旧域名的公共拉取缓存。查重:域名已被其他仓库使用返回 409「域名 X 已被其他仓库使用」(含并发写入唯一索引冲突兜底)。格式:至少两段标签、每段 1~63 位且仅字母数字与连字符、首尾不得为连字符(天然排除通配符 *、下划线、首尾点与单段主机名),不合法返回 400「domain 格式不正确」;空值返回 400「domain 不能为空」;超长返回 400「domain 长度不能超过 100 字符」。域名变更(仅大小写差异不算变更)会同时清空既有证书(cert_pem/cert_key/cert_path/key_path/cert_expire_at 置空)并重置同步状态(sync_status=0、sync_attempts=0、清空 last_sync_error/last_synced_at),避免 nginx 继续用旧域名证书对外服务;同一域名重复设置时:已验证则幂等返回(不刷新校验码、不清证书、不改验证状态),未验证/验证失败则重发新校验码并清零 attempts/last_error。响应口径与 frontConfig.getDomain 一致(9 字段);domain_status=1 时 verify_host/verify_value 返回空字符串。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "domain", + "type": "string", + "required": true, + "source": "body", + "description": "仓库自持域名(必填,trim 后非空、≤100 字符、全局唯一;统一转小写存储;为空报 400「domain 不能为空」,超长报 400「domain 长度不能超过 100 字符」,形态非法报 400「domain 格式不正确」)" + } + ], + "response": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库ID(取登录用户 store_id;未识别到仓库时报 400)" + }, + { + "name": "domain", + "type": "string", + "required": true, + "description": "仓库自持域名(未设置为空字符串)" + }, + { + "name": "domain_status", + "type": "number", + "required": true, + "description": "域名验证状态(0=未验证 / 1=已验证 / 2=验证失败)" + }, + { + "name": "verify_host", + "type": "string", + "required": true, + "description": "待配置的 TXT 记录主机名(wmsv-<10 位 hex>.;domain_status=1 已验证时返回空字符串)" + }, + { + "name": "verify_value", + "type": "string", + "required": true, + "description": "待配置的 TXT 记录值(32 位 hex;domain_status=1 已验证时返回空字符串)" + }, + { + "name": "cname", + "type": "string", + "required": true, + "description": "CNAME 目标(取自配置 config.frontConfig.cname;未配置为空字符串),未验证时提示把域名 CNAME 指向该目标" + }, + { + "name": "verified_at", + "type": "string", + "required": true, + "description": "域名验证通过时间(未验证/未记录为 null)" + }, + { + "name": "attempts", + "type": "number", + "required": true, + "description": "域名验证尝试次数(setDomain 首次设置/重发校验码时清零;checkDomain 失败与定时任务每轮自增)" + }, + { + "name": "last_error", + "type": "string", + "required": true, + "description": "最近一次验证失败原因(脱敏截断 ≤500 字符;未失败为空字符串)" + } + ], + "errors": [ + { + "code": "400", + "message": "domain 不能为空" + }, + { + "code": "400", + "message": "domain 长度不能超过 100 字符" + }, + { + "code": "400", + "message": "domain 格式不正确(至少两段标签、每段 1~63 位仅字母数字与连字符、首尾不得为连字符)" + }, + { + "code": "400", + "message": "未识别到当前仓库,无法操作仓库设置" + }, + { + "code": "403", + "message": "仅仓库主体可配置前端独立部署" + }, + { + "code": "409", + "message": "域名 {domain} 已被其他仓库使用" + }, + { + "code": "409", + "message": "仓库前端配置保存冲突,请稍后重试(并发写入唯一索引冲突且非 domain 冲突时兜底)" + }, + { + "code": "500", + "message": "签约关系服务不可用 / WarehouseFrontConfig model 不可用 / 设置域名失败" + } + ], + "notes": [ + "代码位置:出口 app/service/systemMethods/frontConfig.js 的 setDomain,实现 app/service/systems/frontConfig.js 的 setDomain(校验码由 buildDomainVerifyCode 生成,输出由 buildDomainOutput 构建)", + "鉴权标记:isNeedLogin=true、isNeedAuth=false;方法层 _noNeedRight/_noNeedLog/_noNeedAuth 均含 setDomain(_noNeedLogin 仍仅 getByDomain)", + "域名全局唯一由应用层校验(assertDomainUnique):可空列唯一索引不约束多个 NULL,非空值唯一性必须应用层兜底;同时捕获 SequelizeUniqueConstraintError 的 domain 字段冲突统一转 409", + "校验目标用一次性随机子域而非裸域名:避免与用户主域已有的其它 TXT 记录(SPF/DKIM/站点校验等)相互干扰", + "缓存:写库成功后清理「旧 domain + 新 domain」两个公共拉取缓存 key(front:config:domain:{domain}),先写库后清缓存;清缓存失败仅记日志,不影响设置结果", + "后续链路:用户按 verify_host/verify_value 配置 TXT 记录后,由 frontConfig.checkDomain 手动触发或 app/schedule/domain_verify_scan.js 定时任务(默认 10m)自动校验;domain_status=1 后 frontConfig.saveCert 才可上传证书、frontConfig.getByDomain 才放行", + "旧口径变更:域名原先只能通过 frontConfig.saveCert 变更,现统一收敛到本接口(saveCert 已移除 domain 入参,前端若仍传会被忽略)" + ] + }, + { + "method": "frontConfig.getDomain", + "description": "查询当前仓库前端独立部署域名与验证状态(settings 页回显;需登录、免权限、免鉴权,仅仓库主体可调用)。响应 9 字段:warehouse_id/domain/domain_status/verify_host/verify_value/cname/verified_at/attempts/last_error。domain_status 语义:0 未验证 / 1 已验证 / 2 验证失败。安全口径:domain_status=1(已验证)时 verify_host/verify_value 返回空字符串(校验令牌已无用途,不再回显);未验证(0/2)时回显本仓库应配置的 TXT 主机名与记录值,并额外返回 cname(取自配置 config.frontConfig.cname),指导用户把域名 CNAME 指向该目标。仓库未设置过域名时返回默认空值(warehouse_id 取当前仓库、domain 为空字符串、domain_status=0、verified_at 为 null、attempts=0、last_error 为空字符串),不返回 404。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库ID(取登录用户 store_id;未识别到仓库时报 400)" + }, + { + "name": "domain", + "type": "string", + "required": true, + "description": "仓库自持域名(未设置为空字符串)" + }, + { + "name": "domain_status", + "type": "number", + "required": true, + "description": "域名验证状态(0=未验证 / 1=已验证 / 2=验证失败)" + }, + { + "name": "verify_host", + "type": "string", + "required": true, + "description": "待配置的 TXT 记录主机名(wmsv-<10 位 hex>.;domain_status=1 已验证时返回空字符串)" + }, + { + "name": "verify_value", + "type": "string", + "required": true, + "description": "待配置的 TXT 记录值(32 位 hex;domain_status=1 已验证时返回空字符串)" + }, + { + "name": "cname", + "type": "string", + "required": true, + "description": "CNAME 目标(取自配置 config.frontConfig.cname;未配置为空字符串),未验证时提示把域名 CNAME 指向该目标" + }, + { + "name": "verified_at", + "type": "string", + "required": true, + "description": "域名验证通过时间(未验证/未记录为 null)" + }, + { + "name": "attempts", + "type": "number", + "required": true, + "description": "域名验证尝试次数(setDomain 首次设置/重发校验码时清零;checkDomain 失败与定时任务每轮自增)" + }, + { + "name": "last_error", + "type": "string", + "required": true, + "description": "最近一次验证失败原因(脱敏截断 ≤500 字符;未失败为空字符串)" + } + ], + "errors": [ + { + "code": "400", + "message": "未识别到当前仓库,无法操作仓库设置" + }, + { + "code": "403", + "message": "仅仓库主体可配置前端独立部署" + }, + { + "code": "500", + "message": "签约关系服务不可用 / WarehouseFrontConfig model 不可用 / 获取域名配置失败" + } + ], + "notes": [ + "代码位置:出口 app/service/systemMethods/frontConfig.js 的 getDomain,实现 app/service/systems/frontConfig.js 的 getDomain(buildDomainOutput)", + "鉴权标记:isNeedLogin=true、isNeedAuth=false;方法层 _noNeedRight/_noNeedLog/_noNeedAuth 均含 getDomain", + "cname 取自配置 config.frontConfig.cname(默认空字符串,非数据库字段),未验证时随本响应返回", + "同一输出口径被 setDomain(设置后回显)与 checkDomain(校验后回显)复用,字段含义一致" + ] + }, + { + "method": "frontConfig.checkDomain", + "description": "主动校验当前仓库前端独立部署域名的 DNS TXT 归属记录并回写库(需登录、免权限、免鉴权,仅仓库主体可调用)。解析目标一律取库内 domain_verify_host(不解析裸域名);解析路径 DoH 为主(config.frontConfig.domainVerify.dohUrl,默认 https://doh.pub/dns-query),DoH 失败降级系统 DNS(node:dns)。成功 → domain_status=1、写入 domain_verified_at、清空 domain_last_error,并清理该域名的公共拉取缓存;失败 → domain_status=2、domain_verify_attempts+1、domain_last_error 写入脱敏截断(≤500 字符)后的原因(如「未解析到 TXT 记录」「TXT 记录未包含校验值」「DNS 解析失败:…」)。无记录或 domain 为空 → 400「请先设置域名」。库内缺少校验码(历史脏数据)时自动补发一份再校验(本次因记录尚未生效仍会记失败);迁移回填的历史行(domain_status=1 但无校验码)直接返回 verified=true 且 resolved_values=[],不会把线上生效中的域名降级为验证失败。响应 = frontConfig.getDomain 的 9 字段 + verified(本次是否通过,boolean)+ resolved_values(本次解析到的 TXT 值,最多 5 条、单条截断 255 字符,排障用)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库ID(取登录用户 store_id;未识别到仓库时报 400)" + }, + { + "name": "domain", + "type": "string", + "required": true, + "description": "仓库自持域名(未设置为空字符串)" + }, + { + "name": "domain_status", + "type": "number", + "required": true, + "description": "域名验证状态(0=未验证 / 1=已验证 / 2=验证失败)" + }, + { + "name": "verify_host", + "type": "string", + "required": true, + "description": "待配置的 TXT 记录主机名(wmsv-<10 位 hex>.;domain_status=1 已验证时返回空字符串)" + }, + { + "name": "verify_value", + "type": "string", + "required": true, + "description": "待配置的 TXT 记录值(32 位 hex;domain_status=1 已验证时返回空字符串)" + }, + { + "name": "cname", + "type": "string", + "required": true, + "description": "CNAME 目标(取自配置 config.frontConfig.cname;未配置为空字符串),未验证时提示把域名 CNAME 指向该目标" + }, + { + "name": "verified_at", + "type": "string", + "required": true, + "description": "域名验证通过时间(未验证/未记录为 null)" + }, + { + "name": "attempts", + "type": "number", + "required": true, + "description": "域名验证尝试次数(setDomain 首次设置/重发校验码时清零;checkDomain 失败与定时任务每轮自增)" + }, + { + "name": "last_error", + "type": "string", + "required": true, + "description": "最近一次验证失败原因(脱敏截断 ≤500 字符;未失败为空字符串)" + }, + { + "name": "verified", + "type": "boolean", + "required": true, + "description": "本次校验是否通过(true=解析到的 TXT 记录包含校验值;false=未通过)" + }, + { + "name": "resolved_values", + "type": "array", + "required": true, + "description": "本次解析到的 TXT 记录值列表(string[],最多 5 条、单条截断 255 字符;未解析到为空数组,用于排障)" + } + ], + "errors": [ + { + "code": "400", + "message": "请先设置域名" + }, + { + "code": "400", + "message": "未识别到当前仓库,无法操作仓库设置" + }, + { + "code": "403", + "message": "仅仓库主体可配置前端独立部署" + }, + { + "code": "500", + "message": "签约关系服务不可用 / WarehouseFrontConfig model 不可用 / 校验域名失败" + } + ], + "notes": [ + "代码位置:出口 app/service/systemMethods/frontConfig.js 的 checkDomain,实现 app/service/systems/frontConfig.js 的 checkDomain(解析走 resolveTxtValues,单行校验走 verifyDomainRecord)", + "鉴权标记:isNeedLogin=true、isNeedAuth=false;方法层 _noNeedRight/_noNeedLog/_noNeedAuth 均含 checkDomain", + "DNS 解析细节:DoH 返回非 200 或响应体非合法 JSON 视为失败并降级系统 DNS;Status=3(NXDOMAIN)或 Status=0 且无 Answer 视为「未解析到记录」返回空数组,不再重复走系统 DNS;两条路径均失败时错误文案为「DNS 解析失败:{脱敏原因}」并写入 domain_last_error", + "与定时任务的关系:本接口为手动触发兜底,与 app/schedule/domain_verify_scan.js 共用同一套解析与落库逻辑(verifyDomainRecord);定时任务对超过 maxAttempts 的行不再自动重试,但仍可通过本接口手动校验", + "脱敏:失败原因统一经 sanitizeErrorText 处理(剥离 PEM 块内容、压缩空白、截断至 500 字符)后落库与回显,不写入原始网络错误/堆栈", + "定时任务 lockTtlSeconds 默认 600s(略大于 interval 10m),避免上一轮未结束时重复加锁" + ] } ] }, diff --git a/test/app/service/systems/workbench.bigGroupTimeGate.regression.test.js b/test/app/service/systems/workbench.bigGroupTimeGate.regression.test.js new file mode 100644 index 0000000..ba8a868 --- /dev/null +++ b/test/app/service/systems/workbench.bigGroupTimeGate.regression.test.js @@ -0,0 +1,443 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const WorkbenchService = require('../../../../app/service/systems/workbench'); + +// 测试环境固定参数:仓库 100000 / 货主 1000000(与 wms-test-agent 约定一致) +const TEST_WAREHOUSE_ID = 100000; +const TEST_STORE_ID = 1000000; +const TEST_ORDER_ID = 9001; +const TEST_WAVE_ID = 5001; +const TEST_OTHER_WAVE_ID = 5002; +const TEST_BARCODE = 'SF1234567890'; +const TEST_WORKBENCH_ID = 200; + +// 大团购打包系数:mock 仓库配置固定为 3(秒/单) +const TEST_COEFFICIENT = 3; + +/** + * 构造待处理/配送分表订单行 fixture。 + * @param {Object} [overrides={}] 字段覆盖。 + * @return {Object} 订单行。 + */ +function buildOrderRow(overrides = {}) { + return { + id: TEST_ORDER_ID, + warehouse_id: TEST_WAREHOUSE_ID, + wave_id: TEST_WAVE_ID, + wave_no: 'W20260830001', + wave_scope: 1, + delivery_order_code: 'DO20260830001', + order_type: 1, + store_id: TEST_STORE_ID, + status: 1, + step: 1, + post_status: null, + pick_status: null, + pack_status: 'none', + intercept_status: 'none', + recheck_status: null, + outbound_status: null, + items_count: 2, + items_total: 2, + items_weight: 500, + source_platform_code: 'PDD', + logistics_name: '顺丰速运', + create_at: '2026-08-30 08:00:00', + updated_at: '2026-08-30 08:00:00', + ...overrides, + }; +} + +/** + * 构造 _queryOrder 回归 harness(mock ctx,不访问数据库)。 + * @param {Object} [options={}] 测试配置。 + * @param {Object} [options.currentTask] 当前工作台进行中的打包任务行(PackTask.findOne 返回值)。 + * @param {boolean} [options.withWorkbench=true] 是否携带 workbench_id(false 模拟无工作台上下文)。 + * @param {Object} [options.orderRow] 订单行覆盖(wave_scope / wave_id 等)。 + * @return {Object} 测试上下文。 + */ +function createQueryOrderHarness(options = {}) { + const orderRow = buildOrderRow(options.orderRow || {}); + const waveBatch = { wave_id: orderRow.wave_id, warehouse_id: TEST_WAREHOUSE_ID, wave_type: 1, total_orders: 99 }; + + const currentModel = { + async findOne() { + return orderRow; + }, + async count() { + return 3; + }, + }; + const dispatchModel = { + async findOne() { + return null; + }, + async count() { + return 4; + }, + }; + const itemsModel = { + async findAll() { + return []; + }, + }; + + const packTaskCalls = { findOne: 0 }; + + const ctx = { + app: { + Sequelize, + config: {}, + async getCacheAsync() { + return null; + }, + async setCacheAsync() { + // mock:写入缓存无操作 + }, + }, + user: { store_id: TEST_WAREHOUSE_ID }, + logger: { info() {}, warn() {}, error() {} }, + service: { + systems: { + deliveryOrder: { + async getStoreSubjectConfig() { + return { big_group_pack_coefficient: TEST_COEFFICIENT }; + }, + }, + stockWarehouse: { + async getStockDetails() { + return []; + }, + }, + }, + }, + model: { + OrderExpress: { + async findOne() { + return { + order_id: TEST_ORDER_ID, + warehouse_id: TEST_WAREHOUSE_ID, + waybill_code: TEST_BARCODE, + logistics_name: '顺丰速运', + weighing_weight: 1000, + package_material_name_snapshot: '快递袋', + }; + }, + }, + OrderDeliveryFactory: { + async getCurrentModel() { + return currentModel; + }, + async getDispatchModel() { + return dispatchModel; + }, + }, + WaveBatch: { + async findOne() { + return waveBatch; + }, + }, + OrderItemsFactory: { + async getCurrentModel() { + return itemsModel; + }, + async getDispatchModel() { + return itemsModel; + }, + }, + StoreWarehouse: { + async findOne() { + return null; + }, + }, + PackTask: { + async findOne(findOptions) { + packTaskCalls.findOne += 1; + if (!options.currentTask) { + return null; + } + // 模拟数据库 where 过滤:wave_scope 不匹配时视为无记录 + const where = findOptions && findOptions.where; + if (where && where.wave_scope !== undefined + && Number(where.wave_scope) !== Number(options.currentTask.wave_scope || 0)) { + return null; + } + return options.currentTask; + }, + }, + }, + }; + + const service = new WorkbenchService(ctx); + + const queryParams = { + barcode: TEST_BARCODE, + warehouseId: String(TEST_WAREHOUSE_ID), + ...(options.withWorkbench === false ? {} : { workbench_id: TEST_WORKBENCH_ID }), + }; + + return { service, ctx, orderRow, packTaskCalls, queryParams }; +} + +/** + * 构造 _packOrder 回归 harness(散单路径 mock,不访问数据库)。 + * @param {Object} [options={}] - { orderWaveScope, waveScopeParam, coefficient } + * @return {Object} 测试上下文(created 数组捕获 PackTask.create 落库数据)。 + */ +function createPackOrderHarness(options = {}) { + const orderRow = buildOrderRow({ + wave_id: 0, + wave_no: '', + wave_scope: options.orderWaveScope === undefined ? 1 : options.orderWaveScope, + }); + + const created = []; + + const orderModel = { + async findOne() { + return orderRow; + }, + async update() { + return [ 1 ]; + }, + }; + + const ctx = { + app: { + Sequelize, + config: {}, + async getCacheAsync() { + return null; + }, + async setCacheAsync() { + // mock:写入缓存无操作 + }, + async delCacheAsync() { + // mock:删除缓存无操作 + }, + }, + logger: { info() {}, warn() {}, error() {} }, + service: { + systems: { + deliveryOrder: { + async getStoreSubjectConfig() { + return { big_group_pack_coefficient: options.coefficient === undefined ? TEST_COEFFICIENT : options.coefficient }; + }, + }, + }, + systemMethods: { + order: { + wave: { + async bumpConfirmPrintUnclaimedWaveVersion() { + // mock:统计版本号递增无操作 + }, + }, + }, + }, + }, + model: { + OrderDeliveryFactory: { + async getCurrentModel() { + return orderModel; + }, + async getDispatchModel() { + return orderModel; + }, + }, + WaveBatch: { + async findOne() { + return null; + }, + }, + OrderExpress: { + async findOne() { + return null; + }, + }, + Workbench: { + async findByPk() { + return { name: '打包台1', device_ids: null, token: 'mock-token' }; + }, + }, + WorkbenchMember: { + async findAll() { + return []; + }, + }, + PackTask: { + async findOne() { + return null; + }, + async findAll() { + return []; + }, + async create(data) { + created.push({ ...data }); + return { id: 777, ...data }; + }, + async destroy() { + return 0; + }, + }, + PackTaskPacker: { + async destroy() { + return 0; + }, + }, + }, + }; + + const service = new WorkbenchService(ctx); + + const packParams = { + delivery_order_code: orderRow.delivery_order_code, + warehouse_id: TEST_WAREHOUSE_ID, + workbench_id: TEST_WORKBENCH_ID, + ...(options.waveScopeParam === undefined ? {} : { wave_scope: options.waveScopeParam }), + }; + + return { service, ctx, orderRow, created, packParams }; +} + +describe('workbench 大团购打包系数回归(wave_scope 落库 / 倒计时下发 / 查询阀门)', () => { + describe('1. queryOrder 响应带波次类型(order.wave_scope)', () => { + it('大团购订单(wave_scope=1)响应返回 order.wave_scope=1', async () => { + const harness = createQueryOrderHarness({ orderRow: { wave_scope: 1 } }); + const result = await harness.service._queryOrder(harness.queryParams); + assert.strictEqual(result.order.wave_scope, 1); + }); + + it('散单波次订单(wave_scope=2)响应返回 order.wave_scope=2', async () => { + const harness = createQueryOrderHarness({ orderRow: { wave_scope: 2 } }); + const result = await harness.service._queryOrder(harness.queryParams); + assert.strictEqual(result.order.wave_scope, 2); + }); + }); + + describe('2. packOrder 信息写入 wms_pack_task(wave_scope 落库)与倒计时字段下发', () => { + it('wave_scope=1:PackTask.create 落库 wave_scope=1,并下发 pack_wait_seconds=打包数×系数 与 pack_start_time>0', async () => { + const harness = createPackOrderHarness({ orderWaveScope: 1, waveScopeParam: 1 }); + const result = await harness.service._packOrder(harness.packParams); + + assert.strictEqual(harness.created.length, 1, '应创建一条打包任务'); + assert.strictEqual(harness.created[0].wave_scope, 1, 'wave_scope=1 应写入打包任务'); + // 散单打包数=1,系数=3 → 等待秒数=3 + assert.strictEqual(result.pack_wait_seconds, 3); + assert.ok(result.pack_start_time > 0, 'wave_scope=1 时应下发开始打包时间'); + }); + + it('未上报 wave_scope:兜底订单行 wave_scope=1 落库,并下发倒计时字段', async () => { + const harness = createPackOrderHarness({ orderWaveScope: 1 }); + const result = await harness.service._packOrder(harness.packParams); + + assert.strictEqual(harness.created[0].wave_scope, 1, '缺省时应兜底订单行 wave_scope=1 落库'); + assert.strictEqual(result.pack_wait_seconds, 3); + assert.ok(result.pack_start_time > 0); + }); + + it('wave_scope=2(非大团购):落库 wave_scope=2,倒计时字段一律为 0', async () => { + const harness = createPackOrderHarness({ orderWaveScope: 2, waveScopeParam: 2 }); + const result = await harness.service._packOrder(harness.packParams); + + assert.strictEqual(harness.created[0].wave_scope, 2); + assert.strictEqual(result.pack_wait_seconds, 0); + assert.strictEqual(result.pack_start_time, 0); + }); + }); + + describe('3. queryOrder 大团购打包时长阀门(wave_scope=1 任务限制,其他不限制)', () => { + it('wave_scope=1 任务未到时 + 查询订单非本波次 → 抛「打包时长不足」', async () => { + const harness = createQueryOrderHarness({ + orderRow: { wave_scope: 1, wave_id: TEST_WAVE_ID }, + currentTask: { + id: 1, + wave_scope: 1, + wave_id: TEST_OTHER_WAVE_ID, + pack_quantity: 10, + start_time: new Date(Date.now() - 5 * 1000), + create_time: new Date(Date.now() - 5 * 1000), + }, + }); + + // 需要 10×3=30 秒,仅过去 5 秒 → 未到时 → 不同波次拦截 + await assert.rejects( + () => harness.service._queryOrder(harness.queryParams), + error => error && error.message === '打包时长不足' + ); + }); + + it('wave_scope=1 任务未到时 + 查询订单为本波次 → 正常返回信息', async () => { + const harness = createQueryOrderHarness({ + orderRow: { wave_scope: 1, wave_id: TEST_OTHER_WAVE_ID }, + currentTask: { + id: 1, + wave_scope: 1, + wave_id: TEST_OTHER_WAVE_ID, + pack_quantity: 10, + start_time: new Date(Date.now() - 5 * 1000), + create_time: new Date(Date.now() - 5 * 1000), + }, + }); + + const result = await harness.service._queryOrder(harness.queryParams); + assert.strictEqual(result.order.wave_id, TEST_OTHER_WAVE_ID); + assert.strictEqual(result.order.wave_scope, 1); + }); + + it('wave_scope=1 任务已到时 + 查询订单非本波次 → 正常返回(不限制)', async () => { + const harness = createQueryOrderHarness({ + orderRow: { wave_scope: 1, wave_id: TEST_WAVE_ID }, + currentTask: { + id: 1, + wave_scope: 1, + wave_id: TEST_OTHER_WAVE_ID, + pack_quantity: 10, + start_time: new Date(Date.now() - 60 * 1000), + create_time: new Date(Date.now() - 60 * 1000), + }, + }); + + // 需要 30 秒,已过 60 秒 → 已到时 → 不拦截 + const result = await harness.service._queryOrder(harness.queryParams); + assert.strictEqual(result.order.wave_id, TEST_WAVE_ID); + }); + + it('当前任务 wave_scope≠1(散单任务)→ 不限制(其他不限制)', async () => { + const harness = createQueryOrderHarness({ + orderRow: { wave_scope: 1, wave_id: TEST_WAVE_ID }, + currentTask: { + id: 1, + wave_scope: 2, + wave_id: TEST_OTHER_WAVE_ID, + pack_quantity: 10, + start_time: new Date(Date.now() - 5 * 1000), + create_time: new Date(Date.now() - 5 * 1000), + }, + }); + + // 任务 wave_scope=2 不匹配阀门 where.wave_scope=1 → 无匹配任务 → 不拦截 + const result = await harness.service._queryOrder(harness.queryParams); + assert.strictEqual(result.order.wave_id, TEST_WAVE_ID); + assert.strictEqual(harness.packTaskCalls.findOne, 1); + }); + + it('无进行中的 wave_scope=1 任务 → 不限制', async () => { + const harness = createQueryOrderHarness({ orderRow: { wave_scope: 1, wave_id: TEST_WAVE_ID } }); + const result = await harness.service._queryOrder(harness.queryParams); + assert.strictEqual(result.order.wave_id, TEST_WAVE_ID); + assert.strictEqual(harness.packTaskCalls.findOne, 1); + }); + + it('无 workbench_id 上下文 → 不触发阀门查询', async () => { + const harness = createQueryOrderHarness({ + withWorkbench: false, + orderRow: { wave_scope: 1, wave_id: TEST_WAVE_ID }, + }); + const result = await harness.service._queryOrder(harness.queryParams); + assert.strictEqual(result.order.wave_id, TEST_WAVE_ID); + assert.strictEqual(harness.packTaskCalls.findOne, 0, '无工作台上下文不应查询打包任务'); + }); + }); +});