Compare commits
11 Commits
f1fb6a7e19
...
3c252a65d3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c252a65d3 | ||
|
|
01454bb916 | ||
|
|
d129103d0b | ||
|
|
aca6867d57 | ||
|
|
81127b61aa | ||
|
|
0a31b3aab1 | ||
|
|
3f5eb49081 | ||
|
|
1cccc6b4a4 | ||
|
|
943c096c5a | ||
|
|
3d2291907e | ||
|
|
c727cd1c5c |
2
.gitignore
vendored
2
.gitignore
vendored
@ -22,6 +22,8 @@ pnpm-debug.log*
|
||||
config/config.local.js
|
||||
config/deploy.config.local.cjs
|
||||
database/config.json
|
||||
# 数据库备份/迁移前快照(本地与临时产物,只留在磁盘,不入库)
|
||||
database/backups/
|
||||
|
||||
native/addons/*.node
|
||||
|
||||
|
||||
@ -294,6 +294,20 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- 数据表:wms_after_sale_type / wms_after_sale_sub_type(app/model/after_sale_type.js、after_sale_sub_type.js)
|
||||
- 接口文档:methods/system.json 分组「售后模块」(module=afterSale),变更记录见 methods/changes/system.json 版本 2026.09.16-after-sale-type-subtype-crud
|
||||
|
||||
## 5.9 index.uploadClientErrorLog(客户端错误日志上报)能力速查
|
||||
|
||||
| method | 实现文件 | 函数 | 登录 | 鉴权/权限 |
|
||||
|---|---|---|---|---|
|
||||
| index.uploadClientErrorLog | app/service/systemMethods/index.js → app/service/systems/client_error_log.js | uploadClientErrorLog / upload | 免登录 | 免权限、免鉴权(systemInit 声明) |
|
||||
|
||||
- 语义:设备端(android/ios/web)将运行时错误日志批量上报暂存到新表 wms_client_error_log,供后台查询分析;免登录、免权限、免鉴权,保留系统日志(不在 INDEX_NO_NEED_LOG_METHODS 清单;index 模块日志口径已由通配符改为显式清单)
|
||||
- 入口:POST /system?method=index.uploadClientErrorLog&v=1×tamp=<数字时间戳>,请求头需 platform/project(根 headers 已声明),无需 Authorization/token
|
||||
- 入参三种形态:单条对象 / 数组 / { logs: [...] }(单次最多 50 条,超限 code=400);字段 snake_case 为主、兼容 camelCase 别名(clientType/appVersion/deviceId/osVersion/deviceModel/errorType/errorMessage/errorStack/reportUuid/clientTime);error_message 与 error_stack 至少一项有值(超长截断 5000/65535)、extra 截断 65535、字符串列宽 client_type 32 / app_version 64 / device_id 128 / os_version 64 / device_model 128 / error_type 64 / report_uuid 64 超出截断;client_time 支持毫秒/秒时间戳与日期字符串(非法存 null,仅参考)
|
||||
- 幂等:report_uuid 唯一索引 uk_report_uuid;重复上报 duplicated +1、静默成功不产生重复行;客户端未传时服务端生成 srv-{uuid}(此时不保证幂等);created_at/updated_at 由 Sequelize 统一取服务器时间
|
||||
- 出参:成功 { flag:'success', code:200, message:'上报成功', success:true, total, accepted, duplicated, rejected, rejected_reasons(≤10 条,每条 { index, reason }), timestamp };失败 400/500 为 HTTP 200 + { flag:'failure', code, message, timestamp }
|
||||
- 表结构:wms_client_error_log(迁移 database/migrations/20260925100000-create-wms-client-error-log.js、模型 app/model/client_error_log.js);索引 uk_report_uuid(唯一)、idx_created_at、idx_client_type_app_version、idx_device_id
|
||||
- 接口文档:methods/system.json 分组「基础模块」(module=index),变更记录见 methods/changes/system.json 版本 `2026.09.25-index-upload-client-error-log`
|
||||
|
||||
## method结束
|
||||
|
||||
## 6. 全量 Service Method 能力清单(自动扫描)
|
||||
@ -305,7 +319,9 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- 临时清单输出:temp/tmp-service-method-inventory.md
|
||||
|
||||
<!-- SERVICE_METHOD_INVENTORY:BEGIN -->
|
||||
自动生成时间: 2026-09-23T17:34:46.974Z
|
||||
自动生成时间: 2026-09-24T13:58:51.474Z
|
||||
(2026-09-25 手动补录:systemMethods/index.js 新增 uploadClientErrorLog、新增 systems/client_error_log.js;生成脚本 tmp-gen-service-method-inventory.cjs 不在仓库,待补齐脚本后重扫)
|
||||
(2026-09-27 手动下线:删除 systems/system_log.js(findCleanupBoundaryId / deleteSystemLogsBatch / cleanupExpiredSystemLogs)—— wms_system_log 表已随迁移 20260927090000-offline-wms-system-log.js 整表下线,文件数 220 -> 219)
|
||||
|
||||
扫描范围: app/service/**/*.js
|
||||
文件数: 219
|
||||
@ -412,8 +428,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- getFrontConfigService, getByDomain, getInfo, getCert, saveInfo, saveCert, setDomain, getDomain, checkDomain
|
||||
- app/service/systemMethods/inbox.js (14)
|
||||
- group, message, v2, after_sales, bindCode, groupList, groupQuickList, groupMembers, groupDisable, groupUpdate, groupReset, groupMessages, retry, reply
|
||||
- app/service/systemMethods/index.js (59)
|
||||
- fastWhereTree, loadStores, loadWarehouses, loadExpressInterfaces, getCOSUploadConfig, getImages, uploadSuccessNotify, recognizeLicensePlate, ReferenceFile, getMessageDetail, test, getI18nMessage, putI18nCollect, extractModule, tryAutoTranslateNewKeys, searchSpace, searchSpaces, listInterfaceTypes, getLocationTypeList, getQimenAppList, getExpressList, getExpressProductTypeList, getPlatformList, getPrintPlatformList, ensureShopPrintPlatformExists, buildShopPrintPlatformInclude, getShopList, requestPddWaybillSearch, requestPddStdTemplates, requestTbWaybillSearch, requestTbCainiaoStdTemplates, requestPolyStdTemplates, getShopExpressList, getCainiaoStfTemplates, normalizeTemplatePlatformCode, normalizeTemplateExpressCode, getExpressPlatformFieldName, getTemplateAllowedExpressCodeSet, filterPrintPlatformTemplateResponseData, getPrintPlatformTemplateCacheKey, requestPrintPlatformTemplateList, resolvePddTemplateWpCodeCandidates, requestPddTemplateSourceList, getPrintPlatformTemplateList, isPlatformOauthReservationDuplicateError, getPlatformOauthReservationCodePrefix, hasPlatformOauthReservationCodePrefix, normalizePlatformOauthReservationCode, generatePlatformOauthReservationCode, createPlatformOauthReservation, getPlatformOauthLink, listenPlatformOauthBind, loginToIm, polyapiAuthorizeUrl, toOrder, getWorkbenchBindCode, LoginWorkbenchByCode, queryUserByToken, parseWechatBadgeCode
|
||||
- app/service/systemMethods/index.js (60)
|
||||
- fastWhereTree, loadStores, loadWarehouses, loadExpressInterfaces, getCOSUploadConfig, getImages, uploadSuccessNotify, recognizeLicensePlate, ReferenceFile, getMessageDetail, test, getI18nMessage, putI18nCollect, extractModule, tryAutoTranslateNewKeys, searchSpace, searchSpaces, listInterfaceTypes, getLocationTypeList, getQimenAppList, getExpressList, getExpressProductTypeList, getPlatformList, getPrintPlatformList, ensureShopPrintPlatformExists, buildShopPrintPlatformInclude, getShopList, requestPddWaybillSearch, requestPddStdTemplates, requestTbWaybillSearch, requestTbCainiaoStdTemplates, requestPolyStdTemplates, getShopExpressList, getCainiaoStfTemplates, normalizeTemplatePlatformCode, normalizeTemplateExpressCode, getExpressPlatformFieldName, getTemplateAllowedExpressCodeSet, filterPrintPlatformTemplateResponseData, getPrintPlatformTemplateCacheKey, requestPrintPlatformTemplateList, resolvePddTemplateWpCodeCandidates, requestPddTemplateSourceList, getPrintPlatformTemplateList, isPlatformOauthReservationDuplicateError, getPlatformOauthReservationCodePrefix, hasPlatformOauthReservationCodePrefix, normalizePlatformOauthReservationCode, generatePlatformOauthReservationCode, createPlatformOauthReservation, getPlatformOauthLink, listenPlatformOauthBind, loginToIm, polyapiAuthorizeUrl, toOrder, getWorkbenchBindCode, LoginWorkbenchByCode, queryUserByToken, parseWechatBadgeCode, uploadClientErrorLog
|
||||
- app/service/systemMethods/order/archiveOrder.js (2)
|
||||
- list, detail
|
||||
- app/service/systemMethods/order/base.js (56)
|
||||
@ -558,6 +574,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- list, detail, create, update, setOsd, _findCameraForControl, _assertPtzSuccess, ptzControl, ptzStop, ptzPresetGoto, ptzPresetSet, delete
|
||||
- app/service/systems/cameraServer.js (5)
|
||||
- list, detail, create, update, delete
|
||||
- app/service/systems/client_error_log.js (5)
|
||||
- _pick, _toText, _parseClientTime, _normalizeItem, upload
|
||||
- app/service/systems/comboGoods.js (15)
|
||||
- fetchStockInfoMap, buildSimpleNotation, buildNameNotation, validateItems, getTargetStoreIdFromMap, checkCustomCodeUniqueForCreate, checkCustomCodeUniqueForUpdate, list, buildListWhere, create, update, delete, search, searchByIdOrCode, enrichComboList
|
||||
- app/service/systems/delivery_order.js (56)
|
||||
@ -576,8 +594,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- buildTree, getTreeByType, buildSubTree, getWithChildrenByType, getAllChildren, getByType, getGroups, getChildrenByPid, getTreeChildrenByPid, create, update, findById, delete
|
||||
- app/service/systems/file.js (2)
|
||||
- getImages, ReferenceFile
|
||||
- app/service/systems/frontConfig.js (42)
|
||||
- createError, getCurrentWarehouseId, deleteCacheByKey, normalizeText, normalizeTheme, assertDomainUnique, getRecordField, sanitizeErrorText, getDomainVerifyConfig, getCnameTarget, buildDomainVerifyCode, parseTxtAnswerData, extractTxtValuesFromAnswers, resolveTxtByDoh, resolveTxtBySystem, resolveTxtValues, verifyDomainRecord, isUnknownColumnError, findVerifiedDomainRecord, verifyPendingDomains, buildInfoOutput, buildCertOutput, getInfo, getCert, getDomain, setDomain, checkDomain, buildDomainOutput, describeDomainStatus, getDomainCacheKey, buildPublicOutput, clearDomainCache, getByDomain, normalizePem, parseCertPem, assertCertValid, collectCertNames, certCoversDomain, validateKeyPem, assertWarehouseSubject, saveInfo, saveCert
|
||||
- app/service/systems/frontConfig.js (50)
|
||||
- createError, getCurrentWarehouseId, deleteCacheByKey, normalizeText, normalizeTheme, assertDomainUnique, getRecordField, sanitizeErrorText, getDomainVerifyConfig, resolveDohUrls, getCnameTarget, buildDomainVerifyCode, parseTxtAnswerData, extractTxtValuesFromAnswers, queryDohEndpoint, resolveTxtByDoh, resolveTxtBySystem, timeoutMs, resolveTxtValues, verifyDomainRecord, isUnknownColumnError, findVerifiedDomainRecord, verifyPendingDomains, buildInfoOutput, buildCertOutput, getInfo, getCert, getDomain, setDomain, promotePendingDomain, checkPendingDomainRecord, checkDomain, buildDomainOutput, buildResolvedValues, describeDomainStatus, getDomainCacheKey, buildPublicOutput, clearDomainCache, clearDomainCaches, buildPendingClearPatch, getByDomain, normalizePem, parseCertPem, assertCertValid, collectCertNames, certCoversDomain, validateKeyPem, assertWarehouseSubject, saveInfo, saveCert
|
||||
- app/service/systems/inbound_direct_log.js (15)
|
||||
- getItems, _addSingleItem, _bindReceivingDetail, addItem, removeItem, commit, notifyEntryOrderCompleted, _queryCompletedEntryItems, _buildCompletedItemLines, buildEntryOrderConfirmRequest, _sendOpenApiCallback, operationLog, qimenEntrySync, _syncReceivingStorageStatus, _applyReceivingStockOccupancy
|
||||
- app/service/systems/inbox/group.js (11)
|
||||
@ -724,8 +742,6 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- createError, getCurrentStoreId, getCurrentAccountId, toPositiveNumber, normalizePage, normalizeStatusFlag, normalizeAuthStatus, normalizeNonNegativeInteger, normalizeInteger, normalizeText, normalizeIntegerRange, normalizeEmail, getPolicyConfigFieldList, getPolicyConfigFieldMetaList, normalizePolicyConfig, getPolicyConfigCacheKey, hasPolicyConfigColumn, loadPolicyConfigByContractId, savePolicyConfigByContractId, getPolicyConfigDefaults, mergePolicyConfigWithDefaults, getEffectivePolicyConfigByContractId, ensureWarehouseSubject, getNoticeService, sendPrintQuantityAdjustNotice, resolveRelationId, normalizeDate, normalizeSignAction, normalizeTempCode, getTempCodeCacheKey, createTempCode, pickRemaskField, resolveRemaskValue, buildCurrentRemaskPatch, requireCurrentRemaskPatch, saveTempSignPayload, getTempSignPayload, clearTempSignPayload, buildTempSignView, getCurrentSubject, getCounterparty, buildListWhereByStoreId, buildListWhere, getRelationIncludes, getQimenContractCacheKey, clearQimenContractCache, getApiInterfaceType, getQimenInterfaceType, resolveQimenCustomerIdByAppKey, getQimenErpNameMapByAppKeys, serializeQimenConfig, getQimenConfigMap, getSingleQimenConfig, resolvePairIds, serializeRelation, findScopedRelation, buildListForStoreWhere, listForStore, exportListForStore, listForWarehouse, list, sign, trimContract, confirmSign, rename, adjustPrintQuantity, queryPrintQuantityLogs, exportPrintQuantityLogs, getPolicyConfigFields, getPolicyConfig, savePolicyConfig, listApiConfig, saveApiConfig, deleteQimenConfig, unbind, getContractConfigCacheKey, invalidateContractConfigCache, getContractConfig, openAccount, createUser
|
||||
- app/service/systems/store.js (22)
|
||||
- normalizeSubjectConfigInput, validateStoreData, checkCompanyNameExists, findByAccountId, findAllEnabled, findAllWarehouses, getStoreName, getStoreRemaskName, createStore, createWarehouse, joinStore, joinWarehouse, ensureEmployeeRoleBinding, assignAdminRoleToCreator, generateJoinToken, sendNotification, sendNotificationToAdmins, getStoreRoles, auditApply, loadStores, loadWarehouses, bindCode
|
||||
- app/service/systems/system_log.js (3)
|
||||
- findCleanupBoundaryId, deleteSystemLogsBatch, cleanupExpiredSystemLogs
|
||||
- app/service/systems/upload.js (19)
|
||||
- getTencentCloudConfig, getCosConfig, initCOS, getUploadParams, hash_hmac, generatePolicyAndSignature, resolveUploadMaxSizeBytes, validateFileInfo, generateFileName, parseSizeToBytes, formatFileSize, getFrontendConfig, uploadFile, uploadBuffer, validateFile, uploadSuccessNotify, getMimeType, createFileReference, handleUploadCallback
|
||||
- app/service/systems/video_record_request.js (15)
|
||||
@ -738,8 +754,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- toOrder, list, detail, export, buildWaybillExportFile
|
||||
- app/service/systems/wechat.js (35)
|
||||
- getAuthUrl, getAccountInfoSync, resolveWechatApp, loginByCode, getMyLoginCode, bindUser, buildBindResult, bindByEmployee, getUserAgreementText, getUserAgreement, setUserAgreement, findWarehouseWechatApp, findLatestAgreementVersion, getAgreementVersion, cleanupUnusedAgreementVersions, pushLoginCode, queryauth, wxaauth, resolveBodyMedia, resolveMediaValue, downloadFromUrl, resolveMediaFilename, registerMiniprogram, updateInfo, buildHeadimgKey, uploadHeadimg, getTemplateList, hasFuncScope, buildAuthorizerPatch, getAuthorizerInfo, commit, submitAudit, buildTrialQrCodeKey, getTrialQRCode, userList
|
||||
- app/service/systems/workbench.js (73)
|
||||
- list, detail, create, update, delete, bindCamera, business, _loadPackCtx, _countWaveOrders, _countWaveOrdersCached, SUM, _sumWaveItemsTotal, _sumWaveItemsTotalCached, _getWaveOrderIds, Set, _buildPackChangeSummary, _writePackOperationLog, _updateOrderPackStatus, _packOrder, resolvePackTaskEndTime, _finishPack, _resetPackOsd, _sendWeight, _writeWeighOpLog, _aggregateWaveItems, _fetchWaveItemsSummary, _fetchOrderItemsDetail, _queryOrder, generatePackCtxKey, getWorkbenchPackCtxCacheKey, getWorkbenchBindClientCacheKey, getWorkbenchBindCodeCacheKey, getWorkbenchTokenCacheKey, generateRandomChars, generateWorkbenchToken, generateWorkbenchLoginCode, normalizeWorkbenchBindCode, generateUniqueWorkbenchLoginCode, createUniqueWorkbenchClientCode, createUniqueWorkbenchBindCode, buildWorkbenchBindState, getWorkbenchBindRemainingSeconds, setWorkbenchBindState, createWorkbenchBindSession, refreshWorkbenchBindCode, formatWorkbenchBindData, waitForWorkbenchBindComplete, getWorkbenchBindCode, formatWorkbenchTokenInfo, listWorkbenchMembers, listCurrentPackTasks, buildCurrentPackingInfo, invalidateWorkbenchTokenCacheByWorkbenchId, buildWorkbenchTokenInfo, bindWorkbench, getWorkbenchInfoByToken, _round2, _formatPackCountTime, buildWorkbenchPackCountTimeRange, getWorkbenchCountByToken, loginWorkbenchByCode, resetLoginCode, clearExpiredWorkbenchTokens, resolveWorkbenchContext, resolveWorkbenchByToken, packOrderByToken, finishPackByToken, sendWeightByToken, queryOrderByToken, normalizeWorkbenchMemberIds, _finishAllPackTasksByMemberLogout, removeWorkbenchMember, bindWorkbenchMember
|
||||
- app/service/systems/workbench.js (75)
|
||||
- list, detail, create, update, delete, bindCamera, business, _loadPackCtx, _countWaveOrders, _countWaveOrdersCached, SUM, _sumWaveItemsTotal, _sumWaveItemsTotalCached, _getWaveOrderIds, Set, _buildPackChangeSummary, _writePackOperationLog, _updateOrderPackStatus, _packOrder, resolvePackTaskEndTime, _finishPack, _resetPackOsd, _sendWeight, _writeWeighOpLog, _aggregateWaveItems, _fetchWaveItemsSummary, _fetchOrderItemsDetail, _countCurrentPackMembers, _getBigGroupPackCoefficient, _queryOrder, generatePackCtxKey, getWorkbenchPackCtxCacheKey, getWorkbenchBindClientCacheKey, getWorkbenchBindCodeCacheKey, getWorkbenchTokenCacheKey, generateRandomChars, generateWorkbenchToken, generateWorkbenchLoginCode, normalizeWorkbenchBindCode, generateUniqueWorkbenchLoginCode, createUniqueWorkbenchClientCode, createUniqueWorkbenchBindCode, buildWorkbenchBindState, getWorkbenchBindRemainingSeconds, setWorkbenchBindState, createWorkbenchBindSession, refreshWorkbenchBindCode, formatWorkbenchBindData, waitForWorkbenchBindComplete, getWorkbenchBindCode, formatWorkbenchTokenInfo, listWorkbenchMembers, listCurrentPackTasks, buildCurrentPackingInfo, invalidateWorkbenchTokenCacheByWorkbenchId, buildWorkbenchTokenInfo, bindWorkbench, getWorkbenchInfoByToken, _round2, _formatPackCountTime, buildWorkbenchPackCountTimeRange, getWorkbenchCountByToken, loginWorkbenchByCode, resetLoginCode, clearExpiredWorkbenchTokens, resolveWorkbenchContext, resolveWorkbenchByToken, packOrderByToken, finishPackByToken, sendWeightByToken, queryOrderByToken, normalizeWorkbenchMemberIds, _finishAllPackTasksByMemberLogout, removeWorkbenchMember, bindWorkbenchMember
|
||||
- app/service/warehouse.js (7)
|
||||
- resolveWarehouseMethod, getWarehouseMethodService, dispatchWarehouseMethod, validateWarehouseParams, parseJsonBody, normalizeSignFields, processRequest
|
||||
- app/service/warehouseMethods/inbox.js (2)
|
||||
@ -802,6 +818,10 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
190
app/lib/api_log_sink.js
Normal file
190
app/lib/api_log_sink.js
Normal file
@ -0,0 +1,190 @@
|
||||
// app/lib/api_log_sink.js
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 接口日志落盘器:接口流水经 Egg 日志写出(`wms_system_log` 表已下线删除)。
|
||||
*
|
||||
* 设计要点:
|
||||
* 1. 只使用 Egg 自带 logger(`app.getLogger('apiLog')`),不自行操作 fs ——
|
||||
* egg-logger 的 FileTransport 以 O_APPEND 追加写、多 worker 共写同一文件、
|
||||
* 自动创建目录并按天轮转,避免自建写流带来的「轮转后句柄失效 / ENOSPC 崩进程 /
|
||||
* 每请求建流导致 fd 泄漏 / 退出前未 flush」等问题。
|
||||
* 2. 一行一条记录,形如 `HH:mm:ss {JSON}`:
|
||||
* 前缀是**本地时区的时分秒**,只给人眼定位用(tail/grep 时有个时间锚点),
|
||||
* 机器解析请用行内的 `created_at`(ISO 8601 UTC,无时区歧义,与前缀为同一时刻);
|
||||
* 前缀之后是沿用旧 `wms_system_log` 表结构的平铺 JSON(不嵌套,首字符是 `{`),
|
||||
* 可直接用 grep 搜索;用 jq 时先剥前缀:`jq -R 'sub("^[0-9:]+ "; "") | fromjson'`。
|
||||
* 3. 写入失败绝不影响接口返回:异常由调用方兜底,只记 app logger。
|
||||
*/
|
||||
|
||||
/** body / result 截断长度:沿用旧 wms_system_log 入库时的长文本上限(65535) */
|
||||
const TEXT_LIMIT = 65535;
|
||||
|
||||
/** customLogger.apiLog 缺失的告警只打一次,避免每请求刷屏 */
|
||||
let warnedApiLogMissing = false;
|
||||
|
||||
/**
|
||||
* 归一化为字符串,必要时截断。
|
||||
* @param {*} value 原始值。
|
||||
* @param {number} [limit] 截断长度(正数才生效),默认不截断。
|
||||
* @return {string} 字符串结果。
|
||||
*/
|
||||
function toText(value, limit) {
|
||||
if (value === undefined || value === null) {
|
||||
return '';
|
||||
}
|
||||
// 对象/数组一律 JSON 序列化:调用方若漏了 JSON.stringify(例如 controller 直接把
|
||||
// 响应对象塞进 logData.result),String() 会得到 "[object Object]" 而丢掉内容。
|
||||
let text;
|
||||
if (typeof value === 'string') {
|
||||
text = value;
|
||||
} else if (typeof value === 'object') {
|
||||
try {
|
||||
text = JSON.stringify(value);
|
||||
} catch (e) {
|
||||
text = String(value);
|
||||
}
|
||||
} else {
|
||||
text = String(value);
|
||||
}
|
||||
if (Number(limit) > 0 && text.length > Number(limit)) {
|
||||
return text.substring(0, Number(limit));
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造一行平铺记录。
|
||||
*
|
||||
* 字段与顺序沿用旧 `wms_system_log` 入库时的入参:
|
||||
* method / v / url / headers / auth / created_at / body / result / use_time / store_id / device。
|
||||
* `created_at` 统一写 ISO 8601(UTC,带 Z):与原入库是同一时刻,但没有时区歧义。
|
||||
*
|
||||
* @param {object} logData 原始日志数据。
|
||||
* @param {object} [options] 选项。
|
||||
* @param {number} [options.startTime] 请求开始时间戳(ms),用于计算 use_time。
|
||||
* @param {number} [options.useTime] 直接指定耗时(ms),优先于 startTime。
|
||||
* @param {string} [options.device] 设备标识。
|
||||
* @param {Date} [options.createdAt] 记录时间,默认当前时间。
|
||||
* @return {object} 平铺记录对象。
|
||||
*/
|
||||
function buildRecord(logData, options = {}) {
|
||||
const source = logData && typeof logData === 'object' ? logData : {};
|
||||
const createdAt = options.createdAt instanceof Date ? options.createdAt : new Date();
|
||||
|
||||
let useTime = 0;
|
||||
if (options.useTime !== undefined) {
|
||||
useTime = Number(options.useTime);
|
||||
} else if (Number(options.startTime) > 0) {
|
||||
useTime = Date.now() - Number(options.startTime);
|
||||
}
|
||||
if (!Number.isFinite(useTime) || useTime < 0) {
|
||||
useTime = 0;
|
||||
}
|
||||
|
||||
return {
|
||||
method: toText(source.method),
|
||||
v: toText(source.v),
|
||||
url: toText(source.url),
|
||||
headers: toText(source.headers),
|
||||
auth: toText(source.auth),
|
||||
created_at: createdAt.toISOString(),
|
||||
body: toText(source.body, TEXT_LIMIT),
|
||||
result: toText(source.result, TEXT_LIMIT),
|
||||
use_time: useTime,
|
||||
store_id: source.store_id || null,
|
||||
device: toText(options.device),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* customLogger.apiLog 缺失时的显式告警(每个 worker 只打一次)。
|
||||
*
|
||||
* egg 的 `app.getLogger(name)` 对未声明的 name 返回 null 而不抛错,
|
||||
* 若不处理就会「日志静默消失、且无任何报错」。
|
||||
* 生产 config 不参与 deploy,「代码已上线、配套配置没上」极易发生,故必须显式报出来。
|
||||
*
|
||||
* @param {Egg.Application} app Egg 应用实例。
|
||||
* @return {void}
|
||||
*/
|
||||
function warnApiLogMissing(app) {
|
||||
if (warnedApiLogMissing) {
|
||||
return;
|
||||
}
|
||||
warnedApiLogMissing = true;
|
||||
const logger = app && typeof app.getLogger === 'function' ? app.getLogger('logger') : null;
|
||||
if (logger && typeof logger.error === 'function') {
|
||||
logger.error(
|
||||
'[api_log_sink] config.customLogger.apiLog 未配置,接口日志不会落盘!' +
|
||||
'请在 config.default.js 补上 customLogger.apiLog' +
|
||||
'(生产 config 不参与 deploy,需手工同步到线上)。'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 两位补零。
|
||||
* @param {number} value 待补零的数字。
|
||||
* @return {string} 补零后的字符串。
|
||||
*/
|
||||
function pad2(value) {
|
||||
return String(value).padStart(2, '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成日志行的时间前缀(本地时区 `HH:mm:ss`)。
|
||||
*
|
||||
* 整行内容本身是完整 JSON(首字符是 `{`),直接 tail/grep 时没有时间锚点,
|
||||
* 故在行首加一个本地时间的时分秒前缀。前缀只给人看:
|
||||
* 它与行内 `created_at` 取同一时刻,仅表达方式不同(本地 `HH:mm:ss` vs UTC ISO 8601)。
|
||||
* 日期无需前缀 —— 日志按天轮转为 `wms-api.log.YYYY-MM-DD`,日期由文件名提供。
|
||||
*
|
||||
* @param {Date|string} [value] 记录时间;缺省或非法时回退当前时间。
|
||||
* @return {string} `HH:mm:ss` 形式的前缀。
|
||||
*/
|
||||
function formatTimePrefix(value) {
|
||||
const parsed = value instanceof Date ? value : new Date(value || Date.now());
|
||||
const date = Number.isNaN(parsed.getTime()) ? new Date() : parsed;
|
||||
return `${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写出接口日志。
|
||||
*
|
||||
* 只落 Egg 日志文件(`config.customLogger.apiLog`);wms_system_log 表已下线,
|
||||
* 不再存在任何入库分支。
|
||||
*
|
||||
* @param {Egg.Application} app Egg 应用实例。
|
||||
* @param {object} payload 负载。
|
||||
* @param {object} payload.logData 原始日志数据。
|
||||
* @param {number} [payload.startTime] 请求开始时间戳(ms)。
|
||||
* @param {number} [payload.useTime] 直接指定耗时(ms)。
|
||||
* @param {string} [payload.device] 设备标识。
|
||||
* @param {Date} [payload.createdAt] 记录时间。
|
||||
* @return {Promise<object>} 实际写出的平铺记录。
|
||||
*/
|
||||
async function write(app, payload = {}) {
|
||||
const record = buildRecord(payload.logData, {
|
||||
startTime: payload.startTime,
|
||||
useTime: payload.useTime,
|
||||
device: payload.device,
|
||||
createdAt: payload.createdAt,
|
||||
});
|
||||
|
||||
const logger = app && typeof app.getLogger === 'function' ? app.getLogger('apiLog') : null;
|
||||
if (logger) {
|
||||
// 一行一条:`HH:mm:ss {完整 JSON}`,前缀与行内 created_at 是同一时刻
|
||||
logger.info(`${formatTimePrefix(record.created_at)} ${JSON.stringify(record)}`);
|
||||
} else {
|
||||
warnApiLogMissing(app);
|
||||
}
|
||||
|
||||
return record;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
TEXT_LIMIT,
|
||||
buildRecord,
|
||||
formatTimePrefix,
|
||||
write,
|
||||
};
|
||||
112
app/model/client_error_log.js
Normal file
112
app/model/client_error_log.js
Normal file
@ -0,0 +1,112 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 客户端错误日志暂存表模型(wms_client_error_log)。
|
||||
*
|
||||
* Android/iOS/Web 等设备端通过 index.uploadClientErrorLog 上报的运行时错误日志暂存,
|
||||
* 仅做数据落库供人工/后台查询分析;report_uuid 唯一索引承担幂等去重(重复上报静默成功)。
|
||||
* created_at/updated_at 由 Sequelize 时间戳统一取服务器当前时间,不采信客户端时间。
|
||||
*
|
||||
* @param {import('egg').Application} app Egg 应用实例。
|
||||
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, DATE, TEXT } = app.Sequelize;
|
||||
|
||||
const ClientErrorLog = app.model.define('client_error_log', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键ID',
|
||||
},
|
||||
client_type: {
|
||||
type: STRING(32),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '客户端类型:android/ios/web 等',
|
||||
},
|
||||
app_version: {
|
||||
type: STRING(64),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '客户端版本号',
|
||||
},
|
||||
device_id: {
|
||||
type: STRING(128),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '设备唯一标识',
|
||||
},
|
||||
os_version: {
|
||||
type: STRING(64),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '操作系统版本',
|
||||
},
|
||||
device_model: {
|
||||
type: STRING(128),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '设备型号',
|
||||
},
|
||||
error_type: {
|
||||
type: STRING(64),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '错误类型/等级',
|
||||
},
|
||||
error_message: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '错误信息(服务端截断上限 5000 字符)',
|
||||
},
|
||||
error_stack: {
|
||||
type: TEXT('medium'),
|
||||
allowNull: true,
|
||||
comment: '错误堆栈(服务端截断上限 65535 字符)',
|
||||
},
|
||||
extra: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '附加上下文(JSON 字符串,服务端截断上限 65535 字符)',
|
||||
},
|
||||
report_uuid: {
|
||||
type: STRING(64),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '客户端上报幂等ID(唯一索引,重复上报静默成功)',
|
||||
},
|
||||
client_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '客户端错误发生时间(仅参考,不作为记录时间)',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '服务端写入时间(统一取服务器当前时间)',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_client_error_log',
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: false,
|
||||
comment: '客户端错误日志暂存表(设备端运行时错误上报暂存)',
|
||||
indexes: [
|
||||
{ name: 'uk_report_uuid', unique: true, fields: [ 'report_uuid' ] },
|
||||
{ name: 'idx_created_at', fields: [ 'created_at' ] },
|
||||
{ name: 'idx_client_type_app_version', fields: [ 'client_type', 'app_version' ] },
|
||||
{ name: 'idx_device_id', fields: [ 'device_id' ] },
|
||||
],
|
||||
});
|
||||
|
||||
return ClientErrorLog;
|
||||
};
|
||||
@ -30,6 +30,26 @@ module.exports = app => {
|
||||
allowNull: false,
|
||||
comment: '查询过的运单号',
|
||||
},
|
||||
group_id: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '触发查询的群ID(站内信外部群ID)',
|
||||
},
|
||||
group_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '触发查询的群名称',
|
||||
},
|
||||
user_id: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '触发查询的用户ID(站内信外部用户ID)',
|
||||
},
|
||||
user_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '触发查询的用户名称',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
|
||||
@ -1,94 +0,0 @@
|
||||
// app/model/system_log.js
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TEXT, DATE, INTEGER } = app.Sequelize;
|
||||
|
||||
const SystemLog = app.model.define('wms_system_log', {
|
||||
id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: 'ID',
|
||||
},
|
||||
method: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '方法名',
|
||||
},
|
||||
v: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '版本',
|
||||
},
|
||||
url: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '请求URL',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '创建时间',
|
||||
},
|
||||
body: {
|
||||
type: TEXT('long'),
|
||||
allowNull: true,
|
||||
comment: '请求体',
|
||||
},
|
||||
result: {
|
||||
type: TEXT('long'),
|
||||
allowNull: true,
|
||||
comment: '响应体',
|
||||
},
|
||||
use_time: {
|
||||
type: INTEGER,
|
||||
allowNull: true,
|
||||
comment: '耗时',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '更新时间',
|
||||
},
|
||||
delete_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '删除时间',
|
||||
},
|
||||
headers: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '请求头',
|
||||
},
|
||||
auth: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '认证信息',
|
||||
},
|
||||
store_id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '门店ID',
|
||||
},
|
||||
device: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '设备',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_system_log',
|
||||
timestamps: false,
|
||||
underscored: false,
|
||||
comment: '系统日志表',
|
||||
indexes: [
|
||||
{
|
||||
name: 'store_id',
|
||||
fields: [ 'store_id' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return SystemLog;
|
||||
};
|
||||
@ -11,6 +11,12 @@
|
||||
* 判断,不单独保留证书 status 列。
|
||||
* - domain_status 状态机:0-未验证,1-已验证(DNS TXT 校验通过),2-验证失败;
|
||||
* 未验证/验证失败的域名禁止上传证书与对外公共拉取,管理后台设置域名后回落到 0。
|
||||
* - 两阶段域名切换(方案 B):生效域名 domain 只在 DNS TXT 校验通过时由
|
||||
* frontConfig.promotePendingDomain 切换;frontConfig.setDomain 只把新域名登记在
|
||||
* pending_domain(+ pending_verify_host/token 校验码),旧域名全程可用(不会出现
|
||||
* 「页面能打开但公共配置 404」的中间态);提升时旧域名写入 retired_domain 下线队列
|
||||
* (由外部证书脚本删除其 nginx 配置与证书文件后置 NULL)、清空证书 5 列并重置同步 4 列
|
||||
* (域名已变,证书必须重新上传)。
|
||||
* - domain 唯一索引(uk_domain)为 MySQL 可空列唯一索引:允许多个 NULL,
|
||||
* 应用层在写入非空 domain 前必须做唯一性校验,不能依赖数据库约束报错。
|
||||
* - store_id 唯一索引(uk_store_id):每仓一行,由数据库层保证。
|
||||
@ -83,6 +89,47 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '最近一次域名验证失败原因',
|
||||
},
|
||||
pending_domain: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '待验证域名:setDomain 只登记到本列,TXT 校验通过后才提升为生效域名 domain',
|
||||
},
|
||||
pending_verify_host: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '待验证域名的 TXT 记录主机名(wmsv-<随机码>.<待验证域名>)',
|
||||
},
|
||||
pending_verify_token: {
|
||||
type: STRING(64),
|
||||
allowNull: true,
|
||||
comment: '待验证域名的 TXT 记录值(32 位 hex)',
|
||||
},
|
||||
pending_verify_attempts: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '待验证域名校验尝试次数',
|
||||
},
|
||||
pending_last_error: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '待验证域名最近一次失败原因',
|
||||
},
|
||||
pending_created_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '发起域名切换的时间',
|
||||
},
|
||||
retired_domain: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '待下线旧域名:域名提升时写入,外部证书脚本删除其 nginx 配置与证书文件后置 NULL',
|
||||
},
|
||||
retired_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '旧域名进入下线队列的时间',
|
||||
},
|
||||
title: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
@ -202,6 +249,14 @@ module.exports = app => {
|
||||
name: 'idx_domain_status',
|
||||
fields: [ 'domain_status' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_pending_domain',
|
||||
fields: [ 'pending_domain' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_retired_domain',
|
||||
fields: [ 'retired_domain' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
|
||||
@ -1,88 +0,0 @@
|
||||
// app/schedule/system_log_cleanup.js
|
||||
'use strict';
|
||||
|
||||
/** @type {number} 默认单批硬删除行数 */
|
||||
const DEFAULT_BATCH_SIZE = 2000;
|
||||
/** @type {number} 默认批间休眠最小毫秒数 */
|
||||
const DEFAULT_SLEEP_MIN_MS = 100;
|
||||
/** @type {number} 默认批间休眠最大毫秒数 */
|
||||
const DEFAULT_SLEEP_MAX_MS = 500;
|
||||
|
||||
/**
|
||||
* 系统日志超期清理定时任务。
|
||||
*
|
||||
* 默认每日凌晨 03:00:00(cron:秒 分 时 日 月 周)在单 worker 中执行一次,
|
||||
* 硬删除 wms_system_log 超过保留天数(默认 60 天)的日志以释放磁盘空间,避开 08:00–23:00 业务高峰。
|
||||
* cron 从 config.systemLogCleanup.cron 读取(config.default.js 提供默认值),
|
||||
* 本地环境可在 config.local.js 覆盖为短间隔以便快速验证,不影响生产 03:00 触发时间。
|
||||
* 保留天数由 service.systems.systemLog 读取 config.systemLogCleanup.retainDays(默认 60,非法值回退 60);
|
||||
* 由 config.systemLogCleanup 控制:enable=false 时不注册本任务;
|
||||
* 实际清理逻辑收敛在 service.systems.systemLog.cleanupExpiredSystemLogs。
|
||||
*
|
||||
* @param {Object} app Egg 应用实例。
|
||||
* @return {Object} 定时任务定义(含 schedule 与 task)。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const cleanupConfig = (app.config && app.config.systemLogCleanup) || {};
|
||||
// cron 从配置读取,缺省时回退为每日凌晨 03:00(cron 格式:秒 分 时 日 月 周)
|
||||
const cleanupCron = typeof cleanupConfig.cron === 'string' && cleanupConfig.cron
|
||||
? cleanupConfig.cron
|
||||
: '0 0 3 * * *';
|
||||
|
||||
return {
|
||||
schedule: {
|
||||
cron: cleanupCron,
|
||||
type: 'worker',
|
||||
immediate: false,
|
||||
disable: cleanupConfig.enable === false,
|
||||
},
|
||||
|
||||
/**
|
||||
* 执行系统日志超期清理。
|
||||
*
|
||||
* 采用单 worker 防重入:上一轮未结束时跳过本轮;
|
||||
* 任务失败只记录错误日志,不向上抛出,避免导致 schedule 崩溃。
|
||||
*
|
||||
* @param {Object} ctx Egg 上下文。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async task(ctx) {
|
||||
const scheduleName = 'system_log_cleanup';
|
||||
|
||||
if (ctx.app._systemLogCleanupRunning) {
|
||||
ctx.logger.info(`[${scheduleName}] 本轮任务跳过,上一轮尚未结束`);
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.app._systemLogCleanupRunning = true;
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
const config = ctx.app.config.systemLogCleanup || {};
|
||||
// 保留天数(retainDays)由 service 读取 config.systemLogCleanup.retainDays 自行解析,此处不再透传
|
||||
const options = {
|
||||
batchSize: Number(config.batchSize) > 0
|
||||
? Math.floor(Number(config.batchSize))
|
||||
: DEFAULT_BATCH_SIZE,
|
||||
sleepMinMs: Number(config.sleepMinMs) >= 0
|
||||
? Math.floor(Number(config.sleepMinMs))
|
||||
: DEFAULT_SLEEP_MIN_MS,
|
||||
sleepMaxMs: Number(config.sleepMaxMs) >= 0
|
||||
? Math.floor(Number(config.sleepMaxMs))
|
||||
: DEFAULT_SLEEP_MAX_MS,
|
||||
};
|
||||
|
||||
const summary = await ctx.service.systems.systemLog.cleanupExpiredSystemLogs(options);
|
||||
|
||||
ctx.logger.info(
|
||||
`[${scheduleName}] 本轮完成 skipped=${summary.skipped} boundary_id=${summary.boundary_id}`
|
||||
+ ` batches=${summary.batch_count} deleted=${summary.deleted_rows}`
|
||||
+ ` duration=${Date.now() - startedAt}ms`
|
||||
);
|
||||
} catch (error) {
|
||||
ctx.logger.error(`[${scheduleName}] 执行失败: ${error.message}`);
|
||||
} finally {
|
||||
ctx.app._systemLogCleanupRunning = false;
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
@ -1698,6 +1698,10 @@ class InboxFunctionsService extends Service {
|
||||
waybill_code: waybill,
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
group_id: ctx.inboxContext?.group_id,
|
||||
group_name: ctx.inboxContext?.group_name,
|
||||
user_id: ctx.inboxContext?.user_id,
|
||||
user_name: ctx.inboxContext?.user_name,
|
||||
});
|
||||
|
||||
const warehouseLabel = result.warehouse_name || '仓库';
|
||||
|
||||
@ -2,6 +2,8 @@
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
const apiLogSink = require('../lib/api_log_sink');
|
||||
|
||||
class pdaService extends Service {
|
||||
async callMethod(className, actionName, requestData, authHeader) {
|
||||
try {
|
||||
@ -62,10 +64,13 @@ class pdaService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存接口日志到系统日志模型
|
||||
* 保存接口日志。
|
||||
*
|
||||
* 经 Egg logger(apiLog)平铺写出到日志文件;wms_system_log 表已下线,不再有任何入库路径。
|
||||
*
|
||||
* @param {Object} logData 日志数据
|
||||
* @param {number} startTime 开始时间戳
|
||||
* @return {Promise<Object|undefined>} 写入结果
|
||||
* @return {Promise<Object|undefined>} 写出的平铺记录
|
||||
*/
|
||||
async saveLog(logData, startTime) {
|
||||
const {
|
||||
@ -73,38 +78,14 @@ class pdaService extends Service {
|
||||
} = this;
|
||||
|
||||
try {
|
||||
// 限制日志内容长度
|
||||
if (logData.body && logData.body.length > 65535) {
|
||||
logData.body = logData.body.substring(0, 65535);
|
||||
}
|
||||
|
||||
if (logData.result && logData.result.length > 65535) {
|
||||
logData.result = logData.result.substring(0, 65535);
|
||||
}
|
||||
|
||||
logData.use_time = Date.now() - startTime;
|
||||
|
||||
// 使用 SystemLog model 保存日志到数据库
|
||||
if (!ctx.model || !ctx.model.SystemLog) {
|
||||
throw new Error('SystemLog model 不存在,无法写入系统日志');
|
||||
}
|
||||
const result = await ctx.model.SystemLog.create({
|
||||
method: logData.method || '',
|
||||
v: logData.v || '',
|
||||
url: logData.url || '',
|
||||
headers: logData.headers || '',
|
||||
auth: logData.auth || '',
|
||||
created_at: new Date(),
|
||||
body: logData.body || '',
|
||||
result: logData.result || '',
|
||||
use_time: logData.use_time || 0,
|
||||
store_id: logData.store_id || null,
|
||||
return await apiLogSink.write(ctx.app, {
|
||||
logData,
|
||||
startTime,
|
||||
device: 'pda',
|
||||
});
|
||||
return result;
|
||||
} catch (error) {
|
||||
ctx.logger.error('保存日志失败: ' + error.message);
|
||||
// 可以选择记录到文件日志作为备用
|
||||
// 兜底:至少把原始数据落到 app 日志,避免整条丢失
|
||||
ctx.logger.info('日志数据: ', JSON.stringify(logData));
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,6 +2,8 @@
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
const apiLogSink = require('../lib/api_log_sink');
|
||||
|
||||
const ALLOWED_PLATFORMS = new Set([ 'web', 'pda', 'app', 'wx', 'miniprogram', 'other', 'workerstation', 'workstation' ]);
|
||||
// project: all=全部, warehouse=仓库, store=货主, tms=物流
|
||||
const ALLOWED_PROJECTS = new Set([ 'all', 'warehouse', 'store', 'tms', 'wms', 'scm', 'other' ]);
|
||||
@ -159,10 +161,13 @@ class systemService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存接口日志到系统日志模型
|
||||
* 保存接口日志。
|
||||
*
|
||||
* 经 Egg logger(apiLog)平铺写出到日志文件;wms_system_log 表已下线,不再有任何入库路径。
|
||||
*
|
||||
* @param {Object} logData 日志数据
|
||||
* @param {number} startTime 开始时间戳
|
||||
* @return {Promise<Object|undefined>} 写入结果
|
||||
* @return {Promise<Object|undefined>} 写出的平铺记录
|
||||
*/
|
||||
async saveLog(logData, startTime) {
|
||||
const {
|
||||
@ -170,38 +175,14 @@ class systemService extends Service {
|
||||
} = this;
|
||||
|
||||
try {
|
||||
// 限制日志内容长度
|
||||
if (logData.body && logData.body.length > 65535) {
|
||||
logData.body = logData.body.substring(0, 65535);
|
||||
}
|
||||
|
||||
if (logData.result && logData.result.length > 65535) {
|
||||
logData.result = logData.result.substring(0, 65535);
|
||||
}
|
||||
|
||||
logData.use_time = Date.now() - startTime;
|
||||
|
||||
// 使用 SystemLog model 保存日志到数据库
|
||||
if (!ctx.model || !ctx.model.SystemLog) {
|
||||
throw new Error('SystemLog model 不存在,无法写入系统日志');
|
||||
}
|
||||
const result = await ctx.model.SystemLog.create({
|
||||
method: logData.method || '',
|
||||
v: logData.v || '',
|
||||
url: logData.url || '',
|
||||
headers: logData.headers || '',
|
||||
auth: logData.auth || '',
|
||||
created_at: new Date(),
|
||||
body: logData.body || '',
|
||||
result: logData.result || '',
|
||||
use_time: logData.use_time || 0,
|
||||
store_id: logData.store_id || null,
|
||||
return await apiLogSink.write(ctx.app, {
|
||||
logData,
|
||||
startTime,
|
||||
device: ctx.header.platform,
|
||||
});
|
||||
return result;
|
||||
} catch (error) {
|
||||
ctx.logger.error('保存奇门接口日志失败: ' + error.message);
|
||||
// 可以选择记录到文件日志作为备用
|
||||
// 兜底:至少把原始数据落到 app 日志,避免整条丢失
|
||||
ctx.logger.info('奇门接口日志数据: ', JSON.stringify(logData));
|
||||
}
|
||||
}
|
||||
|
||||
@ -158,6 +158,9 @@ class FrontConfigMethodsService extends MainService {
|
||||
* 保存后清理该域名的公共拉取缓存并返回证书配置输出
|
||||
* (响应含证书/私钥原文回显,13 字段,口径与 frontConfig.getCert 一致)。
|
||||
*
|
||||
* 域名切换提示:待验证域名提升为生效域名时会清空证书 5 列并重置同步状态(域名已变,证书必须
|
||||
* 重新上传);前置闸门与 SAN/CN 覆盖校验始终以生效域名为准。
|
||||
*
|
||||
* @param {Object} data 请求参数。
|
||||
* @param {string} data.pem 证书 PEM 文本(必填)。
|
||||
* @param {string} data.key 私钥 PEM 文本(必填,与证书成对)。
|
||||
@ -189,13 +192,20 @@ class FrontConfigMethodsService extends MainService {
|
||||
/**
|
||||
* 设置当前仓库前端独立部署域名(需登录、仅仓库主体)。
|
||||
*
|
||||
* 设置成功会下发一次性 DNS TXT 校验记录(verify_host/verify_value)与 CNAME 目标(cname);
|
||||
* 域名发生变更时会同时清空既有证书并重置同步状态(旧证书不覆盖新域名)。
|
||||
* 设置成功只登记待验证域名并下发一次性 DNS TXT 校验记录(pending_verify_host / pending_verify_value)
|
||||
* 与 CNAME 目标(cname);生效域名、证书与同步状态不会因本接口改变。
|
||||
*
|
||||
* 两阶段切换(本次改造):本接口只登记待验证域名(pending_domain)并下发 TXT 校验码,不直接
|
||||
* 改动生效域名、证书与同步状态——切换期间旧域名全程可用,改错域名只要不配置 TXT 记录就不会生效;
|
||||
* TXT 校验通过后由提升逻辑切换生效域名,届时旧域名进入 retired_domain 下线队列、证书被清空并
|
||||
* 重置同步状态(需重新上传证书)。入参为当前生效域名时表示「取消待切换」。
|
||||
*
|
||||
* @param {Object} data 请求参数。
|
||||
* @param {string} data.domain 仓库自持域名(必填,非空,≤100 字符,全局唯一)。
|
||||
* @return {Promise<Object>} 统一响应结果(code=1);data 含
|
||||
* warehouse_id/domain/domain_status/verify_host/verify_value/cname/verified_at/attempts/last_error。
|
||||
* @return {Promise<Object>} 统一响应结果(code=1);data 含生效域名组 9 字段
|
||||
* (warehouse_id/domain/domain_status/verify_host/verify_value/cname/verified_at/attempts/last_error)
|
||||
* + 待验证域名组 7 字段(pending_domain/pending_verify_host/pending_verify_value/pending_attempts/
|
||||
* pending_last_error/pending_created_at/pending_active)。
|
||||
*/
|
||||
async setDomain(data = {}) {
|
||||
const targetService = this.getFrontConfigService();
|
||||
@ -219,8 +229,15 @@ class FrontConfigMethodsService extends MainService {
|
||||
* 返回待校验的 verify_host/verify_value 与 cname;domain_status=1(已验证)时
|
||||
* verify_host/verify_value 返回空串(校验令牌已无用途);无记录时返回空值默认。
|
||||
*
|
||||
* @return {Promise<Object>} 统一响应结果(code=1);data 含
|
||||
* warehouse_id/domain/domain_status/verify_host/verify_value/cname/verified_at/attempts/last_error。
|
||||
* 两阶段切换后响应在既有 9 个字段之后追加待验证域名组(pending_domain / pending_verify_host /
|
||||
* pending_verify_value / pending_attempts / pending_last_error / pending_created_at / pending_active;
|
||||
* 无待验证域名时依次为 ''/''/''/0/''/null/false)。待验证域名的校验码始终回显——该域名尚未生效,
|
||||
* 需据此配置 TXT 记录;生效域名已验证时既有 verify_host/verify_value 仍返回空串(口径不变)。
|
||||
*
|
||||
* @return {Promise<Object>} 统一响应结果(code=1);data 含生效域名组 9 字段
|
||||
* (warehouse_id/domain/domain_status/verify_host/verify_value/cname/verified_at/attempts/last_error)
|
||||
* + 待验证域名组 7 字段(pending_domain/pending_verify_host/pending_verify_value/pending_attempts/
|
||||
* pending_last_error/pending_created_at/pending_active)。
|
||||
*/
|
||||
async getDomain() {
|
||||
const targetService = this.getFrontConfigService();
|
||||
@ -242,6 +259,10 @@ class FrontConfigMethodsService extends MainService {
|
||||
* 主动校验当前仓库前端独立部署域名的 DNS TXT 记录(需登录、仅仓库主体)。
|
||||
*
|
||||
* 校验结果会回写 domain_status/domain_verified_at/attempts/last_error;
|
||||
* 两阶段切换后:存在待验证域名(pending_active=true)时校验的是待验证域名的 TXT 记录,通过即
|
||||
* 提升为生效域名(旧域名入 retired_domain 下线队列、证书清空并重置同步状态);不通过只累加
|
||||
* pending_attempts 并记 pending_last_error,生效域名与证书不受影响。无待验证域名时保持原口径
|
||||
* 回写 domain_status/domain_verified_at/attempts/last_error。
|
||||
* 响应额外含 verified(本次是否通过)与 resolved_values(本次解析到的 TXT 值,最多 5 条)。
|
||||
*
|
||||
* @return {Promise<Object>} 统一响应结果(code=1);未设置域名时 code=400。
|
||||
|
||||
@ -1044,6 +1044,16 @@ function formatTbWaybillSearchResponse(responseData, expressNameMap = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* index 模块免系统日志方法清单(显式登记)。
|
||||
*
|
||||
* 历史口径:index 模块全部方法免系统日志(_noNeedLog='*')。
|
||||
* uploadClientErrorLog 为公共上报接口,要求免登录但保留系统日志,
|
||||
* 因此将通配符改为显式清单:本清单之外的新方法默认记录系统日志,
|
||||
* 新增方法如需免日志须在此登记。
|
||||
*/
|
||||
const INDEX_NO_NEED_LOG_METHODS = 'fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getCOSUploadConfig,getImages,uploadSuccessNotify,recognizeLicensePlate,ReferenceFile,getMessageDetail,test,getI18nMessage,putI18nCollect,extractModule,tryAutoTranslateNewKeys,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,ensureShopPrintPlatformExists,buildShopPrintPlatformInclude,getShopList,requestPddWaybillSearch,requestPddStdTemplates,requestTbWaybillSearch,requestTbCainiaoStdTemplates,requestPolyStdTemplates,getShopExpressList,getCainiaoStfTemplates,normalizeTemplatePlatformCode,normalizeTemplateExpressCode,getExpressPlatformFieldName,getTemplateAllowedExpressCodeSet,filterPrintPlatformTemplateResponseData,getPrintPlatformTemplateCacheKey,requestPrintPlatformTemplateList,resolvePddTemplateWpCodeCandidates,requestPddTemplateSourceList,getPrintPlatformTemplateList,isPlatformOauthReservationDuplicateError,getPlatformOauthReservationCodePrefix,hasPlatformOauthReservationCodePrefix,normalizePlatformOauthReservationCode,generatePlatformOauthReservationCode,createPlatformOauthReservation,getPlatformOauthLink,listenPlatformOauthBind,loginToIm,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,parseWechatBadgeCode,queryUserByWechatBadge';
|
||||
|
||||
class indexService extends MainService {
|
||||
/**
|
||||
* 初始化基础方法的免登录、免权限、免鉴权和免日志配置。
|
||||
@ -1052,10 +1062,10 @@ class indexService extends MainService {
|
||||
*/
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,polyapiAuthorizeUrl,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken';
|
||||
const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken';
|
||||
const _noNeedLog = '*';
|
||||
const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken';
|
||||
const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,polyapiAuthorizeUrl,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,uploadClientErrorLog';
|
||||
const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,uploadClientErrorLog';
|
||||
const _noNeedLog = INDEX_NO_NEED_LOG_METHODS;
|
||||
const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,uploadClientErrorLog';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
async fastWhereTree(data) {
|
||||
@ -3537,5 +3547,41 @@ class indexService extends MainService {
|
||||
code: 200,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 上报客户端错误日志(免登录、免权限、免鉴权,保留系统日志)。
|
||||
*
|
||||
* 入参支持三种形态:
|
||||
* - 单条对象:{ client_type, app_version, device_id, ..., error_message/error_stack 至少一项 }
|
||||
* - 数组:[ item1, item2, ... ](单次最多 50 条)
|
||||
* - 包裹对象:{ logs: [ ... ] }
|
||||
* 字段命名兼容 snake_case 与 camelCase,report_uuid 重复上报静默成功。
|
||||
*
|
||||
* @param {Object|Array<Object>} data 上报数据。
|
||||
* @return {Promise<Object>} 统一响应结构;成功含 total/accepted/duplicated/rejected 统计,
|
||||
* 参数错误返回 code=400,写入失败返回 code=500。
|
||||
*/
|
||||
async uploadClientErrorLog(data) {
|
||||
const { service } = this;
|
||||
// 方法层只做入参形状解构,字段校验、截断与落库逻辑统一在 systems.clientErrorLog 处理
|
||||
const list = Array.isArray(data)
|
||||
? data
|
||||
: Array.isArray(data && data.logs)
|
||||
? data.logs
|
||||
: (data && typeof data === 'object' ? [ data ] : []);
|
||||
|
||||
try {
|
||||
const result = await service.systems.clientErrorLog.upload({ list });
|
||||
if (result && result.success) {
|
||||
return this.success(result.message || '上报成功', { ...result });
|
||||
}
|
||||
|
||||
return this.fail(result && result.message ? result.message : '上报失败', {
|
||||
code: (result && result.code) || 500,
|
||||
});
|
||||
} catch (error) {
|
||||
return this.fail(`客户端错误日志上报失败: ${error.message}`, { code: 500 });
|
||||
}
|
||||
}
|
||||
}
|
||||
module.exports = indexService;
|
||||
|
||||
@ -31,12 +31,15 @@ class OrderPackingMethodService extends MainService {
|
||||
* @param {Object} [data.pagination] 分页参数 { page, pageSize }
|
||||
* @param {Object} [data.where] 筛选条件。
|
||||
* 支持字段:status(任务状态)、pack_mode(打包模式)、waybill_code(运单号)、wave_no(波次号)、
|
||||
* order_id(订单ID)、workbench_id(工作台ID)、quickWhere(快捷搜索:波次号直接匹配 + 运单号通过express→order→wave链路解析)、
|
||||
* order_id(订单ID)、workbench_id(工作台ID)、operator_text(打包员/作业人员姓名)、
|
||||
* quickWhere(快捷搜索:波次号直接匹配 + 运单号通过express→order→wave链路解析)、
|
||||
* start_time(开始打包时间范围,{operator:'between', value:[start,end]})、end_time(结束打包时间范围)、create_time(创建时间范围);
|
||||
* start_time_start / start_time_end 为开始时间范围的兼容旧写法。
|
||||
* 运单号与波次号字段支持 {operator, value} 标准结构且 value 支持数组:
|
||||
* operator=contains/like 时按 LIKE '%值%' 模糊匹配(waybill_code 可命中 '主体-1-1-' 等分段单号),wave_no 另支持 eq/in 精确、ne 不等;
|
||||
* waybill_code 缺省/eq 时为「完整单号等值 + 剥离分段后缀主体等值 + 主体前缀」精确匹配。
|
||||
* operator_text(打包员/作业人员姓名)支持 {operator,value} 标准结构且 value 支持数组:
|
||||
* contains/like 与缺省为模糊 LIKE '%值%'(通配符已转义、多值取并集)、eq/in 精确、ne 不等于(取首值)、notlike 排除(多值逐个排除)。
|
||||
* @param {Object} [data.sort] 排序参数 { sortField, sortOrder }
|
||||
* @return {Promise<Object>} 统一成功包装响应
|
||||
*/
|
||||
|
||||
@ -2727,6 +2727,21 @@ class PendingOrderService extends OrderBaseService {
|
||||
// 拦截标记已写入,提交后抛出业务错误(调用方按"已转拦截"处理)
|
||||
await transaction.commit();
|
||||
|
||||
// 创建售后工单 + 通知快递群(失败不影响主流程,与 batchIntercept 口径一致)
|
||||
try {
|
||||
const op = this.getOrderLogOperator();
|
||||
await this.ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({
|
||||
orderIds: syncedOrderIds,
|
||||
warehouseId,
|
||||
creatorLabel: (op && op.name) || '系统',
|
||||
reason: '订单已同步,不可取消,转为拦截处理',
|
||||
});
|
||||
} catch (workOrderErr) {
|
||||
this.ctx.logger.warn(
|
||||
`[PendingOrderService.cancelOrder] 转拦截创建工单/通知失败, count=${syncedOrderIds.length}, error=${workOrderErr.message}`
|
||||
);
|
||||
}
|
||||
|
||||
// 写入拦截操作日志(不影响主流程)
|
||||
try {
|
||||
const operator = this.getOrderLogOperator() || {};
|
||||
|
||||
@ -1619,8 +1619,13 @@ class UserService extends Service {
|
||||
platform_code: platformCode,
|
||||
});
|
||||
|
||||
// 清理缓存
|
||||
await this.clearUserCache(user.id);
|
||||
// 清理缓存:必须带上 platformCode
|
||||
// clearUserCache(userId) 不带平台时只清 web/pda/mini/app/workerstation/workstation 这几个硬编码平台,
|
||||
// 小程序(miniProgram)、微信(wx)等取值不在清单内且 Redis key 大小写敏感,会残留旧身份,
|
||||
// 导致紧随其后的 findById 命中 5 分钟旧缓存,签发 token / 返回 user 时仍是切换前的角色。
|
||||
await this.clearUserCache(user.id, platformCode);
|
||||
// 同步清理平台激活上下文缓存(platform_active:{accountId}:{platformCode},30 分钟 TTL)
|
||||
await this.service.systems.accountPlatform.clearPlatformCache(user.id, platformCode);
|
||||
|
||||
// 获取更新后的用户信息
|
||||
const userInfo = await this.findById(user.id);
|
||||
|
||||
255
app/service/systems/client_error_log.js
Normal file
255
app/service/systems/client_error_log.js
Normal file
@ -0,0 +1,255 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
const crypto = require('crypto');
|
||||
|
||||
/** 单次批量上报最大条数 */
|
||||
const MAX_BATCH_SIZE = 50;
|
||||
|
||||
/** error_message 单条最大长度(超出截断) */
|
||||
const ERROR_MESSAGE_MAX_LENGTH = 5000;
|
||||
|
||||
/** error_stack 单条最大长度(超出截断) */
|
||||
const ERROR_STACK_MAX_LENGTH = 65535;
|
||||
|
||||
/** extra 单条最大长度(超出截断) */
|
||||
const EXTRA_MAX_LENGTH = 65535;
|
||||
|
||||
/** 字符串字段最大长度(与 wms_client_error_log 表结构列宽对齐) */
|
||||
const STRING_FIELD_LIMITS = Object.freeze({
|
||||
client_type: 32,
|
||||
app_version: 64,
|
||||
device_id: 128,
|
||||
os_version: 64,
|
||||
device_model: 128,
|
||||
error_type: 64,
|
||||
report_uuid: 64,
|
||||
});
|
||||
|
||||
/**
|
||||
* 客户端错误日志服务层。
|
||||
*
|
||||
* 职责:接收 index.uploadClientErrorLog 转交的原始上报数据(数组),
|
||||
* 完成字段归一化、必填校验、长度截断、report_uuid 幂等去重与批量落库;
|
||||
* 所有写入失败均返回友好结果对象,不向上抛出未捕获异常。
|
||||
*/
|
||||
class ClientErrorLogService extends Service {
|
||||
/**
|
||||
* 从上报项中按候选字段名提取首个非空值(兼容 snake_case 与 camelCase 两种入参命名)。
|
||||
*
|
||||
* @param {Object} item 上报项。
|
||||
* @param {Array<string>} keys 候选字段名(按优先级排序)。
|
||||
* @return {*} 命中的字段值;未命中返回 undefined。
|
||||
*/
|
||||
_pick(item, keys) {
|
||||
for (const key of keys) {
|
||||
if (Object.prototype.hasOwnProperty.call(item, key) && item[key] !== null && item[key] !== undefined) {
|
||||
return item[key];
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将任意值转换为去除首尾空白并截断到指定长度的字符串。
|
||||
*
|
||||
* @param {*} value 原始值。
|
||||
* @param {number} maxLength 最大长度。
|
||||
* @return {string} 转换后的字符串。
|
||||
*/
|
||||
_toText(value, maxLength) {
|
||||
if (value === null || value === undefined) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const text = String(value).trim();
|
||||
return text.length > maxLength ? text.slice(0, maxLength) : text;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析客户端时间:支持毫秒/秒时间戳与日期字符串,解析失败返回 null。
|
||||
*
|
||||
* @param {*} value 客户端时间原始值。
|
||||
* @return {Date|null} 解析出的日期;无法解析返回 null。
|
||||
*/
|
||||
_parseClientTime(value) {
|
||||
if (value === null || value === undefined || value === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
let parsed = null;
|
||||
|
||||
if (typeof value === 'number') {
|
||||
// 13 位以上视为毫秒,其余视为秒
|
||||
parsed = new Date(value >= 1e12 ? value : value * 1000);
|
||||
} else {
|
||||
const text = String(value).trim();
|
||||
if (/^\d{10,16}$/.test(text)) {
|
||||
const number = Number(text);
|
||||
parsed = new Date(number >= 1e12 ? number : number * 1000);
|
||||
} else {
|
||||
parsed = new Date(text);
|
||||
}
|
||||
}
|
||||
|
||||
if (Number.isNaN(parsed.getTime())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化单条上报项,输出可落库字段或拒绝原因。
|
||||
*
|
||||
* @param {*} raw 原始上报项。
|
||||
* @return {Object} { row } 归一化成功;{ error } 校验失败(附原因文案)。
|
||||
*/
|
||||
_normalizeItem(raw) {
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
||||
return { error: '日志项必须为对象' };
|
||||
}
|
||||
|
||||
const errorMessage = this._toText(
|
||||
this._pick(raw, [ 'error_message', 'errorMessage' ]),
|
||||
ERROR_MESSAGE_MAX_LENGTH
|
||||
);
|
||||
const errorStack = this._toText(
|
||||
this._pick(raw, [ 'error_stack', 'errorStack' ]),
|
||||
ERROR_STACK_MAX_LENGTH
|
||||
);
|
||||
|
||||
// 必填校验:error_message 与 error_stack 至少一项有值
|
||||
if (!errorMessage && !errorStack) {
|
||||
return { error: 'error_message 与 error_stack 至少填写一项' };
|
||||
}
|
||||
|
||||
const extraRaw = this._pick(raw, [ 'extra' ]);
|
||||
let extra = '';
|
||||
if (extraRaw !== null && extraRaw !== undefined) {
|
||||
if (typeof extraRaw === 'string') {
|
||||
extra = extraRaw.slice(0, EXTRA_MAX_LENGTH);
|
||||
} else {
|
||||
try {
|
||||
extra = JSON.stringify(extraRaw);
|
||||
} catch (error) {
|
||||
extra = '';
|
||||
}
|
||||
|
||||
if (extra.length > EXTRA_MAX_LENGTH) {
|
||||
extra = extra.slice(0, EXTRA_MAX_LENGTH);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let reportUuid = this._toText(
|
||||
this._pick(raw, [ 'report_uuid', 'reportUuid' ]),
|
||||
STRING_FIELD_LIMITS.report_uuid
|
||||
);
|
||||
// 客户端未生成 uuid 时由服务端补齐,保证唯一索引可用(此时不做幂等去重)
|
||||
if (!reportUuid) {
|
||||
reportUuid = `srv-${crypto.randomUUID()}`;
|
||||
}
|
||||
|
||||
return {
|
||||
row: {
|
||||
client_type: this._toText(this._pick(raw, [ 'client_type', 'clientType' ]), STRING_FIELD_LIMITS.client_type),
|
||||
app_version: this._toText(this._pick(raw, [ 'app_version', 'appVersion' ]), STRING_FIELD_LIMITS.app_version),
|
||||
device_id: this._toText(this._pick(raw, [ 'device_id', 'deviceId' ]), STRING_FIELD_LIMITS.device_id),
|
||||
os_version: this._toText(this._pick(raw, [ 'os_version', 'osVersion' ]), STRING_FIELD_LIMITS.os_version),
|
||||
device_model: this._toText(this._pick(raw, [ 'device_model', 'deviceModel' ]), STRING_FIELD_LIMITS.device_model),
|
||||
error_type: this._toText(this._pick(raw, [ 'error_type', 'errorType' ]), STRING_FIELD_LIMITS.error_type),
|
||||
error_message: errorMessage,
|
||||
error_stack: errorStack,
|
||||
extra,
|
||||
report_uuid: reportUuid,
|
||||
client_time: this._parseClientTime(this._pick(raw, [ 'client_time', 'clientTime' ])),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量上报客户端错误日志(幂等写入,report_uuid 重复时静默成功)。
|
||||
*
|
||||
* @param {Object} params 入参(由方法层解构传入)。
|
||||
* @param {Array<Object>} params.list 归一化后的上报项数组(单次最多 50 条)。
|
||||
* @return {Promise<Object>} 处理结果:
|
||||
* success=true 时含 total/accepted/duplicated/rejected/rejected_reasons 统计;
|
||||
* success=false 时含 message/code(校验失败或写入失败)。
|
||||
*/
|
||||
async upload({ list }) {
|
||||
const { ctx } = this;
|
||||
|
||||
if (!Array.isArray(list) || list.length === 0) {
|
||||
return { success: false, message: '缺少上报日志数据', code: 400 };
|
||||
}
|
||||
|
||||
if (list.length > MAX_BATCH_SIZE) {
|
||||
return { success: false, message: `单次最多上报 ${MAX_BATCH_SIZE} 条日志`, code: 400 };
|
||||
}
|
||||
|
||||
const rows = [];
|
||||
const rejectedReasons = [];
|
||||
list.forEach((item, index) => {
|
||||
const normalized = this._normalizeItem(item);
|
||||
if (normalized.error) {
|
||||
rejectedReasons.push({ index, reason: normalized.error });
|
||||
} else {
|
||||
rows.push(normalized.row);
|
||||
}
|
||||
});
|
||||
|
||||
if (rows.length === 0) {
|
||||
return { success: false, message: '没有可入库的有效日志', code: 400, rejected: rejectedReasons.length };
|
||||
}
|
||||
|
||||
// 幂等去重:查询已存在的 report_uuid,重复项静默成功、不产生重复行
|
||||
let existingUuids = [];
|
||||
try {
|
||||
const uuids = rows.map(row => row.report_uuid);
|
||||
const existingRows = await ctx.model.ClientErrorLog.findAll({
|
||||
where: { report_uuid: uuids },
|
||||
attributes: [ 'report_uuid' ],
|
||||
raw: true,
|
||||
});
|
||||
existingUuids = existingRows.map(item => item.report_uuid);
|
||||
} catch (error) {
|
||||
ctx.logger.error(`[clientErrorLog] 查询已有 report_uuid 失败: ${error.message}`);
|
||||
return { success: false, message: '日志上报失败,请稍后重试', code: 500 };
|
||||
}
|
||||
|
||||
const newRows = rows.filter(row => !existingUuids.includes(row.report_uuid));
|
||||
const duplicatedCount = rows.length - newRows.length;
|
||||
|
||||
let insertedCount = 0;
|
||||
if (newRows.length > 0) {
|
||||
try {
|
||||
// created_at/updated_at 由 Sequelize 时间戳统一取服务器当前时间,不采信客户端时间。
|
||||
// 注意:Sequelize v6 的 bulkCreate 在实例校验(validate)之后才注入时间戳,
|
||||
// 模型显式声明 created_at/updated_at 且 allowNull:false 时,validate:true 会触发
|
||||
// notNull Violation,导致所有有效上报写入失败;字段类型/必填/长度校验已由本服务层
|
||||
// _normalizeItem 完整保证(字符串归一化 + 长度截断 + client_time 解析),
|
||||
// 故此处关闭模型级校验,与项目中其他 bulkCreate 调用(默认 validate:false)保持一致。
|
||||
await ctx.model.ClientErrorLog.bulkCreate(newRows, { validate: false });
|
||||
insertedCount = newRows.length;
|
||||
} catch (error) {
|
||||
ctx.logger.error(`[clientErrorLog] 批量写入失败: ${error.message}`);
|
||||
return { success: false, message: '日志写入失败,请稍后重试', code: 500 };
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: '上报成功',
|
||||
code: 200,
|
||||
total: list.length,
|
||||
accepted: insertedCount,
|
||||
duplicated: duplicatedCount,
|
||||
rejected: rejectedReasons.length,
|
||||
rejected_reasons: rejectedReasons.slice(0, 10),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ClientErrorLogService;
|
||||
File diff suppressed because it is too large
Load Diff
@ -76,9 +76,12 @@ class OrderPackingService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建列表筛选条件(list 与 export 复用同一套语义)。
|
||||
* 构建列表筛选条件(list 与 exportPackTask 复用同一套语义,导出会自动获得同一筛选语义)。
|
||||
*
|
||||
* @param {Object} where 筛选条件对象(与 list 入参一致)
|
||||
* @param {Object} where 筛选条件对象(与 list 入参一致)。其中 operator_text(打包员/作业人员姓名,
|
||||
* 对应 wms_pack_task.operator_text 多人姓名逗号拼接快照列)支持 {operator,value} 标准结构,
|
||||
* value 支持字符串或字符串数组(多值取并集):contains/like 与缺省为模糊 LIKE '%值%'(通配符已转义)、
|
||||
* eq/in 精确(单值等值、多值 Op.in)、ne 不等于(取首值)、notlike 排除(多值逐个排除)。
|
||||
* @param {Object} Op Sequelize Op 对象
|
||||
* @param {number} warehouseId 仓库ID
|
||||
* @return {Promise<Object>} Sequelize where 条件对象
|
||||
@ -189,6 +192,57 @@ class OrderPackingService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 打包员(作业人员)筛选:wms_pack_task.operator_text 为多人姓名逗号拼接快照(如 '小吴哥,阿猫')。
|
||||
// 支持 {operator,value} 标准结构,value 支持字符串或字符串数组(多值取并集):
|
||||
// - operator=contains / like 与缺省:模糊匹配 LIKE '%值%'(通配符已转义);
|
||||
// - operator=eq / in:精确匹配(单值等值,多值 Op.in);
|
||||
// - operator=ne:不等于(取首值);
|
||||
// - operator=notlike:NOT LIKE '%值%'(多值时逐个排除)。
|
||||
// 本函数同时被 list 与 exportPackTask 复用,因此导出 Excel 会自动获得同一筛选语义。
|
||||
if (where.operator_text) {
|
||||
// 空值识别:仅当条件是对象且 value 为 null/undefined 时视为空(忽略该条件、不过滤),
|
||||
// 不得回退到条件对象本身,否则会被 String 化为 '[object Object]' 产生恒空过滤。
|
||||
const operatorTextCondition = where.operator_text;
|
||||
const isConditionObject = operatorTextCondition
|
||||
&& typeof operatorTextCondition === 'object'
|
||||
&& !Array.isArray(operatorTextCondition);
|
||||
const operatorTextRawValue = isConditionObject ? operatorTextCondition.value : operatorTextCondition;
|
||||
const operatorTextOperator = isConditionObject
|
||||
? String(operatorTextCondition.operator || '').trim().toLowerCase()
|
||||
: '';
|
||||
const operatorTextList = (Array.isArray(operatorTextRawValue) ? operatorTextRawValue : [ operatorTextRawValue ])
|
||||
.map(item => (item === undefined || item === null ? '' : String(item).trim()))
|
||||
.filter(Boolean);
|
||||
|
||||
if (operatorTextList.length > 0) {
|
||||
if (operatorTextOperator === 'eq' || operatorTextOperator === 'in') {
|
||||
queryWhere.operator_text = operatorTextList.length === 1
|
||||
? operatorTextList[0]
|
||||
: { [Op.in]: operatorTextList };
|
||||
} else if (operatorTextOperator === 'ne') {
|
||||
queryWhere.operator_text = { [Op.ne]: operatorTextList[0] };
|
||||
} else if (operatorTextOperator === 'notlike') {
|
||||
if (operatorTextList.length === 1) {
|
||||
queryWhere.operator_text = { [Op.notLike]: `%${escapeLikeWildcards(operatorTextList[0])}%` };
|
||||
} else {
|
||||
const notLikeConditions = operatorTextList.map(
|
||||
item => ({ operator_text: { [Op.notLike]: `%${escapeLikeWildcards(item)}%` } })
|
||||
);
|
||||
queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), ...notLikeConditions ];
|
||||
}
|
||||
} else if (operatorTextList.length === 1) {
|
||||
queryWhere.operator_text = { [Op.like]: `%${escapeLikeWildcards(operatorTextList[0])}%` };
|
||||
} else {
|
||||
const likeConditions = operatorTextList.map(
|
||||
item => ({ operator_text: { [Op.like]: `%${escapeLikeWildcards(item)}%` } })
|
||||
);
|
||||
queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []),
|
||||
{ [Op.or]: likeConditions },
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 订单ID精确匹配
|
||||
if (where.order_id !== undefined && where.order_id !== null) {
|
||||
const orderIdValue = where.order_id?.value ?? where.order_id;
|
||||
@ -442,6 +496,7 @@ class OrderPackingService extends Service {
|
||||
* @param {Object} [where.waybill_code] 运单号(通过 wms_order_express 解析 order_id 后过滤)。支持 {operator,value} 标准结构,value 支持字符串或数组:
|
||||
* operator=contains/like 时按 LIKE '%单号%' 模糊匹配(可命中分段单号);缺省/eq 时先剥离一单多件分段后缀、主体单号等值匹配 + 主体前缀匹配
|
||||
* @param {Object} [where.wave_no] 波次号。支持 {operator,value} 标准结构,value 支持字符串或数组:eq/in 精确、ne 不等、contains/like 与缺省为模糊匹配
|
||||
* @param {Object} [where.operator_text] 打包员/作业人员姓名(wms_pack_task.operator_text 快照列,多人姓名逗号拼接)。支持 {operator,value} 标准结构,value 支持字符串或数组:contains/like 与缺省为模糊 LIKE '%值%'(通配符已转义、多值取并集)、eq/in 精确、ne 不等于(取首值)、notlike 排除(多值逐个排除)
|
||||
* @param {Object} [where.order_id] 订单ID(精确匹配)
|
||||
* @param {Object} [where.workbench_id] 工作台ID(精确匹配)
|
||||
* @param {Object} [where.quickWhere] 快捷搜索:支持波次号模糊匹配;运单号通过 express→order→wave 链路解析(团购按波次号查、散单按订单ID查;运单号先剥离分段后缀等值匹配,精确未命中且关键词长度≥4 时才降级模糊,短词禁止降级避免误命中)
|
||||
|
||||
@ -674,7 +674,7 @@ class ReturnUnpackService extends Service {
|
||||
ctx.logger.warn(`[returnUnpack.submit] 更新退回查询记录 is_back 失败: ${err.message}`);
|
||||
}
|
||||
|
||||
// 拆包完成后通知货主群:登记表/拆包单有货主归属且未通知的,推送到货主售后群并标记 is_notified=1
|
||||
// 拆包完成后按原查询登记来源通知(登记时记录的来源群/用户):推送成功后标记 is_notified=1
|
||||
await this._notifyUnpacked(unpack);
|
||||
|
||||
const updated = await ctx.model.ReturnUnpack.findOne({
|
||||
@ -688,9 +688,11 @@ class ReturnUnpackService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 拆包完成后通知货主群。
|
||||
* 通知集合:仅退回查询登记表中该运单已退回(is_back=1)且未通知(is_notified=0)、有货主归属的记录;
|
||||
* 货主从未查询过退回(登记表无匹配)的不通知。推送成功后标记 is_notified=1。
|
||||
* 拆包完成后按原查询登记来源通知(不再泛推货主售后群)。
|
||||
* 通知集合:仅退回查询登记表中该运单已退回(is_back=1)且未通知(is_notified=0)的记录;
|
||||
* 按登记来源(group_id + user_id)聚合后逐来源回信:有用户信息时走 writeOutboundReply
|
||||
* 定向回原查询用户,无用户信息时退化为该群的系统通知;登记时无来源群的记录(如后台 API 登记)不通知。
|
||||
* 仅推送成功的登记标记 is_notified=1。
|
||||
*
|
||||
* @param {Object} unpack 拆包单主表记录
|
||||
* @return {Promise<void>} 异常仅记日志不阻塞主流程
|
||||
@ -700,8 +702,16 @@ class ReturnUnpackService extends Service {
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
const warehouseId = Number(unpack.warehouse_id || 0);
|
||||
try {
|
||||
const processor = ctx.service.inbox && ctx.service.inbox.processor;
|
||||
if (!processor || typeof processor.pushSystemNotification !== 'function') {
|
||||
ctx.logger.warn(
|
||||
`[returnUnpack._notifyUnpacked] inbox processor 不可用,跳过通知 waybill=${unpack.waybill_code}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const logs = await ctx.model.ReturnQueryLog.findAll({
|
||||
attributes: [ 'id', 'store_id', 'waybill_code' ],
|
||||
attributes: [ 'id', 'store_id', 'waybill_code', 'group_id', 'group_name', 'user_id', 'user_name' ],
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
[Op.or]: this._buildWaybillMatch(unpack.waybill_code),
|
||||
@ -711,52 +721,118 @@ class ReturnUnpackService extends Service {
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// 通知对象:store_id → 运单号集合(仅货主查询过退回的登记,store_id 必须有归属)
|
||||
const notifyMap = new Map();
|
||||
if (logs.length === 0) {
|
||||
ctx.logger.info(
|
||||
`[returnUnpack._notifyUnpacked] 无待通知的退回查询登记,跳过通知 waybill=${unpack.waybill_code}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// 按登记来源聚合:key=group_id|user_id → 运单号集合(同一来源的多条登记合并为一条消息)
|
||||
const buckets = new Map();
|
||||
const bucketIds = new Map();
|
||||
const skippedIds = [];
|
||||
for (const log of logs) {
|
||||
const sid = Number(log.store_id || 0);
|
||||
if (sid <= 0) continue;
|
||||
if (!notifyMap.has(sid)) notifyMap.set(sid, new Set());
|
||||
notifyMap.get(sid).add(log.waybill_code || unpack.waybill_code);
|
||||
const groupId = String(log.group_id || '').trim();
|
||||
if (!groupId) {
|
||||
// 登记时无来源群(如后台 API 登记):不通知,保留 is_notified=0
|
||||
skippedIds.push(log.id);
|
||||
continue;
|
||||
}
|
||||
const userId = String(log.user_id || '').trim();
|
||||
const key = `${groupId}\u0000${userId}`;
|
||||
if (!buckets.has(key)) {
|
||||
buckets.set(key, {
|
||||
groupId,
|
||||
groupName: String(log.group_name || '').trim(),
|
||||
userId,
|
||||
userName: String(log.user_name || '').trim(),
|
||||
waybills: new Set(),
|
||||
storeId: 0,
|
||||
});
|
||||
bucketIds.set(key, []);
|
||||
}
|
||||
const bucket = buckets.get(key);
|
||||
bucket.waybills.add(log.waybill_code || unpack.waybill_code);
|
||||
if (!bucket.storeId) bucket.storeId = Number(log.store_id || 0);
|
||||
bucketIds.get(key).push(log.id);
|
||||
}
|
||||
|
||||
if (notifyMap.size === 0) {
|
||||
if (buckets.size === 0) {
|
||||
ctx.logger.info(
|
||||
`[returnUnpack._notifyUnpacked] 无货主查询过退回的登记,跳过通知 waybill=${unpack.waybill_code}`
|
||||
`[returnUnpack._notifyUnpacked] 登记均无来源群信息,跳过通知 waybill=${unpack.waybill_code} skipped=${skippedIds.length}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// 查货主售后群
|
||||
const storeIds = [ ...notifyMap.keys() ];
|
||||
const groups = await ctx.service.systems.inbox.group.findStoreAfterSalesGroups({
|
||||
storeIds,
|
||||
warehouseId,
|
||||
});
|
||||
if (groups.length === 0) {
|
||||
ctx.logger.info(
|
||||
`[returnUnpack._notifyUnpacked] 未找到货主售后群,跳过通知 storeIds=${storeIds.join(',')}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// 按群推送(一条消息含该货主的全部运单)
|
||||
for (const g of groups) {
|
||||
const waybills = [ ...(notifyMap.get(Number(g.store_id)) || new Set()) ];
|
||||
if (waybills.length === 0) continue;
|
||||
const content = `退回包裹已拆包完成:\n${waybills.join('\n')}\n发送:查退回+运单号,可查看拆包明细`;
|
||||
ctx.service.inbox.processor.pushSystemNotification({
|
||||
warehouse_id: warehouseId,
|
||||
group_id: g.group_id,
|
||||
group_name: g.group_name,
|
||||
content,
|
||||
ext_data: g.ext_data || null,
|
||||
store_id: g.store_id || null,
|
||||
// 批量反查群信息(补全 group_name/ext_data/store_id;群已解绑时用登记快照兑底)
|
||||
const groupMap = new Map();
|
||||
const groupIds = [ ...buckets.values() ].map(bucket => bucket.groupId);
|
||||
try {
|
||||
const groupRows = await ctx.model.InboxGroup.findAll({
|
||||
attributes: [ 'group_id', 'group_name', 'store_id', 'ext_data' ],
|
||||
where: { group_id: { [Op.in]: groupIds }, warehouse_id: warehouseId },
|
||||
raw: true,
|
||||
});
|
||||
for (const g of groupRows) {
|
||||
groupMap.set(String(g.group_id), g);
|
||||
}
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[returnUnpack._notifyUnpacked] 批量查询群信息失败: ${err.message}`);
|
||||
}
|
||||
|
||||
// 标记已通知
|
||||
const notifiedIds = logs.map(l => l.id);
|
||||
// 逐来源回信(一条消息含该来源登记的全部运单)
|
||||
const notifiedIds = [];
|
||||
let bucketIdx = 0;
|
||||
for (const [ key, bucket ] of buckets) {
|
||||
bucketIdx += 1;
|
||||
const groupRow = groupMap.get(bucket.groupId) || null;
|
||||
const groupName = String(bucket.groupName || (groupRow && groupRow.group_name) || '').trim();
|
||||
if (!groupName) {
|
||||
skippedIds.push(...bucketIds.get(key));
|
||||
ctx.logger.warn(
|
||||
`[returnUnpack._notifyUnpacked] 来源群名缺失,跳过通知 group=${bucket.groupId}`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const storeId = bucket.storeId || Number(groupRow && groupRow.store_id) || null;
|
||||
const extData = (groupRow && groupRow.ext_data) || null;
|
||||
const waybills = [ ...bucket.waybills ];
|
||||
const content = `退回包裹已拆包完成:\n${waybills.join('\n')}\n发送:查退回+运单号,可查看拆包明细`;
|
||||
try {
|
||||
if (bucket.userId && bucket.userName && typeof processor.writeOutboundReply === 'function') {
|
||||
// 定向回原查询用户(登记来源用户信息完整时)
|
||||
await processor.writeOutboundReply({
|
||||
warehouse_id: warehouseId,
|
||||
group_id: bucket.groupId,
|
||||
group_name: groupName,
|
||||
user_id: bucket.userId,
|
||||
user_name: bucket.userName,
|
||||
store_id: storeId,
|
||||
ext_data: extData,
|
||||
ext_id: `unpack:notify:${unpack.id}:${bucketIdx}`,
|
||||
}, content, 'ai_reply');
|
||||
} else {
|
||||
// 无用户信息:退化为来源群系统通知
|
||||
processor.pushSystemNotification({
|
||||
warehouse_id: warehouseId,
|
||||
group_id: bucket.groupId,
|
||||
group_name: groupName,
|
||||
content,
|
||||
ext_data: extData,
|
||||
store_id: storeId,
|
||||
});
|
||||
}
|
||||
notifiedIds.push(...bucketIds.get(key));
|
||||
} catch (err) {
|
||||
skippedIds.push(...bucketIds.get(key));
|
||||
ctx.logger.warn(
|
||||
`[returnUnpack._notifyUnpacked] 通知失败 group=${bucket.groupId}: ${err.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 仅标记推送成功的登记(失败/无来源的保留 is_notified=0)
|
||||
if (notifiedIds.length > 0) {
|
||||
await ctx.model.ReturnQueryLog.update(
|
||||
{ is_notified: 1 },
|
||||
@ -765,7 +841,7 @@ class ReturnUnpackService extends Service {
|
||||
}
|
||||
ctx.logger.info(
|
||||
`[returnUnpack._notifyUnpacked] 拆包通知完成 waybill=${unpack.waybill_code} ` +
|
||||
`groups=${groups.length} logs=${notifiedIds.length}`
|
||||
`notified=${notifiedIds.length} skipped=${skippedIds.length} buckets=${buckets.size}`
|
||||
);
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[returnUnpack._notifyUnpacked] 拆包通知失败: ${err.message}`);
|
||||
@ -1599,10 +1675,14 @@ class ReturnUnpackService extends Service {
|
||||
* @param {string} params.waybill_code 退回包裹运单号(必填)。
|
||||
* @param {number} params.warehouse_id 仓库ID(必填)。
|
||||
* @param {number} [params.store_id] 货主ID(可选,用于货主隔离与未退回登记)。
|
||||
* @param {string} [params.group_id] 触发查询的群ID(站内信外部群ID,登记来源)。
|
||||
* @param {string} [params.group_name] 触发查询的群名称(登记来源)。
|
||||
* @param {string} [params.user_id] 触发查询的用户ID(站内信外部用户ID,登记来源)。
|
||||
* @param {string} [params.user_name] 触发查询的用户名称(登记来源)。
|
||||
* @return {Promise<Object>} { status, waybill_code, warehouse_name, ... }。
|
||||
* status:unpacked(已拆包)/ received(已收到未拆包)/ not_returned(未退回)/ hidden(跨货主不可见)。
|
||||
*/
|
||||
async queryByWaybill({ waybill_code, warehouse_id, store_id } = {}) {
|
||||
async queryByWaybill({ waybill_code, warehouse_id, store_id, group_id, group_name, user_id, user_name } = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
@ -1617,6 +1697,12 @@ class ReturnUnpackService extends Service {
|
||||
}
|
||||
const storeId = Number(store_id || 0);
|
||||
|
||||
// 登记来源(站内信「查退回」触发):群/用户信息写入退回查询登记表,用于追溯与定向通知
|
||||
const sourceGroupId = String(group_id || '').trim() || null;
|
||||
const sourceGroupName = String(group_name || '').trim() || null;
|
||||
const sourceUserId = String(user_id || '').trim() || null;
|
||||
const sourceUserName = String(user_name || '').trim() || null;
|
||||
|
||||
const warehouseName = await this._resolveWarehouseName(warehouseId);
|
||||
|
||||
// 1. 已拆包:同一运单号取最新一条有效拆包单(跳过已作废)
|
||||
@ -1746,6 +1832,10 @@ class ReturnUnpackService extends Service {
|
||||
remark: '站内信查询退回自动登记(已收到未拆包)',
|
||||
is_notified: 0,
|
||||
is_back: 0,
|
||||
group_id: sourceGroupId,
|
||||
group_name: sourceGroupName,
|
||||
user_id: sourceUserId,
|
||||
user_name: sourceUserName,
|
||||
});
|
||||
queryLog = created && typeof created.toJSON === 'function' ? created.toJSON() : created;
|
||||
} catch (err) {
|
||||
@ -1802,6 +1892,10 @@ class ReturnUnpackService extends Service {
|
||||
remark: '站内信查询退回自动登记',
|
||||
is_notified: 0,
|
||||
is_back: 0,
|
||||
group_id: sourceGroupId,
|
||||
group_name: sourceGroupName,
|
||||
user_id: sourceUserId,
|
||||
user_name: sourceUserName,
|
||||
});
|
||||
createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created;
|
||||
} catch (err) {
|
||||
@ -2710,6 +2804,9 @@ class ReturnUnpackService extends Service {
|
||||
* 根据标准化 where 条件构建主表 Sequelize 查询条件。
|
||||
*
|
||||
* @param {Object} where 标准化 where 条件对象。
|
||||
* 文本字段(unpack_no / waybill_code / unpacker_name)支持 {operator,value} 标准结构:
|
||||
* operator=like 时按 LIKE '%值%' 模糊匹配(value 为数组时多值取并集)、eq/in 精确、ne/notin 取反、between 范围等;
|
||||
* 其中 unpacker_name 为拆包人员工号名称快照列(wms_return_unpack.unpacker_name)。
|
||||
* @param {Object} Op Sequelize Op 对象。
|
||||
* @return {Object} Sequelize where 条件。
|
||||
*/
|
||||
@ -2759,12 +2856,28 @@ class ReturnUnpackService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 文本字段(支持模糊)
|
||||
const textFields = [ 'unpack_no', 'waybill_code' ];
|
||||
// 文本字段(支持模糊;unpacker_name 为拆包人员工号名称快照列)
|
||||
const textFields = [ 'unpack_no', 'waybill_code', 'unpacker_name' ];
|
||||
for (const field of textFields) {
|
||||
if (where[field] !== undefined && where[field] !== null) {
|
||||
queryWhere[field] = this._resolveConditionValue(where[field], Op);
|
||||
const condition = where[field];
|
||||
if (condition === undefined || condition === null) {
|
||||
continue;
|
||||
}
|
||||
// 空值条件跳过:条件对象取 condition.value,为 null/undefined/纯空白字符串/空数组时不生成该字段条件,
|
||||
// 避免生成 IS NULL / IN () 等恒空条件(如 unpacker_name 列 NOT NULL,IS NULL 会清空整个列表)。
|
||||
// 例外:operator=like 的空数组由 _resolveConditionValue 退化为 '%%'(全匹配、不过滤,既有测试锁定该口径)。
|
||||
if (condition && typeof condition === 'object' && !Array.isArray(condition)) {
|
||||
const conditionValue = condition.value;
|
||||
const conditionOperator = String(condition.operator || '').trim().toLowerCase();
|
||||
const isEmptyValue = conditionValue === null
|
||||
|| conditionValue === undefined
|
||||
|| (typeof conditionValue === 'string' && conditionValue.trim() === '')
|
||||
|| (Array.isArray(conditionValue) && conditionValue.length === 0 && conditionOperator !== 'like');
|
||||
if (isEmptyValue) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
queryWhere[field] = this._resolveConditionValue(condition, Op);
|
||||
}
|
||||
|
||||
return queryWhere;
|
||||
@ -2836,6 +2949,8 @@ class ReturnUnpackService extends Service {
|
||||
|
||||
/**
|
||||
* 解析标准化条件值为 Sequelize 可用的条件对象。
|
||||
* like 分支:value 为标量时保持 LIKE '%值%' 行为不变;value 为数组时按元素做并集模糊
|
||||
* (多值 → { [Op.or]: [{ [Op.like]: '%值1%' }, ...] }),数组经 trim/去空归一后为空则退化为 '%%'(全匹配、不过滤)。
|
||||
*
|
||||
* @param {*} condition 标准化条件(可能是 {operator, value} 或直接值)。
|
||||
* @param {Object} Op Sequelize Op 对象。
|
||||
@ -2859,8 +2974,21 @@ class ReturnUnpackService extends Service {
|
||||
return { [Op.in]: Array.isArray(value) ? value : [ value ] };
|
||||
case 'notin':
|
||||
return { [Op.notIn]: Array.isArray(value) ? value : [ value ] };
|
||||
case 'like':
|
||||
case 'like': {
|
||||
if (Array.isArray(value)) {
|
||||
const likeList = value
|
||||
.map(item => (item === undefined || item === null ? '' : String(item).trim()))
|
||||
.filter(Boolean);
|
||||
if (likeList.length === 0) {
|
||||
return { [Op.like]: '%%' };
|
||||
}
|
||||
if (likeList.length === 1) {
|
||||
return { [Op.like]: `%${likeList[0]}%` };
|
||||
}
|
||||
return { [Op.or]: likeList.map(item => ({ [Op.like]: `%${item}%` })) };
|
||||
}
|
||||
return { [Op.like]: `%${value}%` };
|
||||
}
|
||||
case 'gt':
|
||||
return { [Op.gt]: value };
|
||||
case 'gte':
|
||||
|
||||
@ -1,180 +0,0 @@
|
||||
// app/service/systems/system_log.js
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
/** @type {string} 系统日志表名 */
|
||||
const SYSTEM_LOG_TABLE = 'wms_system_log';
|
||||
/** @type {number} 默认日志保留天数:删除创建时间早于该天数的日志 */
|
||||
const DEFAULT_RETAIN_DAYS = 60;
|
||||
/** @type {number} 默认单批硬删除行数 */
|
||||
const DEFAULT_BATCH_SIZE = 2000;
|
||||
/** @type {number} 默认批间休眠最小毫秒数 */
|
||||
const DEFAULT_SLEEP_MIN_MS = 100;
|
||||
/** @type {number} 默认批间休眠最大毫秒数 */
|
||||
const DEFAULT_SLEEP_MAX_MS = 500;
|
||||
|
||||
/**
|
||||
* 休眠指定毫秒数。
|
||||
*
|
||||
* @param {number} ms 休眠毫秒数。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将保留天数归一化为正整数。
|
||||
*
|
||||
* 仅接受正整数(含数字字符串),其余非法值(负数、0、小数、非数字)一律回退默认保留天数;
|
||||
* 归一化后的值直接拼入 SQL 模板的 INTERVAL 表达式,保证无 SQL 注入风险。
|
||||
*
|
||||
* @param {*} value 待归一化的保留天数。
|
||||
* @return {number} 归一化后的正整数保留天数。
|
||||
*/
|
||||
function normalizeRetainDays(value) {
|
||||
const normalized = Number(value);
|
||||
return Number.isInteger(normalized) && normalized > 0 ? normalized : DEFAULT_RETAIN_DAYS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 系统日志清理服务。
|
||||
*
|
||||
* 背景:wms_system_log 单表无分表无分区,日志长期增长会占用大量磁盘空间。
|
||||
* created_at 由应用写入 new Date(),与自增主键 id 严格单调递增,且 created_at 无索引,
|
||||
* 因此按时间条件过滤会全表扫描,必须按 id 边界走主键索引删除;
|
||||
* 同时必须使用原生 SQL 硬删除,禁止 SystemLog.destroy(全局 paranoid 软删除会增大行体积且语义不符)。
|
||||
*/
|
||||
class SystemLogService extends MainService {
|
||||
/**
|
||||
* 定位删除边界 id:创建时间早于保留天数截止时间的最大 id。
|
||||
*
|
||||
* 由于 created_at 与 id 严格单调递增,id 不大于该边界的行即全部过期行,
|
||||
* 等价于按 created_at 时间边界删除且走主键索引;查不到时返回 null 表示无过期日志。
|
||||
*
|
||||
* @param {number} retainDays 日志保留天数(正整数;非法值回退默认 60)。
|
||||
* @return {Promise<number|null>} 边界 id;无过期日志时返回 null。
|
||||
*/
|
||||
async findCleanupBoundaryId(retainDays) {
|
||||
const { ctx } = this;
|
||||
const safeRetainDays = normalizeRetainDays(retainDays);
|
||||
|
||||
const rows = await ctx.model.query(
|
||||
`SELECT id FROM ${SYSTEM_LOG_TABLE}`
|
||||
+ ` WHERE created_at < DATE_SUB(NOW(), INTERVAL ${safeRetainDays} DAY)`
|
||||
+ ' ORDER BY id DESC LIMIT 1',
|
||||
{ type: ctx.model.QueryTypes.SELECT }
|
||||
);
|
||||
|
||||
const firstRow = Array.isArray(rows) ? rows[0] : null;
|
||||
const boundaryId = firstRow ? Number(firstRow.id) : null;
|
||||
return Number.isInteger(boundaryId) && boundaryId > 0 ? boundaryId : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 单批硬删除 id 不大于边界值的系统日志(每批最多 batchSize 行)。
|
||||
*
|
||||
* @param {number} boundaryId 删除边界 id(含边界行本身)。
|
||||
* @param {number} batchSize 单批最大删除行数。
|
||||
* @return {Promise<number>} 本批实际删除行数。
|
||||
*/
|
||||
async deleteSystemLogsBatch(boundaryId, batchSize) {
|
||||
const { ctx } = this;
|
||||
const safeBoundaryId = Number(boundaryId) > 0 ? Math.floor(Number(boundaryId)) : 0;
|
||||
const safeBatchSize = Number(batchSize) > 0 ? Math.floor(Number(batchSize)) : DEFAULT_BATCH_SIZE;
|
||||
if (safeBoundaryId <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 不传 type:默认走 RAW 查询,mysql2 对 DELETE 返回 ResultSetHeader,
|
||||
// 取 [result, data] 结构中第一项的 affectedRows 作为本批删除行数
|
||||
const rawResult = await ctx.model.query(
|
||||
`DELETE FROM ${SYSTEM_LOG_TABLE}`
|
||||
+ ` WHERE id <= ${safeBoundaryId}`
|
||||
+ ' ORDER BY id'
|
||||
+ ` LIMIT ${safeBatchSize}`
|
||||
);
|
||||
const header = Array.isArray(rawResult) ? rawResult[0] : rawResult;
|
||||
const affectedRows = Number(header && header.affectedRows);
|
||||
return Number.isFinite(affectedRows) && affectedRows > 0 ? affectedRows : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理超过保留天数的系统日志(定时任务入口)。
|
||||
*
|
||||
* 流程:先定位边界 id,再按 id 升序分批硬删除,循环到单批受影响行数为 0 为止,
|
||||
* 批间随机休眠 100~500ms 降低数据库压力;不执行 OPTIMIZE TABLE,
|
||||
* 由 InnoDB 自行复用已删除数据页,避免重建大表占满磁盘。
|
||||
*
|
||||
* @param {Object} [options={}] 清理参数。
|
||||
* @param {number} [options.retainDays] 日志保留天数(正整数);缺省时读取
|
||||
* config.systemLogCleanup.retainDays,仍非法或未配置时回退 60。
|
||||
* @param {number} [options.batchSize=2000] 单批硬删除行数。
|
||||
* @param {number} [options.sleepMinMs=100] 批间休眠最小毫秒数。
|
||||
* @param {number} [options.sleepMaxMs=500] 批间休眠最大毫秒数。
|
||||
* @return {Promise<Object>} 清理结果摘要。
|
||||
*/
|
||||
async cleanupExpiredSystemLogs(options = {}) {
|
||||
const { ctx } = this;
|
||||
const startedAt = Date.now();
|
||||
const safeOptions = options && typeof options === 'object' ? options : {};
|
||||
|
||||
const cleanupConfig = (ctx.app.config && ctx.app.config.systemLogCleanup) || {};
|
||||
const rawRetainDays = safeOptions.retainDays !== undefined && safeOptions.retainDays !== null
|
||||
? safeOptions.retainDays
|
||||
: cleanupConfig.retainDays;
|
||||
const retainDays = normalizeRetainDays(rawRetainDays);
|
||||
const batchSize = Number(safeOptions.batchSize) > 0
|
||||
? Math.floor(Number(safeOptions.batchSize))
|
||||
: DEFAULT_BATCH_SIZE;
|
||||
const sleepMinMs = Number(safeOptions.sleepMinMs) >= 0
|
||||
? Math.floor(Number(safeOptions.sleepMinMs))
|
||||
: DEFAULT_SLEEP_MIN_MS;
|
||||
let sleepMaxMs = Number(safeOptions.sleepMaxMs) >= 0
|
||||
? Math.floor(Number(safeOptions.sleepMaxMs))
|
||||
: DEFAULT_SLEEP_MAX_MS;
|
||||
if (sleepMaxMs < sleepMinMs) {
|
||||
sleepMaxMs = sleepMinMs;
|
||||
}
|
||||
|
||||
const boundaryId = await this.findCleanupBoundaryId(retainDays);
|
||||
if (boundaryId === null) {
|
||||
ctx.logger.info(`[system-log-cleanup] 无超过 ${retainDays} 天的系统日志,跳过本次清理`);
|
||||
return {
|
||||
skipped: true,
|
||||
boundary_id: null,
|
||||
batch_count: 0,
|
||||
deleted_rows: 0,
|
||||
duration_ms: Date.now() - startedAt,
|
||||
};
|
||||
}
|
||||
|
||||
let batchCount = 0;
|
||||
let totalDeleted = 0;
|
||||
let affectedRows = 1;
|
||||
|
||||
while (affectedRows > 0) {
|
||||
if (batchCount > 0) {
|
||||
const sleepMs = Math.floor(sleepMinMs + Math.random() * (sleepMaxMs - sleepMinMs + 1));
|
||||
await sleep(sleepMs);
|
||||
}
|
||||
|
||||
affectedRows = await this.deleteSystemLogsBatch(boundaryId, batchSize);
|
||||
if (affectedRows > 0) {
|
||||
batchCount += 1;
|
||||
totalDeleted += affectedRows;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
skipped: false,
|
||||
boundary_id: boundaryId,
|
||||
batch_count: batchCount,
|
||||
deleted_rows: totalDeleted,
|
||||
duration_ms: Date.now() - startedAt,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SystemLogService;
|
||||
@ -782,7 +782,7 @@ class WorkbenchService extends Service {
|
||||
* 打包人:上报了 users(business 旧链路)以上报为准,未上报(token+key 新链路)自动回填工作台绑定成员。
|
||||
* 波次范围(wave_scope):优先取上报值(0-4 整数),非法/缺省时兜底取订单行 wave_scope,
|
||||
* 服务端复查落库,防止前端失真;写入 wms_pack_task.wave_scope。
|
||||
* 响应附大团购倒计时字段:wave_scope=1 时下发 pack_wait_seconds(当前波次打包数 × 大团购打包系数,秒)
|
||||
* 响应附大团购倒计时字段: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] 扫描打包的运单号(可选,用于运单维度记录流水)
|
||||
@ -1269,13 +1269,16 @@ class WorkbenchService extends Service {
|
||||
};
|
||||
|
||||
// 大团购波次(wave_scope=1)下发倒计时字段供前端展示:
|
||||
// pack_wait_seconds = 当前波次打包数 × 大团购打包系数(秒),pack_start_time = 开始打包时间(毫秒时间戳);
|
||||
// 其他波次一律下发 0(不参与倒计时)。
|
||||
// pack_wait_seconds = 大团购打包系数 × 当前波次打包数 ÷ 当前工作台打包人数(秒),
|
||||
// pack_start_time = 开始打包时间(毫秒时间戳);其他波次一律下发 0(不参与倒计时)。
|
||||
// 打包人数取该工作台当前打包成员数;人数为 0 时任务已被成员全部登出流程自动结束,
|
||||
// 不会出现 0 人任务,仍按 1 兜底防除零。
|
||||
let packWaitSeconds = 0;
|
||||
let packStartTime = 0;
|
||||
if (normalizedWaveScope === 1) {
|
||||
const coefficient = await this._getBigGroupPackCoefficient(warehouseId);
|
||||
packWaitSeconds = packQuantity * coefficient;
|
||||
const packMemberCount = Array.isArray(users) && users.length > 0 ? users.length : 1;
|
||||
packWaitSeconds = packQuantity * coefficient / packMemberCount;
|
||||
packStartTime = packTimeMs;
|
||||
}
|
||||
result.pack_wait_seconds = packWaitSeconds;
|
||||
@ -2066,6 +2069,28 @@ class WorkbenchService extends Service {
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* 统计当前工作台打包成员人数(wms_workbench_member 未软删除记录)。
|
||||
* 查询失败或结果为 0 时按 1 兜底:成员全部登出时未结束任务已被自动结束,
|
||||
* 正常流程不会出现 0 人任务,兜底仅防除零。
|
||||
* @param {number} workbenchId 工作台ID
|
||||
* @return {Promise<number>} 打包成员人数(至少 1)
|
||||
*/
|
||||
async _countCurrentPackMembers(workbenchId) {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const count = await ctx.model.WorkbenchMember.count({
|
||||
where: { workbench_id: workbenchId },
|
||||
});
|
||||
if (Number.isInteger(count) && count > 0) {
|
||||
return count;
|
||||
}
|
||||
} catch (countErr) {
|
||||
ctx.logger.warn('[Workbench._countCurrentPackMembers] 统计打包成员失败: %s', countErr.message);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取仓库「大团购打包系数」配置(wms_store.subject_config.big_group_pack_coefficient)。
|
||||
* 走 deliveryOrder.getStoreSubjectConfig 公共读取链路(带缓存);配置读取失败
|
||||
@ -2100,7 +2125,7 @@ class WorkbenchService extends Service {
|
||||
* order 对象始终包含 picker_id / picker_name:通过 wave_id 关联拣货任务取拣货人,
|
||||
* 散单无波次或未分配拣货人时为 null / 空串。
|
||||
* 大团购打包时长闸门:当前工作台存在进行中的大团购打包任务时,判断是否已到
|
||||
* 「当前波次打包数 × 大团购打包系数」秒:未到时仅允许查询本波次订单,
|
||||
* 「大团购打包系数 × 当前波次打包数 ÷ 当前工作台打包人数」秒:未到时仅允许查询本波次订单,
|
||||
* 其他波次订单返回「打包时长不足」错误;已到时不受限制。
|
||||
* 查询成功时生成一次性打包上下文 key(20 分钟有效)写入 Redis,
|
||||
* 响应附 key 供 workbench.packOrder 消费,打包参数由后端维护防篡改。
|
||||
@ -2224,8 +2249,9 @@ class WorkbenchService extends Service {
|
||||
|
||||
// 步骤3.5:大团购打包时长闸门。
|
||||
// 打包任务已落库 wave_scope,直接按 wave_scope=1 快捷判定当前工作台是否有
|
||||
// 进行中的大团购任务需要限制下一个任务的开始时间:
|
||||
// - 未到「当前波次打包数 × 大团购打包系数」秒时:仅允许查询本波次订单,其他波次订单返回「打包时长不足」错误;
|
||||
// 进行中的大团购任务(status<2,任务已结束则不计)需要限制下一个任务的开始时间:
|
||||
// - 未到「大团购打包系数 × 当前波次打包数 ÷ 当前工作台打包人数」秒时:
|
||||
// 仅允许查询本波次订单,其他波次订单返回「打包时长不足」错误;
|
||||
// - 已到时:不受限制,正常下发。
|
||||
if (validQueryWorkbenchId) {
|
||||
let packTimeGateNotReached = false;
|
||||
@ -2252,7 +2278,8 @@ class WorkbenchService extends Service {
|
||||
const currentPackQuantity = Number(currentPackTask.pack_quantity) > 0
|
||||
? Number(currentPackTask.pack_quantity)
|
||||
: 1;
|
||||
const requiredSeconds = currentPackQuantity * coefficient;
|
||||
const packMemberCount = await this._countCurrentPackMembers(validQueryWorkbenchId);
|
||||
const requiredSeconds = currentPackQuantity * coefficient / packMemberCount;
|
||||
const elapsedSeconds = Math.floor((Date.now() - startMs) / 1000);
|
||||
if (elapsedSeconds < requiredSeconds) {
|
||||
packTimeGateNotReached = true;
|
||||
|
||||
@ -17,7 +17,6 @@ module.exports = appInfo => {
|
||||
|
||||
// add your middleware config here
|
||||
config.middleware = [];
|
||||
|
||||
// add your user config here
|
||||
const userConfig = {
|
||||
// myAppName: 'egg',
|
||||
@ -122,6 +121,33 @@ module.exports = appInfo => {
|
||||
fileExtension: '.log',
|
||||
progressExtension: '.progress',
|
||||
};
|
||||
// 日志落盘目录:显式声明,避免依赖 $HOME 的隐式默认值
|
||||
// (生产 HOME=/root 时 egg 默认会落到 /root/logs/wms;此处固定下来便于查询与清理)
|
||||
config.logPaths = {
|
||||
base: process.env.WMS_LOG_DIR || (process.platform === 'win32'
|
||||
? path.join(appInfo.baseDir, 'logs')
|
||||
: '/root/logs/wms'),
|
||||
};
|
||||
// 文件日志只保留 WARN/ERROR:INFO(含 egg-sequelize 逐条 SQL 日志)不再落盘,
|
||||
// 避免 wms-web.log 每天增长约 2GB 撑爆根分区(/ 仅 40G)。
|
||||
// consoleLevel 仍为 INFO,本地开发在终端照常看到 INFO,不受影响。
|
||||
// 与线上 /www/wwwroot/qimen/v1、v2 的手工配置保持一致(生产 config 不参与 deploy,由人工维护)。
|
||||
config.logger = {
|
||||
dir: config.logPaths.base,
|
||||
level: 'WARN',
|
||||
consoleLevel: 'INFO',
|
||||
};
|
||||
// 接口流水日志(已替代 wms_system_log 表,该表已下线):一行一条,字段沿用旧表结构并平铺。
|
||||
// formatter 直接返回 message,不改写内容;整行形如 `HH:mm:ss {JSON}`
|
||||
// (行首时分秒前缀由 app/lib/api_log_sink.js 加上,行尾 eol 由 egg-logger 追加)。
|
||||
config.customLogger = {
|
||||
apiLog: {
|
||||
file: path.join(config.logPaths.base, 'wms-api.log'),
|
||||
level: 'INFO',
|
||||
consoleLevel: 'NONE',
|
||||
formatter: meta => meta.message,
|
||||
},
|
||||
};
|
||||
config.fileTypes = {
|
||||
// 图片类型
|
||||
image: 'image',
|
||||
@ -267,19 +293,6 @@ module.exports = appInfo => {
|
||||
// 单批硬删除行数(按 id 分批,走主键索引)
|
||||
batchSize: 500,
|
||||
};
|
||||
// 系统日志超期清理定时任务配置(每日凌晨 03:00 执行,硬删除 wms_system_log 超期数据释放磁盘空间)
|
||||
config.systemLogCleanup = {
|
||||
enable: true,
|
||||
// 触发 cron(秒 分 时 日 月 周):默认每日凌晨 03:00;本地环境可在 config.local.js 覆盖为短间隔
|
||||
cron: '0 0 3 * * *',
|
||||
// 日志保留天数:删除 created_at 早于该天数的日志(默认 60 天,仅接受正整数,非法值回退 60)
|
||||
retainDays: 60,
|
||||
// 单批硬删除行数(按 id 升序分批,走主键索引)
|
||||
batchSize: 2000,
|
||||
// 批间休眠毫秒数下限/上限:在区间内随机取值,降低数据库瞬时压力
|
||||
sleepMinMs: 100,
|
||||
sleepMaxMs: 500,
|
||||
};
|
||||
// 配送表(dispatch) → 历史表(history) 归档定时任务配置
|
||||
// 每日凌晨 06:00 把配送表超期订单(连同商品明细)迁入历史表,并更新订单索引表位置指针
|
||||
config.orderDeliveryArchive = {
|
||||
@ -317,9 +330,26 @@ module.exports = appInfo => {
|
||||
enable: true, // 是否注册域名验证定时任务
|
||||
interval: '10m', // 扫描间隔
|
||||
lockTtlSeconds: 600, // Redis 跨进程锁 TTL(略大于 interval)
|
||||
batchSize: 50, // 单轮最多处理行数
|
||||
// 单轮最多处理行数:单行最坏耗时 ≈ (DoH 端点数 3 + 系统 DNS 兜底 1) × timeoutMs(3000ms) = 12s,
|
||||
// 20 行最坏 ≈ 240s,明显小于 lockTtlSeconds(600s) 与扫描间隔 interval(600s),跨进程锁不会被下一轮抢走
|
||||
batchSize: 20,
|
||||
// DoH 端点列表(多端点按序尝试,任一端点拿到 TXT 值即立即返回,不再询问后续端点):
|
||||
// 1) https://dns.alidns.com/resolve 阿里公共 DNS 的 JSON 接口,默认主解析器;
|
||||
// 2) https://223.5.5.5/resolve 阿里公共 DNS 的 IP 直连入口(同一后端,域名侧解析异常时兜底);
|
||||
// 3) https://doh.pub/dns-query 腾讯 doh.pub,保留但置于最后。
|
||||
// 为什么把 doh.pub 放最后:其负缓存(NODATA)可能长时间滞后于权威服务器。
|
||||
// 实测案例:主机 wmsv-aa4adaab13.wms.wms.gztbyc.com 的 TXT 记录 ddd9ae51cf95b488db544f23ccd01e7b 真实存在
|
||||
// (8.8.8.8 / 223.5.5.5 / nslookup / AliDNS DoH 四方一致),而 doh.pub 返回 Status=0 且 Answer 为空
|
||||
// (同一主机 A 查询亦 NODATA,其 SOA 序列号 2026081813 旧于 TXT 查询的 2026082815),重复两次结果一致。
|
||||
dohUrls: [
|
||||
'https://dns.alidns.com/resolve',
|
||||
'https://223.5.5.5/resolve',
|
||||
'https://doh.pub/dns-query',
|
||||
],
|
||||
// 兼容键(历史单端点配置):dohUrls 缺失/非法时 getDomainVerifyConfig() 回退用 [dohUrl];多端点生效后不应再依赖本键
|
||||
dohUrl: 'https://doh.pub/dns-query',
|
||||
timeoutMs: 5000, // 单次 DoH 请求超时
|
||||
// 单个 DoH 端点、以及系统 DNS 兜底单次查询的超时(毫秒)
|
||||
timeoutMs: 3000,
|
||||
maxAttempts: 20, // 超过后不再自动重试(仍可手动 checkDomain)
|
||||
},
|
||||
};
|
||||
|
||||
@ -1,46 +0,0 @@
|
||||
-- wms_workbench pre-migration backup (production 112.124.21.102)
|
||||
-- Generated at: 2026-09-06T13:24:37.798Z
|
||||
-- Row count: 20
|
||||
|
||||
DROP TABLE IF EXISTS `wms_workbench`;
|
||||
CREATE TABLE `wms_workbench` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`warehouse_id` bigint(20) unsigned NOT NULL COMMENT '仓库ID',
|
||||
`name` varchar(100) NOT NULL COMMENT '工作台名称(用户自定义)',
|
||||
`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态:0-禁用 1-启用',
|
||||
`type` enum('personal','group') NOT NULL DEFAULT 'personal' COMMENT '工作台类型:personal-个人工作台 group-团体工作台',
|
||||
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
|
||||
`device_ids` json DEFAULT NULL COMMENT '设备ID列表,如 [1,2,3],触发打包任务时透传到 wms_pack_task.device_ids',
|
||||
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`deleted_at` datetime DEFAULT NULL COMMENT '软删除时间',
|
||||
`login_code` varchar(64) DEFAULT NULL COMMENT '工作台登录码(前缀+随机,64位,全局唯一)',
|
||||
`token` varchar(64) DEFAULT NULL COMMENT '工作台令牌(随机64位,绑定后生成)',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_login_code` (`login_code`),
|
||||
KEY `idx_warehouse_id` (`warehouse_id`),
|
||||
KEY `idx_deleted_at` (`deleted_at`),
|
||||
KEY `idx_token` (`token`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
INSERT INTO `wms_workbench` (`id`, `warehouse_id`, `name`, `status`, `type`, `remark`, `device_ids`, `created_at`, `updated_at`, `deleted_at`, `login_code`, `token`) VALUES
|
||||
(1, 1000028, '工作1', 1, 'personal', '1111', NULL, '2026-07-20 07:57:11', '2026-07-20 07:57:23', '2026-07-20 07:57:23', NULL, NULL),
|
||||
(2, 1000028, '散单1号工作台', 1, 'personal', '11111', '9', '2026-07-20 07:58:16', '2026-07-20 07:58:56', '2026-07-20 07:58:56', NULL, NULL),
|
||||
(3, 1000028, '测试', 1, 'personal', NULL, NULL, '2026-07-20 18:01:00', '2026-09-03 00:27:19', '2026-09-03 00:27:19', NULL, NULL),
|
||||
(4, 1000028, '散单工作台1', 1, 'personal', NULL, '9', '2026-07-25 01:05:53', '2026-07-26 08:02:49', NULL, NULL, NULL),
|
||||
(5, 1000028, '散单工作台2', 1, 'personal', NULL, '10', '2026-07-25 01:05:59', '2026-07-26 08:02:53', NULL, NULL, NULL),
|
||||
(6, 1000028, '散单工作台3', 1, 'personal', NULL, '15', '2026-07-25 01:06:05', '2026-07-26 08:03:02', NULL, NULL, NULL),
|
||||
(7, 1000028, '散单工作台4', 1, 'personal', NULL, '12', '2026-07-25 01:06:11', '2026-07-26 08:03:13', NULL, NULL, NULL),
|
||||
(8, 1000028, '散单工作台5', 1, 'personal', NULL, '11', '2026-07-25 01:06:17', '2026-07-26 08:03:21', NULL, NULL, NULL),
|
||||
(9, 1000028, '散单工作台6', 1, 'personal', NULL, '13', '2026-07-25 01:06:22', '2026-07-26 08:03:27', NULL, NULL, NULL),
|
||||
(10, 1000028, '散单工作台7', 1, 'personal', NULL, '16', '2026-07-25 01:06:27', '2026-07-26 09:01:24', NULL, NULL, NULL),
|
||||
(11, 1000028, '散单工作台8', 1, 'personal', NULL, '25', '2026-07-25 01:06:33', '2026-09-05 07:12:51', NULL, NULL, NULL),
|
||||
(12, 1000028, '团购1', 1, 'personal', NULL, '4', '2026-07-31 04:10:54', '2026-07-31 04:11:32', NULL, NULL, NULL),
|
||||
(13, 1000028, '团购2', 1, 'personal', NULL, '3', '2026-07-31 04:11:06', '2026-07-31 04:11:37', NULL, NULL, NULL),
|
||||
(14, 1000028, '团购3', 1, 'personal', NULL, '2', '2026-07-31 04:11:09', '2026-07-31 04:11:52', NULL, NULL, NULL),
|
||||
(15, 1000028, '团购4', 1, 'personal', NULL, '5', '2026-07-31 04:11:13', '2026-07-31 04:12:04', NULL, NULL, NULL),
|
||||
(16, 1000028, '团购5', 1, 'personal', NULL, '6', '2026-07-31 04:11:16', '2026-07-31 04:12:31', NULL, NULL, NULL),
|
||||
(17, 1000028, '团购6', 1, 'personal', NULL, '7', '2026-07-31 04:11:19', '2026-07-31 04:12:37', NULL, NULL, NULL),
|
||||
(18, 1000028, '团购7', 1, 'personal', NULL, NULL, '2026-07-31 04:11:21', '2026-09-03 00:27:07', '2026-09-03 00:27:07', NULL, NULL),
|
||||
(19, 1000028, '小波次 1 号工作台', 1, 'personal', NULL, '4', '2026-08-28 04:13:19', '2026-08-28 04:21:51', NULL, NULL, NULL),
|
||||
(20, 1000028, '小波次 2 号工作台', 1, 'personal', NULL, '24', '2026-08-28 04:13:26', '2026-08-28 04:21:44', NULL, NULL, NULL);
|
||||
@ -0,0 +1,50 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE = 'wms_return_query_log';
|
||||
|
||||
/**
|
||||
* 退回查询记录表新增登记来源字段:group_id / group_name / user_id / user_name。
|
||||
* 站内信「查退回」触发登记时写入查询来源的群/用户信息(后台 API 登记路径为 null),
|
||||
* 用于登记追溯与后续定向回信。字段口径与 wms_video_record_request 保持一致。
|
||||
*/
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const columns = await queryInterface.describeTable(TABLE);
|
||||
if (!columns.group_id) {
|
||||
await queryInterface.addColumn(TABLE, 'group_id', {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '触发查询的群ID(站内信外部群ID)',
|
||||
});
|
||||
}
|
||||
if (!columns.group_name) {
|
||||
await queryInterface.addColumn(TABLE, 'group_name', {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '触发查询的群名称',
|
||||
});
|
||||
}
|
||||
if (!columns.user_id) {
|
||||
await queryInterface.addColumn(TABLE, 'user_id', {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '触发查询的用户ID(站内信外部用户ID)',
|
||||
});
|
||||
}
|
||||
if (!columns.user_name) {
|
||||
await queryInterface.addColumn(TABLE, 'user_name', {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '触发查询的用户名称',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
down: async queryInterface => {
|
||||
const columns = await queryInterface.describeTable(TABLE);
|
||||
if (columns.group_id) await queryInterface.removeColumn(TABLE, 'group_id');
|
||||
if (columns.group_name) await queryInterface.removeColumn(TABLE, 'group_name');
|
||||
if (columns.user_id) await queryInterface.removeColumn(TABLE, 'user_id');
|
||||
if (columns.user_name) await queryInterface.removeColumn(TABLE, 'user_name');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,220 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_warehouse_front_config';
|
||||
const PENDING_DOMAIN_INDEX_NAME = 'idx_pending_domain';
|
||||
const RETIRED_DOMAIN_INDEX_NAME = 'idx_retired_domain';
|
||||
|
||||
/**
|
||||
* Migration: 仓库前端配置表新增「两阶段域名切换」相关列与索引。
|
||||
*
|
||||
* 背景(为什么需要这次改造):
|
||||
* 原实现 frontConfig.setDomain 是「设置即生效」——一次调用就把 domain 改成新域名、
|
||||
* domain_status 归零并清空证书。后果是旧域名立刻被 frontConfig.getByDomain 判为
|
||||
* 「域名未配置」(404),而 nginx 侧旧域名 server 块还在,出现「页面能打开但拉不到配置」
|
||||
* 的中间态;用户改错域名也无法回滚。
|
||||
*
|
||||
* 方案(方案 B·两阶段切换,待验证域名与生效域名分离):
|
||||
* 1. 第一阶段(frontConfig.setDomain):只把新域名登记到 pending_domain 并下发 TXT 校验码,
|
||||
* 生效域名 domain、domain_status、domain_verified_at、证书与同步状态一律不动;
|
||||
* 2. 第二阶段(frontConfig.checkDomain 手动触发 / app/schedule/domain_verify_scan.js 定时扫描):
|
||||
* TXT 校验通过后由 frontConfig.promotePendingDomain 一次性把 pending_domain 提升为
|
||||
* domain(domain_status=1),同时把旧域名写入 retired_domain 下线队列、清空证书并重置同步状态。
|
||||
* 旧域名的 nginx 配置与证书文件由外部证书脚本按 retired_domain 删除后置 NULL(本次不改脚本)。
|
||||
*
|
||||
* 新增列(全部可空或带默认值,无需数据回填):
|
||||
* - pending_domain : 待验证域名(STRING(100),验证通过后才提升为生效域名 domain);
|
||||
* - pending_verify_host : 待验证域名的 TXT 记录主机名(STRING(255),wmsv-<随机码>.<待验证域名>);
|
||||
* - pending_verify_token : 待验证域名的 TXT 记录值(STRING(64),32 位 hex);
|
||||
* - pending_verify_attempts: 待验证域名校验尝试次数(INTEGER,NOT NULL,默认 0);
|
||||
* - pending_last_error : 待验证域名最近一次失败原因(STRING(500),脱敏截断);
|
||||
* - pending_created_at : 发起域名切换的时间(DATE);
|
||||
* - retired_domain : 待下线旧域名(STRING(100),域名提升时写入,外部脚本删除其
|
||||
* nginx 配置与证书文件后置 NULL);
|
||||
* - retired_at : 旧域名进入下线队列的时间(DATE)。
|
||||
* 新增索引:
|
||||
* - idx_pending_domain:域名验证定时任务按 pending_domain 扫描待验证行的查询索引(普通索引);
|
||||
* - idx_retired_domain:外部证书脚本按 retired_domain 扫描待下线旧域名的查询索引(普通索引)。
|
||||
*
|
||||
* 为什么无需回填:
|
||||
* 8 个新列要么可空、要么带默认值 0,存量行的 pending_* 一律为 NULL / 0 → 语义就是
|
||||
* 「没有待验证域名」,生效域名 domain / domain_status / 证书 / 同步状态全部保持原值,
|
||||
* 升级瞬间行为与升级前一致(唯一变化是下次 setDomain 会走两阶段,属预期变更)。
|
||||
* 注意:pending_domain 只有普通索引(非唯一),并发提交同一域名理论上仍可能同时写入两行,
|
||||
* 最终由 domain 上的唯一索引在「提升」阶段兜底(提升冲突会保留待验证状态并记入错误)。
|
||||
*
|
||||
* Idempotent: 列/索引已存在时跳过;down 先删索引、再按倒序删列(均判存在后执行)。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 判断表是否存在。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @return {Promise<boolean>} 存在返回 true。
|
||||
*/
|
||||
async function tableExists(queryInterface, tableName) {
|
||||
const tables = await queryInterface.showAllTables();
|
||||
return tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === tableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断索引是否存在。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @param {string} indexName 索引名。
|
||||
* @return {Promise<boolean>} 存在返回 true。
|
||||
*/
|
||||
async function indexExists(queryInterface, tableName, indexName) {
|
||||
const indexes = await queryInterface.showIndex(tableName);
|
||||
return (indexes || []).some(item => (typeof item === 'string' ? item : item.name) === indexName);
|
||||
}
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行正向迁移:新增两阶段域名切换相关列与索引(幂等,无数据回填)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
if (!(await tableExists(queryInterface, TABLE_NAME))) {
|
||||
return;
|
||||
}
|
||||
|
||||
const columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
|
||||
// 列定义表:after 显式指定列序,pending 组紧随域名验证组,retired 组接在 pending 组之后
|
||||
const columnDefs = [
|
||||
{
|
||||
name: 'pending_domain',
|
||||
after: 'domain_last_error',
|
||||
definition: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '待验证域名:setDomain 只登记到本列,TXT 校验通过后才提升为生效域名 domain',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'pending_verify_host',
|
||||
after: 'pending_domain',
|
||||
definition: {
|
||||
type: Sequelize.STRING(255),
|
||||
allowNull: true,
|
||||
comment: '待验证域名的 TXT 记录主机名(wmsv-<随机码>.<待验证域名>)',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'pending_verify_token',
|
||||
after: 'pending_verify_host',
|
||||
definition: {
|
||||
type: Sequelize.STRING(64),
|
||||
allowNull: true,
|
||||
comment: '待验证域名的 TXT 记录值(32 位 hex)',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'pending_verify_attempts',
|
||||
after: 'pending_verify_token',
|
||||
definition: {
|
||||
type: Sequelize.INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '待验证域名校验尝试次数',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'pending_last_error',
|
||||
after: 'pending_verify_attempts',
|
||||
definition: {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
comment: '待验证域名最近一次失败原因',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'pending_created_at',
|
||||
after: 'pending_last_error',
|
||||
definition: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '发起域名切换的时间',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'retired_domain',
|
||||
after: 'pending_created_at',
|
||||
definition: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '待下线旧域名:域名提升时写入,外部证书脚本删除其 nginx 配置与证书文件后置 NULL',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'retired_at',
|
||||
after: 'retired_domain',
|
||||
definition: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '旧域名进入下线队列的时间',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
for (const item of columnDefs) {
|
||||
if (!columns[item.name]) {
|
||||
await queryInterface.addColumn(TABLE_NAME, item.name, {
|
||||
...item.definition,
|
||||
after: item.after,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (!(await indexExists(queryInterface, TABLE_NAME, PENDING_DOMAIN_INDEX_NAME))) {
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'pending_domain' ], {
|
||||
name: PENDING_DOMAIN_INDEX_NAME,
|
||||
});
|
||||
}
|
||||
|
||||
if (!(await indexExists(queryInterface, TABLE_NAME, RETIRED_DOMAIN_INDEX_NAME))) {
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'retired_domain' ], {
|
||||
name: RETIRED_DOMAIN_INDEX_NAME,
|
||||
});
|
||||
}
|
||||
},
|
||||
/**
|
||||
* 回滚迁移:删除两阶段域名切换相关索引与列(幂等)。
|
||||
*
|
||||
* 注意:回滚会一并丢弃待验证域名与下线队列(pending_* / retired_*),
|
||||
* 但不会改动生效域名 domain、domain_status、证书与同步状态,因此不影响线上已生效域名。
|
||||
* 回滚后代码若仍为两阶段版本,setDomain / checkDomain 会因缺少 pending_* 列而报错,
|
||||
* 需与代码版本一并回退。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
if (!(await tableExists(queryInterface, TABLE_NAME))) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const indexName of [ RETIRED_DOMAIN_INDEX_NAME, PENDING_DOMAIN_INDEX_NAME ]) {
|
||||
if (await indexExists(queryInterface, TABLE_NAME, indexName)) {
|
||||
await queryInterface.removeIndex(TABLE_NAME, indexName);
|
||||
}
|
||||
}
|
||||
|
||||
const columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
// 倒序删除(与 up 的列序相反):先删 retired 组,再删 pending 组
|
||||
for (const columnName of [
|
||||
'retired_at',
|
||||
'retired_domain',
|
||||
'pending_created_at',
|
||||
'pending_last_error',
|
||||
'pending_verify_attempts',
|
||||
'pending_verify_token',
|
||||
'pending_verify_host',
|
||||
'pending_domain',
|
||||
]) {
|
||||
if (columns[columnName]) {
|
||||
await queryInterface.removeColumn(TABLE_NAME, columnName);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,115 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 创建客户端错误日志暂存表 wms_client_error_log。
|
||||
*
|
||||
* 背景:Android/iOS/Web 等设备端将运行时错误日志上报到服务端暂存,
|
||||
* 供人工/后台查询分析跟踪 bug。接口入口 index.uploadClientErrorLog
|
||||
* (免登录、免权限、免鉴权,保留系统日志)。
|
||||
*
|
||||
* 字段:客户端类型/版本、设备标识、系统版本/型号、错误类型、错误信息与堆栈、
|
||||
* 附加上下文 extra、report_uuid(客户端生成,唯一索引幂等去重)、
|
||||
* client_time(客户端发生时间,仅参考)、created_at(服务端写入时间)。
|
||||
*
|
||||
* 索引:idx_created_at、idx_client_type_app_version、idx_device_id、uk_report_uuid(唯一)。
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_client_error_log';
|
||||
|
||||
module.exports = {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { BIGINT, STRING, DATE, TEXT } = Sequelize;
|
||||
await queryInterface.createTable(TABLE_NAME, {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
client_type: {
|
||||
type: STRING(32),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '客户端类型:android/ios/web 等',
|
||||
},
|
||||
app_version: {
|
||||
type: STRING(64),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '客户端版本号',
|
||||
},
|
||||
device_id: {
|
||||
type: STRING(128),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '设备唯一标识',
|
||||
},
|
||||
os_version: {
|
||||
type: STRING(64),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '操作系统版本',
|
||||
},
|
||||
device_model: {
|
||||
type: STRING(128),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '设备型号',
|
||||
},
|
||||
error_type: {
|
||||
type: STRING(64),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '错误类型/等级',
|
||||
},
|
||||
error_message: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '错误信息(服务端截断上限 5000 字符)',
|
||||
},
|
||||
error_stack: {
|
||||
type: TEXT('medium'),
|
||||
allowNull: true,
|
||||
comment: '错误堆栈(服务端截断上限 65535 字符)',
|
||||
},
|
||||
extra: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '附加上下文(JSON 字符串,服务端截断上限 65535 字符)',
|
||||
},
|
||||
report_uuid: {
|
||||
type: STRING(64),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '客户端上报幂等ID(唯一索引,重复上报静默成功)',
|
||||
},
|
||||
client_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '客户端错误发生时间(仅参考,不作为记录时间)',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '服务端写入时间(统一取服务器当前时间)',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '更新时间',
|
||||
},
|
||||
});
|
||||
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'created_at' ], { name: 'idx_created_at' });
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'client_type', 'app_version' ], { name: 'idx_client_type_app_version' });
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'device_id' ], { name: 'idx_device_id' });
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'report_uuid' ], { name: 'uk_report_uuid', unique: true });
|
||||
},
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.dropTable(TABLE_NAME);
|
||||
},
|
||||
};
|
||||
106
database/migrations/20260927090000-offline-wms-system-log.js
Normal file
106
database/migrations/20260927090000-offline-wms-system-log.js
Normal file
@ -0,0 +1,106 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 下线 wms_system_log(接口流水表)。
|
||||
*
|
||||
* 背景:接口流水已改为经 Egg 自定义 logger(`config.customLogger.apiLog`)平铺写入
|
||||
* `/root/logs/wms/wms-api.log`,应用侧不再有任何写入路径;生产库该表已膨胀到
|
||||
* 687,030 行 / DATA_LENGTH 19,357 MB(约 18.9 GB),而 DATA_FREE 仅 5 MB ——
|
||||
* 单纯按保留期删行不会把空间还给操作系统,必须整表下线才能回收磁盘。
|
||||
*
|
||||
* ⚠️ 本迁移会永久丢弃表内历史数据。如需留档,请在执行前先自行导出:
|
||||
* mysqldump -h127.0.0.1 -uwms -p wms wms_system_log | gzip > /root/wms_system_log-$(date +%F).sql.gz
|
||||
*
|
||||
* 幂等:up 用 DROP TABLE IF EXISTS;down 先探测表存在性再重建。
|
||||
*
|
||||
* 同批次一起下线的代码(见同批改动):
|
||||
* - app/model/system_log.js (已删除)
|
||||
* - app/service/systems/system_log.js (已删除,60 天保留期清理服务)
|
||||
* - app/schedule/system_log_cleanup.js (已删除,每日 03:00 清理定时任务)
|
||||
* - app/lib/api_log_sink.js (移除 writeToDb 回滚入库分支)
|
||||
* - config/config.default.js (移除 systemLog / systemLogCleanup)
|
||||
*
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:删除 wms_system_log 表(幂等)。
|
||||
*
|
||||
* 说明:该表对 wms_store 有外键(wms_system_log.store_id → wms_store.id),
|
||||
* 属"出边"外键,删除子表不影响父表,无需先关闭 FOREIGN_KEY_CHECKS;
|
||||
* 已确认库内没有指向 wms_system_log 的入边外键、视图或触发器。
|
||||
*
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async up(queryInterface) {
|
||||
const tableName = 'wms_system_log';
|
||||
// 用 information_schema 探测而非依赖异常:MySQL 5.7 / 8.0 的 IF EXISTS 行为一致但便于记录日志
|
||||
const [[ probe ]] = await queryInterface.sequelize.query(
|
||||
'SELECT COUNT(*) AS cnt FROM information_schema.TABLES'
|
||||
+ ' WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :tableName',
|
||||
{ replacements: { tableName } }
|
||||
);
|
||||
if (!Number(probe && probe.cnt)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [[ size ]] = await queryInterface.sequelize.query(
|
||||
'SELECT ROUND(DATA_LENGTH / 1024 / 1024) AS data_mb, ROUND(INDEX_LENGTH / 1024 / 1024) AS idx_mb, TABLE_ROWS AS est_rows'
|
||||
+ ' FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :tableName',
|
||||
{ replacements: { tableName } }
|
||||
);
|
||||
await queryInterface.sequelize.query(`DROP TABLE IF EXISTS \`${tableName}\``);
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(
|
||||
`[offline-wms-system-log] 已删除 ${tableName}(原估算行数=${size && size.est_rows}`
|
||||
+ ` 数据=${size && size.data_mb}MB 索引=${size && size.idx_mb}MB)`
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:按原结构重建空的 wms_system_log 表(幂等,不恢复数据)。
|
||||
*
|
||||
* 直接用原生 DDL 重建,而不是 queryInterface.createTable —— 后者在 MySQL 下
|
||||
* 默认字符集是 utf8(即 utf8mb3),也不会生成原始的
|
||||
* `created_at datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP`;
|
||||
* 只有原生 DDL 才能让回滚后的结构与下线前完全一致。
|
||||
*
|
||||
* ⚠️ 表内数据不会恢复;需要留档请在 up 之前自行 mysqldump。
|
||||
*
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
const tableName = 'wms_system_log';
|
||||
const tables = await queryInterface.showAllTables();
|
||||
if (tables.includes(tableName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.sequelize.query(
|
||||
`CREATE TABLE \`${tableName}\` (`
|
||||
+ ' `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT,'
|
||||
+ ' `method` varchar(100) DEFAULT NULL,'
|
||||
+ ' `v` varchar(50) DEFAULT NULL,'
|
||||
+ ' `url` text,'
|
||||
+ ' `created_at` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,'
|
||||
+ ' `body` longtext,'
|
||||
+ ' `result` longtext,'
|
||||
+ ' `use_time` int DEFAULT NULL,'
|
||||
+ ' `updated_at` datetime DEFAULT NULL,'
|
||||
+ ' `delete_at` datetime DEFAULT NULL,'
|
||||
+ ' `headers` text,'
|
||||
+ ' `auth` text,'
|
||||
+ ' `store_id` bigint UNSIGNED DEFAULT NULL,'
|
||||
+ ' `device` varchar(100) DEFAULT NULL COMMENT \'设备\','
|
||||
+ ' PRIMARY KEY (`id`),'
|
||||
+ ' KEY `store_id` (`store_id`),'
|
||||
+ ' CONSTRAINT `wms_system_log_ibfk_1` FOREIGN KEY (`store_id`)'
|
||||
+ ' REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION'
|
||||
+ ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci'
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -1,4 +1,194 @@
|
||||
[
|
||||
{
|
||||
"version": "2026.09.26-order-packing-returnUnpack-where-person-filter",
|
||||
"date": "2026-09-26",
|
||||
"type": "updated",
|
||||
"summary": "接口入参新增:order.packing.list 新增 where.operator_text(打包员/作业人员筛选,wms_pack_task.operator_text 多人姓名逗号拼接快照,支持 {operator,value,type} 标准结构,value 支持字符串或数组多值取并集;contains/like 与缺省为 LIKE 模糊(通配符已转义)、eq/in 精确、ne 不等于、notlike 逐值排除、空值忽略);returnUnpack.list 新增 where.unpacker_name(拆包人筛选,wms_return_unpack.unpacker_name 工号名称快照,like 支持数组多值并集,兼支持 eq/ne/in/notin/between)。同一 _buildListWhere 被复用,order.packing.export 与 returnUnpack.export 的 where 同步获得同一筛选语义(其 where 字段清单已补 operator_text / unpacker_name)。",
|
||||
"methods": [
|
||||
"order.packing.list",
|
||||
"order.packing.export",
|
||||
"returnUnpack.list",
|
||||
"returnUnpack.export"
|
||||
],
|
||||
"notes": [
|
||||
"变更类型:updated(接口入参新增 where 字段,不新增/删除 method、不改变响应结构与错误码)。",
|
||||
"代码依据:app/service/systems/order_packing.js#_buildListWhere(operator_text 分支,同时被 list 与 exportPackTask 复用,L525/L653);app/service/systems/return_unpack.js#_buildListWhere(textFields 新增 unpacker_name,同时被 list 与 exportUnpack 复用,L937/L1149)与 #_resolveConditionValue(like 支持数组多值并集)。目标列:wms_pack_task.operator_text(TEXT,多人姓名逗号拼接快照,如 小吴哥,阿猫;写入见 app/service/systems/workbench.js);wms_return_unpack.unpacker_name(STRING(50) NOT NULL,拆包人员工号名称快照 employees_name/real_name,app/model/return_unpack.js)。",
|
||||
"operator_text 取值口径(以代码为准):支持 {operator,value,type} 标准结构,value 支持字符串或字符串数组(多值取并集);operator=contains/like 与缺省(不传 operator)→ LIKE %值%(%/_ 通配符已转义);operator=eq/in → 精确匹配(单值等值、多值 IN);operator=ne → 不等于(多值取首值);operator=notlike → NOT LIKE %值%(多值逐个 AND 排除);值为 空串/null/空数组(trim/去空归一后为空)时忽略该条件(不过滤)。",
|
||||
"unpacker_name 取值口径(以代码为准):{operator:\"like\",value} 或直接值 → LIKE %值%;value 为数组时多值 LIKE 取并集(trim/去空归一后为空退化为 %% 全匹配、不过滤);同时兼容 _resolveConditionValue 既有操作符 eq/ne/in/notin/between/gt/gte/lt/lte。",
|
||||
"文档变更范围:methods/system.json 更新 order.packing.list(where.children 新增 operator_text)、order.packing.export(where description 字段清单补 operator_text)、returnUnpack.list(params 新增 where.unpacker_name)、returnUnpack.export(where description 字段清单补 unpacker_name)共 4 条;分组条数与响应结构不变;根版本 0.3.190 → 0.3.191、updatedAt 2026-09-25 → 2026-09-26;methods/changes/system.json 新增本条(插入数组首位)。",
|
||||
"前端传参示例:order.packing.list / export 传 {\"where\":{\"operator_text\":{\"value\":\"小吴哥\",\"operator\":\"like\",\"type\":\"text\"}}};returnUnpack.list / export 传 {\"where\":{\"unpacker_name\":{\"operator\":\"like\",\"value\":\"阿猫\"}}}。",
|
||||
"维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta,导出脚本 script/method-doc-export.cjs)。本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库(遵循「只修改文档」红线)。后续需由维护者决定是否同步入库(method-doc-update 或全量 method-doc-import 后重新导出),否则下次执行 method-doc-export.cjs 会用库表重建 system.json 而丢失本次文件改动。",
|
||||
"发布顺序:纯文档变更,无迁移、无代码改动(代码已实现并通过 ESLint),前端无需适配。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.25-index-upload-client-error-log",
|
||||
"date": "2026-09-25",
|
||||
"type": "added",
|
||||
"summary": "新增客户端错误日志上报接口 index.uploadClientErrorLog(免登录、免权限、免鉴权,保留系统日志):设备端运行时错误批量上报暂存到新表 wms_client_error_log。入参支持单条对象/数组/{ logs: [...] } 三种形态、单次最多 50 条;snake_case 为主并兼容 camelCase 别名;error_message/error_stack 至少一项有值(超长截断 5000/65535),extra 截断 65535;report_uuid 唯一索引幂等去重(重复静默成功,duplicated +1),缺失时服务端生成 srv-{uuid};client_time 仅参考(非法存 null)。成功返回 code=200 + total/accepted/duplicated/rejected/rejected_reasons(≤10) 统计;方法级错误 HTTP 200 + flag=failure(code=400/500)。配套迁移 database/migrations/20260925100000-create-wms-client-error-log.js、模型 app/model/client_error_log.js、服务 app/service/systems/client_error_log.js。",
|
||||
"methods": [
|
||||
"index.uploadClientErrorLog"
|
||||
],
|
||||
"notes": [
|
||||
"变更类型:added(新增 method + 新增表);影响范围:methods/system.json 的 index(基础模块)分组 28 → 29 条,根版本 0.3.189 → 0.3.190、updatedAt 2026-09-24 → 2026-09-25;methods/changes/system.json 新增本条(插入数组首位)。",
|
||||
"入口与鉴权:POST /system?method=index.uploadClientErrorLog&v=1×tamp=<数字时间戳>(controller.home.system 统一入口);请求头需 platform、project(根 headers 已声明枚举),无 Authorization/token;方法已登记 _noNeedLogin/_noNeedRight/_noNeedAuth,且不在 INDEX_NO_NEED_LOG_METHODS 清单 → 保留系统日志(index 模块日志口径已由通配改为显式清单)。",
|
||||
"入参归一化口径(代码为准):三种形态三选一(单条对象 / 数组 / { logs: [...] },单次最多 50 条,超限 code=400);字段按 snake_case 读取并兼容 camelCase 别名(clientType/appVersion/deviceId/osVersion/deviceModel/errorType/errorMessage/errorStack/reportUuid/clientTime);字符串字段超宽截断:client_type 32、app_version 64、device_id 128、os_version 64、device_model 128、error_type 64、report_uuid 64;error_message 截断 5000、error_stack 截断 65535(两者至少一项有值,否则该条 rejected);extra 支持对象(JSON.stringify 后截断 65535);client_time 支持毫秒/秒时间戳(≥1e12 视为毫秒)与日期字符串,非法解析存 null。",
|
||||
"幂等语义:report_uuid 唯一索引 uk_report_uuid —— 写入前先查已有 uuid,重复项 duplicated +1 且不再写入(静默成功);客户端未传 report_uuid 时服务端生成 srv-{uuid},此时不做幂等去重、不保证幂等;created_at/updated_at 由 Sequelize 统一取服务器时间,不采信 client_time。",
|
||||
"表结构:wms_client_error_log —— id BIGINT(20) UNSIGNED 自增主键;client_type/app_version/device_id/os_version/device_model/error_type/report_uuid 为 STRING(32/64/128/64/128/64/64,NOT NULL DEFAULT '');error_message TEXT、error_stack MEDIUMTEXT、extra TEXT 可空;client_time/created_at/updated_at DATE(created_at/updated_at NOT NULL);索引 uk_report_uuid(唯一)、idx_created_at、idx_client_type_app_version、idx_device_id。",
|
||||
"出参(成功):{ flag:'success', code:200, message:'上报成功', success:true, total, accepted, duplicated, rejected, rejected_reasons(≤10 条,每条 { index, reason }), timestamp };失败(400/500):HTTP 200 + { flag:'failure', code, message, timestamp }。",
|
||||
"客户端接入示例(无需 token,仅需公共头 platform/project 与 query method/v/timestamp):curl -X POST 'https://<host>/system?method=index.uploadClientErrorLog&v=1×tamp=1764000000' -H 'platform: app' -H 'project: wms' -H 'Content-Type: application/json' -d '{\"client_type\":\"android\",\"app_version\":\"1.2.3\",\"device_id\":\"dev-001\",\"os_version\":\"Android 14\",\"device_model\":\"Pixel 8\",\"error_type\":\"crash\",\"error_message\":\"NullPointerException\",\"error_stack\":\"...\",\"report_uuid\":\"uuid-2026-001\",\"client_time\":1763999999000}';Kotlin(OkHttp) 伪代码:RequestBody.create(MediaType.parse(\"application/json\"), JSONObject().apply{put(\"client_type\",\"android\");put(\"error_message\",\"...\");put(\"report_uuid\", UUID.randomUUID().toString())}.toString()),Request.Builder().url(\"$base/system?method=index.uploadClientErrorLog&v=1×tamp=${System.currentTimeMillis()/1000}\").header(\"platform\",\"app\").header(\"project\",\"wms\").post(body).build() —— 客户端应在本地生成 report_uuid 以保证重试幂等。",
|
||||
"前端/客户端是否需适配:是(仅客户端接入层)。既有 /system 前端无改动;android/ios/web 端需按上述示例补齐 platform/project 头与 method/v/timestamp query,并自行生成并持久化 report_uuid 以利用幂等;无 token 校验,无需改造登录态链路。",
|
||||
"维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta,导出脚本 script/method-doc-export.cjs)。本次仅按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库(遵循「只修改文档」红线,与 2026-09-24 变更记录口径一致)。后续需由维护者决定是否以 method-doc-create 将该方法入库并重新导出,否则下次执行 method-doc-export.cjs 会用库表重建 system.json 而丢失本条。",
|
||||
"发布顺序:迁移(20260925100000-create-wms-client-error-log)先于代码发布;迁移为纯建表、无回填,先迁移无风险。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.24-front-config-domain-two-phase-switch",
|
||||
"date": "2026-09-24",
|
||||
"type": "updated",
|
||||
"summary": "域名切换改为两阶段(待验证域名与生效域名分离)—— frontConfig.setDomain 只登记待验证域名 pending_domain 并下发 TXT 校验码,TXT 校验通过后才由提升逻辑切换为生效域名并清空证书;新增旧域名下线记录 retired_domain;解决「改域名瞬间旧域名公共接口 404」的中间态问题。",
|
||||
"methods": [
|
||||
"frontConfig.setDomain",
|
||||
"frontConfig.getDomain",
|
||||
"frontConfig.checkDomain",
|
||||
"frontConfig.getByDomain",
|
||||
"frontConfig.saveCert",
|
||||
"frontConfig.getCert"
|
||||
],
|
||||
"notes": [
|
||||
"变更原因(旧口径问题,P0 中间态):旧 setDomain 是「设置即生效」—— 一次调用即改写生效域名 domain、domain_status 归零并清空证书,frontConfig.getByDomain 的放行闸门(domain + domain_status=1)对旧域名立即失效 → 旧域名公共接口立刻 404,而 nginx 侧旧域名 server 块仍在,出现「页面能打开但拉不到配置」的中间态;且用户改错域名无法回滚(只能再改一次并重新举证)。本轮以「待验证域名与生效域名分离」彻底消除该中间态。",
|
||||
"数据层:wms_warehouse_front_config 新增 8 列 —— pending_domain(STRING(100))、pending_verify_host(STRING(255))、pending_verify_token(STRING(64))、pending_verify_attempts(INTEGER NOT NULL 默认 0)、pending_last_error(STRING(500))、pending_created_at(DATE)、retired_domain(STRING(100),待下线旧域名)、retired_at(DATE);新增普通索引 idx_pending_domain(域名验证定时任务扫描待验证行)与 idx_retired_domain(外部脚本扫描待下线旧域名)。迁移文件 database/migrations/20260924180000-add-pending-domain-to-wms-warehouse-front-config.js(up/down 幂等)。纯追加且可空/带默认值,「无需任何数据回填」:存量行的 pending_* 为 NULL/0,语义即「没有待验证域名」,升级瞬间行为与升级前一致。",
|
||||
"四分支决策表(frontConfig.setDomain,域名比较忽略大小写):A 入参 == 生效域名且无 pending → 幂等短路(不写库;仅大小写不一致时改写 domain 字面值并清新旧两个字面值缓存);B 入参 == 生效域名且有 pending → 取消待切换(只清空 pending 6 列,生效域名/证书/同步状态一律不动);C 入参 == 现有 pending_domain → 校验码齐全则幂等短路,缺码(脏数据)则只补发 pending 校验码并清 pending_verify_attempts / pending_last_error;D 其它(含首次设置)→ 查重通过后只写 pending_domain + 新校验码,domain / domain_status / domain_verified_at / domain_verify_* / 证书 5 列 / 同步 4 列一律不动,也不清任何公共缓存。查重由「其他仓库 domain 命中」扩展为「其他仓库 domain 或 pending_domain 命中」→ 409「域名 X 已被其他仓库使用」。",
|
||||
"提升逻辑(frontConfig.promotePendingDomain,checkDomain 路径一与定时扫描共用):TXT 校验通过后一次 update 提交 —— domain = pending_domain、domain_status=1、domain_verified_at=now、domain_verify_host/token/attempts 由 pending_* 平移、domain_last_error=NULL;旧域名(生效域名非空且与待验证域名不同)写入 retired_domain + retired_at;清空 pending 6 列(pending_verify_attempts 归 0);清空证书 5 列(cert_pem / cert_key / cert_path / key_path / cert_expire_at);重置同步 4 列(sync_status=0、sync_attempts=0、last_sync_error=NULL、last_synced_at=NULL);由调用方清理旧域名与新域名两个公共拉取缓存(clearDomainCaches,先写库后清缓存,清失败仅记 WARN)。update 的 where 带 id + pending_domain 防并发重复提升。",
|
||||
"响应契约变化(纯追加、旧字段名与语义不变,前端可先发版兼容):frontConfig.getDomain 由 9 字段扩为 16 字段(追加 pending_domain / pending_verify_host / pending_verify_value / pending_attempts / pending_last_error / pending_created_at / pending_active);frontConfig.setDomain 响应同步由 9 字段扩为 16 字段;frontConfig.checkDomain 响应由 11 字段扩为 18 字段(getDomain 的 16 字段 + verified + resolved_values),并新增 409 错误码(提升时 domain 唯一索引冲突)。生效域名组字段名与语义一字未改:domain_status=1 时 verify_host/verify_value 仍返回空字符串;待验证域名在 pending_domain 非空时始终回显校验码(pending_verify_host / pending_verify_value)。",
|
||||
"旧域名下线由外部脚本执行(retired_domain 契约):script/warehouse-cert-sync.cjs 消费 retired_domain —— 删除该域名的 nginx server 块与证书文件后把 retired_domain 置 NULL,并有目录孤儿兜底清理;应用侧(service / schedule)不碰任何 nginx 文件。实测核对:当前工作区的 script/warehouse-cert-sync.cjs 尚未引用 retired_domain(全文检索 0 命中),该下线动作需脚本侧补齐后本闭环才完整;retired_domain 只保留最近一个旧域名,多次连续切换会丢中间域名(依赖脚本孤儿兜底清理)。",
|
||||
"发布顺序强约束(必须先迁移、再发代码):新代码的 SELECT 走 Sequelize 全字段,若生产库尚未执行迁移(pending_* / retired_* 共 8 列不存在),frontConfig.setDomain / getDomain / checkDomain 乃至 frontConfig.getByDomain 都会报 ER_BAD_FIELD_ERROR;定时扫描 verifyPendingDomains 会 fail-soft 返回零统计并记 WARN(含「迁移尚未执行」提示)。迁移为纯追加可空,先在生产执行迁移无风险。升级顺序:迁移 → 发布代码 → 前端发版。",
|
||||
"前端必须改造要点:①setDomain 提交成功后的 TXT 指引改读 pending_verify_host / pending_verify_value(不能再用 verify_host / verify_value);②首次设置时 domain 为空字符串是正常态(待验证域名在 pending_domain);③新增「取消待切换」交互 = 用当前生效域名再调一次 setDomain(走分支 B);④「切换中」状态用 pending_active / pending_attempts / pending_last_error / pending_created_at 展示;⑤提升完成后提示「切换完成,请重新上传证书」(提升会清空证书并重置同步状态);⑥明确「切换期间上传的证书属于旧域名」,提升后失效。",
|
||||
"文档变更范围与版本号:methods/system.json 更新 frontConfig.setDomain / frontConfig.getDomain / frontConfig.checkDomain / frontConfig.getByDomain / frontConfig.saveCert / frontConfig.getCert 共 6 条(description + notes;其中 setDomain / getDomain / checkDomain 的 response 同步追加待验证域名组 7 字段,checkDomain 另补 409);frontConfig 分组仍 8 条、其余方法未动;methods/changes/system.json 新增本条记录(插入数组首位);根版本 0.3.188 → 0.3.189(updatedAt 保持 2026-09-24)。",
|
||||
"历史记录说明(不回改):既有变更记录中关于「setDomain 未变化即幂等短路、缺码补发校验码」「domain_status=1 一律短路不降级」等描述属当时真实口径,作为历史事实不回改,由本条新记录承接并覆盖(现口径为四分支 A/B/C/D,原「缺码补发·已验证」分支已不存在)。",
|
||||
"维护源口径冲突(仅记录,未处理):methods/*.json 的维护源是否为数据库表 wms_method_doc_meta 仍待用户决策;本次仍按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库(红线要求)。",
|
||||
"未处理遗留(建议单独修正):app/schedule/domain_verify_scan.js 头注释仍描述升级前口径(扫描 domain_verify_* 行并回写 domain_status / domain_verified_at / domain_verify_attempts / domain_last_error),与两阶段实现(只扫 pending 组、回写 pending_* 并在通过时提升)不符;app/service/systemMethods/frontConfig.js 的部分 JSDoc 仍写「生效域名组 9 字段」。两者均位于 app/**,本次为文档任务、不改代码,仅报告。"
|
||||
],
|
||||
"module": "frontConfig"
|
||||
},
|
||||
{
|
||||
"version": "2026.09.24-front-config-doh-multi-endpoint",
|
||||
"date": "2026-09-24",
|
||||
"type": "updated",
|
||||
"summary": "修复 DNS 解析误判 —— DoH 改为多端点顺序尝试(dohUrls),单端点「无记录」不再直接定论;仅在所有解析路径都失败时才判解析错误。",
|
||||
"methods": [
|
||||
"frontConfig.checkDomain"
|
||||
],
|
||||
"notes": [
|
||||
"问题与实测案例:仓库 wmsv-aa4adaab13.wms.wms.gztbyc.com 的 TXT 记录真实存在(值 ddd9ae51cf95b488db544f23ccd01e7b,8.8.8.8 / 223.5.5.5 / AliDNS DoH / nslookup 四方一致),但默认 DoH 端点 doh.pub 返回 Status=0 且无 Answer(陈旧负缓存,其返回的 SOA 序列号偏旧);旧实现把单端点的 NODATA 直接定论为「未解析到 TXT 记录」→ domain_status=2 → 被 frontConfig.getByDomain 与 nginx 放行闸门断流(真实记录存在却被判为未解析到)。",
|
||||
"新口径:DoH 改为多端点顺序尝试(dohUrls,默认 alidns → 223.5.5.5 → doh.pub)+ 单端点结果三分类(values 立即返回 / empty 继续下一个端点 / error 继续下一个端点);empty(NODATA 或 NXDOMAIN)与 error 都不再直接定论,全部端点未取到值后降级系统 DNS;只要有一个端点或系统 DNS 明确答复「无该记录」就返回 [] (未解析到记录,不抛错),仅「所有 DoH 端点都是 error 且系统 DNS 也失败」才抛 500「DNS 解析失败:…」。",
|
||||
"配置兼容规则(dohUrl → dohUrls):config.frontConfig.domainVerify.dohUrls 为有效非空字符串数组时优先使用(顺序不变);否则回退历史单端点键 dohUrl(等价 [dohUrl]);两者均无效时回退内置默认数组 DEFAULT_DOH_URLS。旧键 dohUrl 保留读兼容,不作废。",
|
||||
"配置默认值变更:timeoutMs 5000 → 3000(单端点超时,系统 DNS 兜底同样显式限时 3s)、batchSize 50 → 20;配套核算 batchSize ≤ lockTtlSeconds×0.5 ÷ ((N+1)×timeoutMs/1000)(N 为端点数),3 端点场景单行最坏 12s、20 行 240s < lockTtlSeconds 600s。",
|
||||
"返回值契约:内部 resolveTxtValues 新增 endpoint 字段(追加不破坏,仍返回 { values, source, endpoint });verifyDomainRecord 契约不变({ verified, values, source, error },永不抛异常);新增内部 helper resolveDohUrls、queryDohEndpoint。",
|
||||
"可观测性:每个端点的 empty / error 均打日志(含 host + endpoint + 脱敏原因),可区分「记录不存在」与「链路不可用」。",
|
||||
"前端无感:不影响任何 method 的入参 / 响应结构,仅影响 frontConfig.checkDomain 与定时任务 domain_verify_scan 的判定正确性。",
|
||||
"文档变更范围:仅更新 frontConfig.checkDomain(description + notes),frontConfig 分组仍 8 条、各 response 计数不变;新增 1 条变更记录;根版本 0.3.187 → 0.3.188(updatedAt 保持 2026-09-24)。",
|
||||
"历史记录说明:既有变更记录中关于「Status=3 或无 Answer 视为未解析到记录、不重复走系统 DNS」的描述属于当时的真实口径,作为历史事实不回改,由本条新记录承接并覆盖。"
|
||||
],
|
||||
"module": "frontConfig"
|
||||
},
|
||||
{
|
||||
"version": "2026.09.24-front-config-domain-verified-shortcircuit",
|
||||
"date": "2026-09-24",
|
||||
"type": "updated",
|
||||
"summary": "修复「domain_status=1 的已验证域名可能被误降级」问题:frontConfig.setDomain 删除「已验证缺码补发」分支(已验证域名一律幂等短路、不补码、不写库);frontConfig.checkDomain 对 domain_status=1 一律短路返回 verified=true 且不写库、不改状态、不增加验证次数。",
|
||||
"methods": [
|
||||
"frontConfig.setDomain",
|
||||
"frontConfig.checkDomain"
|
||||
],
|
||||
"notes": [
|
||||
"变更原因(P0 回归修复):上一轮把「domain_status=1 且缺校验码」的已验证域名也做成缺码补发,使 frontConfig.checkDomain 的「历史回填行短路」条件不再成立——用户手动点一次「校验」即走真实 DNS 解析,失败便把 domain_status 由 1 写成 2(domain_verify_attempts+1、domain_last_error 有值),随后被 frontConfig.getByDomain 与 nginx 放行闸门断流;且 status=1 时 getDomain 不回显校验码,用户无从发现补发的码。本轮改为「已验证域名一律不补码、一律短路」。",
|
||||
"问题现象与复现路径:库内 domain_status=1 且 domain_verify_host/domain_verify_token 为空(迁移回填常态)→ 前端再次提交同一域名触发 frontConfig.setDomain(旧口径走 C 分支补码入库)→ frontConfig.getDomain 因 domain_status=1 仍返回空 verify_host/verify_value(补发的码任何接口都读不到)→ 用户点「校验」触发 frontConfig.checkDomain,此时短路条件「无校验码」已不成立 → 走真实 DNS 解析 → 未配置对应 TXT 记录解析失败 → domain_status 由 1 写成 2、attempts+1、last_error 有值 → frontConfig.getByDomain 与 nginx 闸门断流(线上已生效域名被降级)。",
|
||||
"修复后口径(实现 app/service/systems/frontConfig.js):frontConfig.setDomain 删除原 C「缺码补发·已验证」分支,五分支收敛为 A/B/D/E/F(C 并入 A)——A 的判定为「域名忽略大小写相同 且(校验码齐全且字面值一致 或 domain_status=1)」,命中即幂等短路:不写库、不补码、不刷新校验码、不改验证状态与尝试次数、不清证书、不重置同步状态、不清缓存;B 大小写规范化仅改 domain 字面值(status=1 且缺码同样不补码);D 缺码补发仅限 domain_status∈{0,2};E 域名变更与 F 首次设置行为不变。三条「未变化」分支(A/B/D)均不写入 domain_verified_at。",
|
||||
"frontConfig.checkDomain 短路口径放宽:由「domain_status=1 且缺校验码」改为「domain_status=1」(不论库内有无校验码)一律短路,返回 verified=true、resolved_values=[],不写库、不改状态、不增加 attempts;已验证域名不再重复校验,误点「校验」不会把生效中的域名降级。",
|
||||
"行为影响(已知取舍):已验证(domain_status=1)域名自此无法通过 frontConfig.checkDomain 重新验证;如需该能力需另开接口(本次未做)。如需重新验证,应先通过 frontConfig.setDomain 变更域名(生成新校验码并回到「未验证」)后再校验。",
|
||||
"前端约束:不得依赖「重复调用 frontConfig.setDomain 换新校验码」——域名未变化时一律幂等短路,不会下发新码;当前也没有「更换校验码」的独立接口。",
|
||||
"文档变更范围:methods/system.json 更新 frontConfig.setDomain、frontConfig.checkDomain 的 description 与 notes,并顺带修正 frontConfig.getInfo(response.domain 描述)与 frontConfig.saveInfo(description)中「domain 只能通过 frontConfig.saveCert 变更」的陈旧表述(实际已收敛到 frontConfig.setDomain);4 条 method 的 params/response/errors/headers 均未变动,frontConfig 分组仍为 8 条;methods/changes/system.json 新增本条记录(插入数组首位);根版本 0.3.186 → 0.3.187,updatedAt 保持 2026-09-24。",
|
||||
"验证与实测:测试链路已确认「status=1 缺码 → setDomain 不再补码、不写库」「status=1 调 checkDomain 一律短路、不写库、不降状态、attempts 不变」「A/B/D/E/F 五分支行为与文档一致」;文档侧经 npm run doc:api:update --dry-run 预检,并以写入前备份做最小 diff 审计(除版本行、4 条 method、1 条 change 外无其它条目被动)。",
|
||||
"维护源口径冲突(仅记录,未处理):与前两轮一致,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-setDomain-idempotent",
|
||||
"date": "2026-09-24",
|
||||
"type": "updated",
|
||||
"summary": "frontConfig.setDomain 语义收敛 —— 域名未变化时幂等短路,不再重新生成 DNS TXT 校验码、不再重置验证进度;仅「库内缺少校验码」时补发(已验证域名不降级),仅「库内域名大小写不同」时做小写规范化;域名变更与首次设置行为不变。",
|
||||
"methods": [
|
||||
"frontConfig.setDomain"
|
||||
],
|
||||
"notes": [
|
||||
"变更原因:旧口径下「同一域名未验证/验证失败则重发新校验码并清零 attempts/last_error」,导致用户每次重复提交同一域名都会作废已配置好的 TXT 记录、并清空验证进度(attempts 归零、失败原因丢失),属无谓的进度回退;本轮以「域名是否变化」为第一决策点做幂等收敛",
|
||||
"五分支口径(实现 app/service/systems/frontConfig.js setDomain):A 完全未变化(忽略大小写相同 + 库内已有校验码 + 字面值一致)→ 幂等短路,不写库、不刷新校验码、不改验证状态与尝试次数、不清证书、不重置同步状态、不清缓存;B 大小写规范化(忽略大小写相同但库内字面值不同,如库内 Shop.com、入参 shop.com)→ 仅把 domain 规范化为小写并清理新旧两个字面值的公共缓存,校验码与验证状态不变;C 缺码补发·已验证(domain_status=1 但 host/token 为空)→ 仅补发校验码,domain_status/domain_verified_at/attempts 保持原值不降级;D 缺码补发·未验证或失败(domain_status∈{0,2} 且缺码)→ 补发校验码 + domain_status=0 + attempts=0 + 清 last_error;E 域名变更(忽略大小写后不同)→ 行为不变:查重 409、生成新校验码、domain_status=0、attempts=0、清空证书(cert_pem/cert_key/cert_path/key_path/cert_expire_at)+ 重置同步状态、清理新旧两个 domain 缓存;F 首次设置(无记录)→ 行为不变:先查重 409,其余同 E",
|
||||
"未变化短路(A/B/C/D)不再写入 domain_verified_at(该字段现在只在域名变更/首次设置分支被置 null),也不再调用 assertDomainUnique 查重;变更/首次设置(E/F)查重逻辑与 409 文案保持不变",
|
||||
"行为影响提示:domain_status=2(验证失败)的行若 domain_verify_attempts 已达 config.frontConfig.domainVerify.maxAttempts(默认 20),app/schedule/domain_verify_scan.js 不会再自动拾起(计入 skipped),恢复路径为手动调用 frontConfig.checkDomain(checkDomain 无 maxAttempts 门控);且当前没有「更换校验码」的接口,如需该能力需另开接口",
|
||||
"前端不得再依赖「重复调用 setDomain 换新校验码」这一行为;需要新校验码的场景只有库内缺码(C/D 自动补发),其余重复提交均按幂等短路处理",
|
||||
"文档变更范围:methods/system.json 仅更新 frontConfig.setDomain 一条(description 与 notes 重写,params/response/errors/headers 未变,frontConfig 分组仍 8 条),未使用 deleteMethods、未整条覆盖其它条目;methods/changes/system.json 新增本条记录(插入数组首位);根版本 0.3.185 → 0.3.186,updatedAt 保持 2026-09-24",
|
||||
"未处理遗留(仍建议下一批单独修正):frontConfig.getInfo 的 response.domain 描述与 frontConfig.saveInfo 的 description 仍写「domain 只能通过 frontConfig.saveCert 变更」,实际已收敛到 frontConfig.setDomain;本条 spec.methods 只放 setDomain,避免整条覆盖造成语义漂移",
|
||||
"维护源口径冲突(仅记录,未处理):与上一轮一致,methods/*.json 的维护源是否为数据库表 wms_method_doc_meta 仍待用户决策;本次仍按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库"
|
||||
],
|
||||
"module": "frontConfig"
|
||||
},
|
||||
{
|
||||
"version": "2026.09.24-return-unpack-notify-by-source",
|
||||
"date": "2026-09-24",
|
||||
"type": "updated",
|
||||
"summary": "拆包完成通知改为按原查询登记来源定向回信:_notifyUnpacked 不再按货主泛推售后群,改为按 wms_return_query_log 登记时记录的 group_id+user_id 聚合回信原查询群/用户(有用户信息时 writeOutboundReply 定向回原查询用户,否则退化为来源群系统通知);登记无来源群的记录不通知;仅推送成功的登记标记 is_notified=1。",
|
||||
"methods": [
|
||||
"returnUnpack.submit"
|
||||
],
|
||||
"notes": [
|
||||
"代码位置:app/service/systems/return_unpack.js _notifyUnpacked(依赖此前新增的登记来源字段 group_id/group_name/user_id/user_name)",
|
||||
"回信链路与 video_record_request._replyResult 口径一致:批量反查 wms_inbox_group 补全 group_name/ext_data/store_id,缺失时用登记快照兜底;定向回信 source=ai_reply(wms_inbox_message 记录 user_id/user_name)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.24-return-query-log-source-ids",
|
||||
"date": "2026-09-24",
|
||||
"type": "updated",
|
||||
"summary": "退回查询登记表 wms_return_query_log 新增登记来源字段 group_id/group_name/user_id/user_name(迁移 20260924160000-add-source-ids-to-wms-return-query-log):站内信「查退回」触发登记时写入查询来源群/用户信息,用于登记追溯与后续定向通知;returnWaybill.create/list/detail 响应记录同步包含新字段(后台登记路径为 null)。",
|
||||
"methods": [
|
||||
"returnWaybill.create",
|
||||
"returnWaybill.list",
|
||||
"returnWaybill.detail"
|
||||
],
|
||||
"notes": [
|
||||
"代码位置:app/model/return_query_log.js 新增 4 字段;app/service/systems/return_unpack.js queryByWaybill 增加可选入参并在 received/not_returned 两处自动登记时写入来源;app/service/inbox/functions.js queryReturn 透传 ctx.inboxContext 的 group_id/group_name/user_id/user_name",
|
||||
"迁移执行:npx sequelize-cli db:migrate(生产:$env:NODE_ENV='production'; npx sequelize-cli db:migrate --migrations-path database/migrations --env production)",
|
||||
"库表化维护:method-doc-update.cjs 更新 3 个方法 response 说明并 --bump 至 0.3.184,method-doc-export.cjs 回写 methods/system.json"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.24-big-group-pack-coefficient-desc",
|
||||
"date": "2026-09-24",
|
||||
"type": "updated",
|
||||
"summary": "大团购打包系数字段描述统一:subject_config.big_group_pack_coefficient 描述更新为「大团购波次(wave_scope=1)打包中,扫描其他波次订单至少需等待「当前波次打包数 × 系数」秒,单位:秒/单,默认 3,必须大于 0」",
|
||||
"methods": [
|
||||
"setting.warehouse.getSettings"
|
||||
],
|
||||
"notes": [
|
||||
"字段元信息 app/service/systems/setting/warehouse.js(WAREHOUSE_SETTING_FIELDS)中 big_group_pack_coefficient 的 description 已与该口径一致,无代码变更"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.24-workbench-big-group-pack-member-divide",
|
||||
"date": "2026-09-24",
|
||||
"type": "updated",
|
||||
"summary": "大团购打包时长按人数分摊:workbench.packOrder 倒计时字段 pack_wait_seconds 与 workbench.queryOrder 闸门等待秒数改为「大团购打包系数 × 当前波次打包数 ÷ 当前工作台打包人数」;拉取当前打包任务时仅统计进行中任务(status<2,任务已结束则不计);人数为 0 时任务已被成员全部登出流程自动结束,不会出现,仍按 1 兜底防除零",
|
||||
"methods": [
|
||||
"workbench.packOrder",
|
||||
"workbench.queryOrder"
|
||||
],
|
||||
"notes": [
|
||||
"代码位置:app/service/systems/workbench.js(_packOrder 倒计时按 users 成员数分摊、_queryOrder 闸门按 _countCurrentPackMembers 统计 wms_workbench_member 人数分摊)",
|
||||
"回归测试:test/app/service/systems/workbench.bigGroupTimeGate.regression.test.js 新增人数分摊用例(打包 2 人 1×3/2=1.5 秒、闸门 3 人 10×3/3=10 秒),共 13 用例全绿"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.24-setting-big-group-pack-coefficient",
|
||||
"date": "2026-09-24",
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
{
|
||||
"module": "system",
|
||||
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
|
||||
"version": "0.3.181",
|
||||
"updatedAt": "2026-09-24",
|
||||
"version": "0.3.191",
|
||||
"updatedAt": "2026-09-26",
|
||||
"headers": [
|
||||
{
|
||||
"name": "platform",
|
||||
@ -2409,6 +2409,171 @@
|
||||
"message": "查询失败(数据库异常,message 为具体错误信息)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "index.uploadClientErrorLog",
|
||||
"description": "上报客户端错误日志(免登录、免权限、免鉴权,保留系统日志):设备端将运行时错误日志批量上报到服务端暂存表 wms_client_error_log。入参支持三种形态——单条对象、数组、{ logs: [...] },单次最多 50 条;字段命名兼容 snake_case 与 camelCase 别名。error_message 与 error_stack 至少一项有值(超长分别截断 5000 / 65535 字符),extra 超长截断 65535;report_uuid 幂等去重(重复上报静默成功,duplicated +1、不产生重复行;缺失时服务端生成 srv-{uuid} 且不保证幂等);client_time 仅参考(毫秒/秒时间戳或日期字符串,非法值存 null)。成功返回 flag=success、code=200 与 total/accepted/duplicated/rejected/rejected_reasons 统计;方法级错误按 /system 惯例为 HTTP 200 + flag=failure(code=400/500)。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": false,
|
||||
"headers": [],
|
||||
"params": [
|
||||
{
|
||||
"name": "client_type",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "客户端类型:android/ios/web 等;表宽 STRING(32),超出截断;兼容 camelCase 别名 clientType"
|
||||
},
|
||||
{
|
||||
"name": "app_version",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "客户端版本号;表宽 STRING(64),超出截断;别名 appVersion"
|
||||
},
|
||||
{
|
||||
"name": "device_id",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "设备唯一标识;表宽 STRING(128),超出截断;别名 deviceId"
|
||||
},
|
||||
{
|
||||
"name": "os_version",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "操作系统版本;表宽 STRING(64),超出截断;别名 osVersion"
|
||||
},
|
||||
{
|
||||
"name": "device_model",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "设备型号;表宽 STRING(128),超出截断;别名 deviceModel"
|
||||
},
|
||||
{
|
||||
"name": "error_type",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "错误类型/等级;表宽 STRING(64),超出截断;别名 errorType"
|
||||
},
|
||||
{
|
||||
"name": "error_message",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "错误信息;与 error_stack 至少一项有值,超长截断至 5000 字符;别名 errorMessage"
|
||||
},
|
||||
{
|
||||
"name": "error_stack",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "错误堆栈;与 error_message 至少一项有值,超长截断至 65535 字符;别名 errorStack"
|
||||
},
|
||||
{
|
||||
"name": "extra",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "附加上下文;字符串或对象(对象序列化为 JSON 字符串),超长截断至 65535 字符"
|
||||
},
|
||||
{
|
||||
"name": "report_uuid",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "客户端上报幂等ID(唯一索引 uk_report_uuid);表宽 STRING(64),超出截断;重复上报静默成功(duplicated +1,不产生重复行);缺失时服务端生成 srv-{uuid},此时不保证幂等;别名 reportUuid"
|
||||
},
|
||||
{
|
||||
"name": "client_time",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "客户端错误发生时间(仅参考,不作为记录时间):毫秒/秒时间戳或日期字符串,非法值存 null;别名 clientTime"
|
||||
},
|
||||
{
|
||||
"name": "logs",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "包裹形态 { logs: [...] } 的上报条目数组,单次最多 50 条;与「单条对象」「数组」三种形态三选一"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "flag",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "结果标记:success"
|
||||
},
|
||||
{
|
||||
"name": "code",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "业务码:200 成功;400 入参形状错误/空数据/超 50 条/全部条目无效;500 查询或写入失败(方法级错误仍为 HTTP 200)"
|
||||
},
|
||||
{
|
||||
"name": "message",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "提示文案:成功为「上报成功」"
|
||||
},
|
||||
{
|
||||
"name": "success",
|
||||
"type": "boolean",
|
||||
"required": true,
|
||||
"description": "服务处理结果标记:true 表示成功(400/500 失败响应无此字段)"
|
||||
},
|
||||
{
|
||||
"name": "total",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "本次上报条数"
|
||||
},
|
||||
{
|
||||
"name": "accepted",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "新入库条数"
|
||||
},
|
||||
{
|
||||
"name": "duplicated",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "幂等去重条数(report_uuid 已存在,静默成功、不产生重复行)"
|
||||
},
|
||||
{
|
||||
"name": "rejected",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "校验失败条数"
|
||||
},
|
||||
{
|
||||
"name": "rejected_reasons",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"description": "拒绝明细(最多返回 10 条),每条含 index(0 起条目下标)与 reason(原因文案)"
|
||||
},
|
||||
{
|
||||
"name": "timestamp",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "服务端响应时间戳(秒)"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": 400,
|
||||
"message": "入参形状错误(非对象/数组且无 logs 键)、缺少上报日志数据(空数组)、单次超过 50 条、全部条目无效(error_message 与 error_stack 均无值);HTTP 200 + flag=failure,body 仅含 flag/code/message/timestamp"
|
||||
},
|
||||
{
|
||||
"code": 500,
|
||||
"message": "查询已有 report_uuid 失败或批量写入失败(HTTP 200 + flag=failure,body 仅含 flag/code/message/timestamp)"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
@ -7727,6 +7892,12 @@
|
||||
"required": false,
|
||||
"description": "工作台ID(精确匹配)"
|
||||
},
|
||||
{
|
||||
"name": "operator_text",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "打包员(作业人员)筛选:目标列 wms_pack_task.operator_text(TEXT,多人姓名逗号拼接快照,如 '小吴哥,阿猫')。支持 {operator,value,type} 标准结构,value 支持字符串或字符串数组(多值取并集):operator=contains/like 与缺省(不传 operator)→ 模糊匹配 LIKE '%值%'(通配符 %/_ 已转义);operator=eq/in → 精确匹配(单值等值、多值 IN);operator=ne → 不等于(多值取首值);operator=notlike → 不包含 NOT LIKE '%值%'(多值逐个 AND 排除);值为 ''/null/空数组时忽略该条件(不过滤)"
|
||||
},
|
||||
{
|
||||
"name": "quickWhere",
|
||||
"type": "string",
|
||||
@ -7806,7 +7977,7 @@
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "查询条件,语义与 order.packing.list 的 where 一致(支持 {operator,value,type} 标准结构或直接值;字段含 status/pack_mode/waybill_code/wave_no/order_id/workbench_id/quickWhere/has_video/video_enable/start_time/end_time/create_time 等);禁止传入 warehouse_id/warehouseId(服务端注入)"
|
||||
"description": "查询条件,语义与 order.packing.list 的 where 一致(支持 {operator,value,type} 标准结构或直接值;字段含 status/pack_mode/waybill_code/wave_no/order_id/workbench_id/operator_text/quickWhere/has_video/video_enable/start_time/end_time/create_time 等);禁止传入 warehouse_id/warehouseId(服务端注入)"
|
||||
},
|
||||
{
|
||||
"name": "sort",
|
||||
@ -15131,7 +15302,7 @@
|
||||
"name": "subject_config.big_group_pack_coefficient",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"description": "大团购打包系数(数字,默认 3,单位秒/单,必须大于 0;workbench.packOrder 大团购波次倒计时等待秒数 = 当前波次打包数 × 该系数)"
|
||||
"description": "大团购波次(wave_scope=1)打包中,扫描其他波次订单至少需等待「当前波次打包数 × 系数」秒,单位:秒/单,默认 3,必须大于 0"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.return_unpack_max_record_minutes",
|
||||
@ -35401,7 +35572,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;打包任务落库 wave_scope(波次范围:0=未分配 1=大团购 2=散单 3=小团购 4=单品单件,服务端复查:上报值非法/缺省时兜底订单行值);大团购波次(wave_scope=1)响应附倒计时字段 pack_wait_seconds(当前波次打包数 × 仓库配置大团购打包系数,单位秒)与 pack_start_time(开始打包时间,毫秒时间戳)供前端倒计时,其他波次两字段均为 0",
|
||||
"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(大团购打包系数 × 当前波次打包数 ÷ 当前工作台打包人数,单位秒;人数为 0 时任务已被成员全部登出流程自动结束,不会出现,仍按 1 兜底防除零)与 pack_start_time(开始打包时间,毫秒时间戳)供前端倒计时,其他波次两字段均为 0",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": false,
|
||||
"isNeedRight": false,
|
||||
@ -35469,7 +35640,7 @@
|
||||
"name": "pack_wait_seconds",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "大团购倒计时等待秒数(当前波次打包数 × 仓库配置大团购打包系数 big_group_pack_coefficient;仅 wave_scope=1 返回实际值,其他波次为 0)"
|
||||
"description": "大团购倒计时等待秒数(大团购打包系数 big_group_pack_coefficient × 当前波次打包数 ÷ 当前工作台打包人数;仅 wave_scope=1 返回实际值,其他波次为 0)"
|
||||
},
|
||||
{
|
||||
"name": "pack_start_time",
|
||||
@ -35727,7 +35898,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 打包;order 附 wave_scope(波次范围:0=未分配波次 1=大团购 2=散单 3=小团购 4=单品单件);大团购打包时长闸门:当前工作台存在进行中的 wave_scope=1 打包任务时,未到「当前波次打包数 × 仓库配置大团购打包系数」秒仅允许查询本波次订单,其他波次订单返回错误「打包时长不足」,已到时不受限制",
|
||||
"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 打包任务(status<2,任务已结束则不计)并判断是否已到「大团购打包系数 × 当前波次打包数 ÷ 当前工作台打包人数」秒:未到时仅允许查询本波次订单,其他波次订单返回错误「打包时长不足」,已到时不受限制",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": false,
|
||||
"isNeedRight": false,
|
||||
@ -44690,7 +44861,7 @@
|
||||
},
|
||||
{
|
||||
"method": "returnUnpack.submit",
|
||||
"description": "提交确认:未完成(unpacking)拆包单转 completed 终态并回写 end_time(拆包结束时间;结束时间超过仓库配置的拆包最大录制时长上限时,自动截断为 开始时间+上限——仓库配置项 subject_config.return_unpack_max_record_minutes,默认 5 分钟,配置缺失/非法或开始时间缺失时不约束);同步按 warehouse_id+waybill_code 更新 wms_return_query_log.is_back=1(标记该运单号已退回,更新失败不阻断主流程)。提交后进入终态,不可再录/移除明细。仓库隔离校验(仅本仓库拆包单)。",
|
||||
"description": "提交确认:未完成(unpacking)拆包单转 completed 终态并回写 end_time(拆包结束时间;结束时间超过仓库配置的拆包最大录制时长上限时,自动截断为 开始时间+上限——仓库配置项 subject_config.return_unpack_max_record_minutes,默认 5 分钟,配置缺失/非法或开始时间缺失时不约束);同步按 warehouse_id+waybill_code 更新 wms_return_query_log.is_back=1(标记该运单号已退回,更新失败不阻断主流程)。提交后进入终态,不可再录/移除明细。仓库隔离校验(仅本仓库拆包单)。拆包完成后按退回查询登记来源定向通知:仅登记表 is_back=1 且 is_notified=0 的记录,按登记时记录的 group_id+user_id 回信原查询群/用户(有用户信息时定向回原查询用户,否则退化为来源群系统通知;登记无来源群的记录不通知),不再泛推货主售后群;推送成功标记 is_notified=1。",
|
||||
"isNeedAuth": true,
|
||||
"isNeedLogin": true,
|
||||
"headers": [],
|
||||
@ -44901,6 +45072,13 @@
|
||||
"source": "body.where",
|
||||
"description": "拆包人员工号ID(等值)"
|
||||
},
|
||||
{
|
||||
"name": "where.unpacker_name",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body.where",
|
||||
"description": "拆包人筛选:目标列 wms_return_unpack.unpacker_name(STRING(50),拆包人员工号名称快照)。传 {operator:'like',value} 或直接值 → 模糊 LIKE '%值%';value 为数组时多值 LIKE 取并集(trim/去空归一后为空退化为全匹配、不过滤);也支持 eq/ne/in/notin/between 等既有操作符"
|
||||
},
|
||||
{
|
||||
"name": "where.return_received_id",
|
||||
"type": "number",
|
||||
@ -45193,7 +45371,7 @@
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "查询条件,语义与 returnUnpack.list 的 where 一致(支持 {operator,value,type} 标准结构或直接值;字段含 unpack_no/waybill_code 模糊、unpack_date/start_time/end_time/created_at/updated_at 范围、status/detail_status/store_id/order_express_id/order_id/unpacker_id/return_received_id 等值、has_video/video_enable 等);禁止传入 warehouse_id/warehouseId(服务端注入);不传 status 时不过滤状态"
|
||||
"description": "查询条件,语义与 returnUnpack.list 的 where 一致(支持 {operator,value,type} 标准结构或直接值;字段含 unpack_no/waybill_code/unpacker_name 模糊、unpack_date/start_time/end_time/created_at/updated_at 范围、status/detail_status/store_id/order_express_id/order_id/unpacker_id/return_received_id 等值、has_video/video_enable 等);禁止传入 warehouse_id/warehouseId(服务端注入);不传 status 时不过滤状态"
|
||||
},
|
||||
{
|
||||
"name": "sort",
|
||||
@ -45498,7 +45676,7 @@
|
||||
"name": "record",
|
||||
"type": "object",
|
||||
"required": true,
|
||||
"description": "登记记录包装对象,含登记记录完整字段(id、warehouse_id、store_id、waybill_code、remark、is_notified、is_back、created_at、updated_at,时间字段为格式化字符串)"
|
||||
"description": "登记记录包装对象,含登记记录完整字段(id、warehouse_id、store_id、waybill_code、group_id、group_name、user_id、user_name、remark、is_notified、is_back、created_at、updated_at,时间字段为格式化字符串;group_id/group_name/user_id/user_name 为登记来源,仅站内信「查退回」触发登记时写入,后台登记为 null)"
|
||||
},
|
||||
{
|
||||
"name": "duplicated",
|
||||
@ -45694,7 +45872,7 @@
|
||||
"name": "list",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "运单退回登记列表,每条含登记字段(id、warehouse_id、store_id、waybill_code、remark、is_notified、is_back)及格式化时间字段"
|
||||
"description": "运单退回登记列表,每条含登记字段(id、warehouse_id、store_id、waybill_code、group_id、group_name、user_id、user_name、remark、is_notified、is_back)及格式化时间字段;group_id/group_name/user_id/user_name 为登记来源(站内信「查退回」触发时写入,后台登记为 null)"
|
||||
},
|
||||
{
|
||||
"name": "pagination",
|
||||
@ -45738,7 +45916,7 @@
|
||||
"name": "record",
|
||||
"type": "object",
|
||||
"required": true,
|
||||
"description": "登记记录完整信息(id、warehouse_id、store_id、waybill_code、remark、is_notified、is_back 及格式化时间字段)"
|
||||
"description": "登记记录完整信息(id、warehouse_id、store_id、waybill_code、group_id、group_name、user_id、user_name、remark、is_notified、is_back 及格式化时间字段;来源字段仅站内信「查退回」触发登记时写入,后台登记为 null)"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
@ -47326,7 +47504,7 @@
|
||||
"list": [
|
||||
{
|
||||
"method": "frontConfig.getByDomain",
|
||||
"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 异常降级查库。",
|
||||
"description": "按域名拉取仓库前端公开配置(公共无鉴权接口:免登录、免鉴权、免权限,保留系统日志)。放行闸门仍只认「生效域名」:查库条件为 domain + domain_status=1,未验证(0)/验证失败(2)的域名一律按未配置返回 404「域名未配置」(本次实现未变,仅补充两阶段语义说明);迁移尚未执行(domain_status 列不存在)时降级为仅按 domain 查询并 WARN 一次,保持迁移前行为。两阶段域名切换语义:切换验证期间生效域名仍为旧域名,本接口继续对旧域名正常放行、对新登记的待验证域名按未配置返回 404 —— 因此不会出现「改域名瞬间旧域名公共接口 404、页面能打开但拉不到配置」的中间态;只有 TXT 校验通过、待验证域名被提升为生效域名后,才改为对新域名放行、旧域名返回 404(旧域名 nginx 配置随后由外部脚本按 retired_domain 删除彻底下线)。响应仅含公开字段 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": [],
|
||||
@ -47394,6 +47572,16 @@
|
||||
"code": "500",
|
||||
"message": "WarehouseFrontConfig model 不可用/获取前端配置失败"
|
||||
}
|
||||
],
|
||||
"notes": [
|
||||
"代码位置:出口 app/service/systemMethods/frontConfig.js 的 getByDomain,实现 app/service/systems/frontConfig.js 的 getByDomain(查库走 findVerifiedDomainRecord,缓存走 getDomainCacheKey / clearDomainCaches)",
|
||||
"放行闸门(本轮未改实现,仅补语义说明):查库条件仍为 domain + domain_status=1,只看生效域名 domain,不看 pending_domain",
|
||||
"两阶段切换语义:切换验证期间旧域名(生效域名)继续放行、新域名(待验证域名)返回 404「域名未配置」;提升完成后新域名放行、旧域名 404,旧域名 nginx 配置由外部脚本按 retired_domain 删除后彻底下线 —— 因此不会出现「改域名瞬间旧域名公共接口 404」的中间态",
|
||||
"缓存:域名切换/提升写库成功后由 clearDomainCaches 清理「旧域名 + 新域名」两个 key(front:config:domain:{domain}),先写库后清缓存;Redis 异常降级查库",
|
||||
"安全红线不变:只返回 domain/title/logo_url/login_bg_url/favicon_url/theme 公开字段,绝不返回证书/私钥与证书路径、同步状态等内部字段",
|
||||
"迁移兼容提示:domain_status 列不存在(迁移未执行)时降级为仅按 domain 查询并 WARN 一次;但两阶段版本代码要求 pending_* / retired_* 共 8 列已存在,生产必须先执行迁移 20260924180000-add-pending-domain-to-wms-warehouse-front-config 再发布代码,否则本接口的 Sequelize 全字段查询会报 ER_BAD_FIELD_ERROR",
|
||||
"文档变更范围:本次仅更新本条的 description + notes(params / response / errors / headers 均未变动,response 仍为 6 个公开字段);frontConfig 分组仍 8 条;methods/changes/system.json 新增 1 条变更记录;根版本 0.3.188 → 0.3.189(updatedAt 保持 2026-09-24)",
|
||||
"维护源口径冲突(仅记录,未处理):methods/*.json 的维护源是否为数据库表 wms_method_doc_meta 仍待用户决策;本次仍按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库(红线要求)"
|
||||
]
|
||||
},
|
||||
{
|
||||
@ -47421,7 +47609,7 @@
|
||||
"name": "domain",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "仓库自持域名(未配置为空字符串;只能通过 frontConfig.saveCert 变更)"
|
||||
"description": "仓库自持域名(未配置为空字符串;变更统一走 frontConfig.setDomain)"
|
||||
},
|
||||
{
|
||||
"name": "title",
|
||||
@ -47593,12 +47781,15 @@
|
||||
"响应契约变更(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 部署后回填)"
|
||||
"本接口不返回 cert_path/key_path(保存时已置 null,等待外部 crontab 脚本 script/warehouse-cert-sync.cjs 部署后回填)",
|
||||
"两阶段切换提示(本轮,实现与响应字段均未变):域名提升时会清空证书并重置同步状态,提升后本接口回显的证书字段为空、can_set_cert 仍按生效域名判定(domain 非空且 domain_status=1),用户需重新上传证书;切换中的待验证域名 pending_domain 不参与 can_set_cert 判定",
|
||||
"文档变更范围:本次仅追加本条的 notes(description / params / response / errors / headers 均未变动,response 仍为 13 字段);frontConfig 分组仍 8 条;methods/changes/system.json 新增 1 条变更记录;根版本 0.3.188 → 0.3.189(updatedAt 保持 2026-09-24)",
|
||||
"维护源口径冲突(仅记录,未处理):methods/*.json 的维护源是否为数据库表 wms_method_doc_meta 仍待用户决策;本次仍按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库(红线要求)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"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 字段,不含证书/私钥)。",
|
||||
"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.setDomain(域名验证通过后方可上传证书)。保存即视为一次配置变更:同步状态重置为待同步(sync_status=0、sync_attempts=0、清空 last_sync_error/last_synced_at);写库成功后清理当前 domain 的公共拉取缓存(先写库后清缓存,清缓存失败仅记日志不影响保存结果)。响应为保存后的品牌信息(8 字段,不含证书/私钥)。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
@ -47734,7 +47925,7 @@
|
||||
},
|
||||
{
|
||||
"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 路径字段。",
|
||||
"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 路径字段。注意:域名提升(两阶段切换的第二阶段)会清空证书 5 列并重置同步状态,域名切换完成后必须重新上传证书;切换期间上传的证书属于旧域名,提升后即失效。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
@ -47885,12 +48076,16 @@
|
||||
"前置闸门:无域名 → 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)"
|
||||
"写库内容: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)",
|
||||
"两阶段切换补充(本轮):域名提升时会清空证书(cert_pem / cert_key / cert_path / key_path / cert_expire_at 置 NULL)并重置同步状态(sync_status=0、sync_attempts=0、清空 last_sync_error / last_synced_at),因此域名切换完成后必须重新上传证书;切换期间上传的证书属于旧域名,提升后即失效",
|
||||
"前置闸门口径(本轮,实现未变):仍按生效域名 domain 判定(无域名 → 400「请先设置并验证域名」,domain_status !== 1 → 400「域名未通过验证,暂时无法上传证书」);切换中的待验证域名 pending_domain 不参与本闸门",
|
||||
"文档变更范围:本次更新本条的 description + notes 各一处(params / response / errors / headers 均未变动,response 仍为 13 字段);frontConfig 分组仍 8 条;methods/changes/system.json 新增 1 条变更记录;根版本 0.3.188 → 0.3.189(updatedAt 保持 2026-09-24)",
|
||||
"维护源口径冲突(仅记录,未处理):methods/*.json 的维护源是否为数据库表 wms_method_doc_meta 仍待用户决策;本次仍按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库(红线要求)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "frontConfig.setDomain",
|
||||
"description": "设置或变更当前仓库前端独立部署域名,并发起 DNS TXT 归属验证(需登录、免权限、免鉴权,权限由业务层按 isWarehouse 判定,仅仓库主体可调用)。流程:仓库主体校验 → domain 必填/长度(≤100 字符)/形态校验(统一转小写存储)→ 跨仓库唯一校验 → 生成一次性校验子域 verify_host(wmsv-<10 位 hex>.<domain>)与校验值 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 返回空字符串。",
|
||||
"description": "设置或变更当前仓库前端独立部署域名(需登录、免权限、免鉴权,权限由业务层按 isWarehouse 判定,仅仓库主体可调用)。语义已改为两阶段切换:本接口只登记「待验证域名」pending_domain 并下发一次性 DNS TXT 校验记录,不直接改动生效域名 domain;TXT 校验通过后(frontConfig.checkDomain 手动触发或 app/schedule/domain_verify_scan.js 定时扫描)再由提升逻辑一次性把 pending_domain 提升为生效域名。这样生效域名全程不变:切换期间旧域名的前端页面与 frontConfig.getByDomain 公共拉取都仍然可用,不会出现「改域名瞬间旧域名公共接口 404」的中间态。分支(域名比较一律忽略大小写):A 入参 == 生效域名 domain 且无 pending_domain → 幂等短路:不写库,仅当库内字面值与归一化结果不一致时把 domain 改写为小写并清理新旧两个字面值的缓存 key;B 入参 == 生效域名 domain 且有 pending_domain → 取消待切换:只清空 pending 6 列,生效域名、证书 5 列、同步 4 列与公共缓存一律不动;C 入参 == 现有 pending_domain → 校验码齐全则幂等短路(不重发、不写库),校验码缺失(脏数据)则只补发 pending 校验码并清 pending_verify_attempts/pending_last_error;D 其它(新的待切换域名,含首次设置)→ 查重(其他仓库的 domain 或 pending_domain 命中任一即 409)通过后生成新校验码只写入 pending 组,生效域名 domain / domain_status / domain_verified_at / domain_verify_* / 证书 5 列 / 同步 4 列一律不动,也不清理任何公共缓存(新域名尚未生效)。域名与校验码口径:domain 必填、trim 后非空、≤100 字符,形态校验通过后统一转小写存储;pending_verify_host 为一次性校验子域 wmsv-<10 位 hex>.<待验证域名>,pending_verify_value 为 32 位 hex。格式:至少两段标签、每段 1~63 位且仅字母数字与连字符、首尾不得为连字符(天然排除通配符 *、下划线、首尾点与单段主机名),不合法返回 400「domain 格式不正确」;空值返回 400「domain 不能为空」;超长返回 400「domain 长度不能超过 100 字符」;域名(或待验证域名)被其他仓库占用返回 409「域名 X 已被其他仓库使用」。响应口径与 frontConfig.getDomain 一致(16 字段);生效域名组 domain_status=1 时 verify_host/verify_value 返回空字符串,待验证域名组 pending_domain 非空时 pending_verify_host/pending_verify_value 始终回显。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
@ -47964,6 +48159,48 @@
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "最近一次验证失败原因(脱敏截断 ≤500 字符;未失败为空字符串)"
|
||||
},
|
||||
{
|
||||
"name": "pending_domain",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "待验证域名(切换中非空;未发起切换为空字符串)。frontConfig.setDomain 只登记到本字段,DNS TXT 校验通过后才被提升为生效域名 domain;本字段不参与 frontConfig.getByDomain 放行"
|
||||
},
|
||||
{
|
||||
"name": "pending_verify_host",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "待验证域名的 TXT 记录主机名(wmsv-<10 位 hex>.<pending_domain>;pending_domain 为空时返回空字符串)。该域名尚未生效,校验码始终回显,用户据此配置 TXT 记录"
|
||||
},
|
||||
{
|
||||
"name": "pending_verify_value",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "待验证域名的 TXT 记录值(32 位 hex,读 pending_verify_token 列;pending_domain 为空时返回空字符串)"
|
||||
},
|
||||
{
|
||||
"name": "pending_attempts",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "待验证域名校验尝试次数(setDomain 登记/补码时清零;checkDomain 与定时任务校验失败时 +1)"
|
||||
},
|
||||
{
|
||||
"name": "pending_last_error",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "待验证域名最近一次校验失败原因(脱敏截断 ≤500 字符;未失败或无待验证域名为空字符串)"
|
||||
},
|
||||
{
|
||||
"name": "pending_created_at",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "发起本次域名切换的时间(无待验证域名为 null)"
|
||||
},
|
||||
{
|
||||
"name": "pending_active",
|
||||
"type": "boolean",
|
||||
"required": true,
|
||||
"description": "是否处于域名切换中(boolean,等价于 pending_domain 非空;true=待验证域名已登记、等待 TXT 校验)"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
@ -48001,18 +48238,27 @@
|
||||
}
|
||||
],
|
||||
"notes": [
|
||||
"代码位置:出口 app/service/systemMethods/frontConfig.js 的 setDomain,实现 app/service/systems/frontConfig.js 的 setDomain(校验码由 buildDomainVerifyCode 生成,输出由 buildDomainOutput 构建)",
|
||||
"代码位置:出口 app/service/systemMethods/frontConfig.js 的 setDomain,实现 app/service/systems/frontConfig.js 的 setDomain(校验码由 buildDomainVerifyCode 生成,取消待切换的字段由 buildPendingClearPatch 生成,输出由 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 入参,前端若仍传会被忽略)"
|
||||
"变更原因(本轮核心语义变更):旧口径是「设置即生效」——一次 setDomain 即把 domain 改写为新域名、domain_status 归零并清空证书,导致旧域名立刻被 frontConfig.getByDomain 判为「域名未配置」返回 404,而 nginx 侧旧域名 server 块仍在,出现「页面能打开但拉不到配置」的中间态;用户改错域名也无法回滚。本轮改为两阶段(待验证域名与生效域名分离),本接口只登记待验证域名",
|
||||
"四分支决策表(域名比较一律忽略大小写):A 入参 == 生效域名 domain 且无 pending_domain → 幂等短路(不写库;仅当库内字面值与归一化结果不一致时把 domain 改写为小写,并清理新旧两个字面值的缓存 key);B 入参 == 生效域名 domain 且有 pending_domain → 取消待切换(只清空 pending 6 列);C 入参 == 现有 pending_domain → 校验码齐全则幂等短路(不重发、不写库),校验码缺失(脏数据)则只补发 pending 校验码并清 pending_verify_attempts / pending_last_error;D 其它(新的待切换域名,含首次设置)→ 查重通过后只写 pending_domain + 新校验码(pending_verify_host / pending_verify_token / pending_verify_attempts=0 / pending_last_error=NULL / pending_created_at=now)",
|
||||
"分支 B「取消待切换」的边界:只清 pending 6 列,生效域名 domain / domain_status / domain_verified_at / domain_verify_* / 证书 5 列 / 同步 4 列一律不动;待验证域名从未生效(不参与 getByDomain),因此无需清理公共缓存",
|
||||
"分支 D「只登记不动」清单:domain / domain_status / domain_verified_at / domain_verify_host / domain_verify_token / domain_verify_attempts / domain_last_error / 证书 5 列(cert_pem / cert_key / cert_path / key_path / cert_expire_at)/ 同步 4 列(sync_status / sync_attempts / last_sync_error / last_synced_at)一律不动,也不清理任何公共缓存(新域名尚未生效,getByDomain 结果不受影响)。首次设置时新行只带 store_id 与 pending 组,domain 保持 NULL(尚未生效),domain_status 默认 0,外部证书脚本只处理 domain_status=1 的行、不会误处理该行",
|
||||
"查重扩展(assertDomainUnique):由「其他仓库的 domain 命中」扩展为「其他仓库的 domain 或 pending_domain 命中」即 409「域名 X 已被其他仓库使用」;分支 A/B/C 不查重(域名已是本仓自身持有,全局唯一性由分支 D 查重与数据库唯一索引兜底);并发写入捕获 SequelizeUniqueConstraintError 的 domain 字段冲突同样转 409,其余冲突转 409「仓库前端配置保存冲突,请稍后重试」",
|
||||
"缓存口径:只有分支 A 的「大小写规范化」需要清缓存 —— 公共拉取缓存键按域名字面值精确匹配(front:config:domain:Shop.com 与 front:config:domain:shop.com 是两个 key),新旧两个字面值都必须清;B/C/D 不清缓存(B 清的是从未生效的待验证域名,C/D 未改变生效域名)",
|
||||
"响应契约变更(本轮 9 → 16 字段,纯追加):追加待验证域名组 pending_domain / pending_verify_host / pending_verify_value / pending_attempts / pending_last_error / pending_created_at / pending_active;生效域名组 9 字段名与语义不变;domain_status=1 时生效组的 verify_host/verify_value 仍为空字符串,待验证组在 pending_domain 非空时始终回显校验码",
|
||||
"前端改造要点:提交后 TXT 指引改读 pending_verify_host / pending_verify_value;「取消待切换」= 用当前生效域名再调一次本接口(走分支 B);「切换中」用 pending_active / pending_attempts / pending_last_error / pending_created_at 展示;提升后需提示「切换完成,请重新上传证书」,并明确「切换期间上传的证书属于旧域名」",
|
||||
"旧口径说明(历史事实,不回改):既有变更记录中「同一域名重复设置幂等短路、缺码补发」「未验证/验证失败则重发新校验码并清零 attempts」等描述属当时真实口径,由本条新记录承接覆盖;原「C 缺码补发·已验证」分支已不存在,五分支收敛为四分支 A/B/C/D",
|
||||
"后续链路:用户按 pending_verify_host / pending_verify_value 配置 TXT 记录后,由 frontConfig.checkDomain 手动触发或 app/schedule/domain_verify_scan.js 定时任务(默认 10m)校验;通过后提升为生效域名(domain_status=1、清空证书 5 列、重置同步 4 列、旧域名写入 retired_domain + retired_at、清空 pending 6 列),此后 frontConfig.saveCert 才可重新上传证书、frontConfig.getByDomain 才对新域名放行",
|
||||
"行为影响提示:本接口不再提供「更换校验码」能力(同域名重复提交走 A/B/C 分支),需要新校验码只能提交一个不同的待验证域名(走分支 D);若已登记的待验证域名一直不配置 TXT 记录,则永久停留在切换中状态、生效域名不受影响",
|
||||
"本条 setDomain 的 params / errors / headers 未变动(查重扩展后 409 文案「域名 {domain} 已被其他仓库使用」沿用原文案,语义已覆盖 domain 与 pending_domain 两种占用)",
|
||||
"文档变更范围:methods/system.json 更新 frontConfig.setDomain / frontConfig.getDomain / frontConfig.checkDomain / frontConfig.getByDomain / frontConfig.saveCert / frontConfig.getCert 共 6 条(description + notes;其中 setDomain / getDomain / checkDomain 的 response 同步追加待验证域名组 7 字段,checkDomain 另补 409 错误码);frontConfig 分组仍 8 条、其余方法未动;methods/changes/system.json 新增 1 条变更记录;根版本 0.3.188 → 0.3.189(updatedAt 保持 2026-09-24)",
|
||||
"维护源口径冲突(仅记录,未处理):methods/*.json 的维护源是否为数据库表 wms_method_doc_meta 仍待用户决策;本次仍按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库(红线要求)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"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。",
|
||||
"description": "查询当前仓库前端独立部署域名与验证状态(settings 页回显;需登录、免权限、免鉴权,仅仓库主体可调用)。响应 16 字段,分两组:①生效域名组 9 字段 —— warehouse_id/domain/domain_status/verify_host/verify_value/cname/verified_at/attempts/last_error(字段名、类型与语义一字未改);②待验证域名组 7 字段(两阶段域名切换新增、纯追加)—— pending_domain/pending_verify_host/pending_verify_value/pending_attempts/pending_last_error/pending_created_at/pending_active。两阶段语义:domain 始终是「生效域名」,切换期间(pending_active=true)仍为旧域名并继续对外正常服务,只有 TXT 校验通过被提升后才换成新域名;pending_domain 是用户提交、等待 TXT 校验的「待验证域名」,从未生效、不参与 frontConfig.getByDomain 放行。domain_status 语义:0 未验证 / 1 已验证 / 2 验证失败。安全口径:domain_status=1(已验证)时 verify_host/verify_value 返回空字符串(校验令牌已无用途,不再回显);未验证(0/2)时回显生效域名应配置的 TXT 主机名与记录值;待验证域名组不受该限制 —— pending_domain 非空时 pending_verify_host/pending_verify_value 始终回显(该域名尚未生效,用户必须据此配置 TXT 记录);pending_active 等价于 pending_domain 非空。cname 取配置 config.frontConfig.cname,未验证时提示把域名 CNAME 指向该目标。仓库未设置过域名时返回默认空值(warehouse_id 取当前仓库、domain 与 pending_domain 为空字符串、domain_status=0、pending_active=false、时间字段为 null、其余字符串字段为空字符串),不返回 404。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
@ -48078,6 +48324,48 @@
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "最近一次验证失败原因(脱敏截断 ≤500 字符;未失败为空字符串)"
|
||||
},
|
||||
{
|
||||
"name": "pending_domain",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "待验证域名(切换中非空;未发起切换为空字符串)。frontConfig.setDomain 只登记到本字段,DNS TXT 校验通过后才被提升为生效域名 domain;本字段不参与 frontConfig.getByDomain 放行"
|
||||
},
|
||||
{
|
||||
"name": "pending_verify_host",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "待验证域名的 TXT 记录主机名(wmsv-<10 位 hex>.<pending_domain>;pending_domain 为空时返回空字符串)。该域名尚未生效,校验码始终回显,用户据此配置 TXT 记录"
|
||||
},
|
||||
{
|
||||
"name": "pending_verify_value",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "待验证域名的 TXT 记录值(32 位 hex,读 pending_verify_token 列;pending_domain 为空时返回空字符串)"
|
||||
},
|
||||
{
|
||||
"name": "pending_attempts",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "待验证域名校验尝试次数(setDomain 登记/补码时清零;checkDomain 与定时任务校验失败时 +1)"
|
||||
},
|
||||
{
|
||||
"name": "pending_last_error",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "待验证域名最近一次校验失败原因(脱敏截断 ≤500 字符;未失败或无待验证域名为空字符串)"
|
||||
},
|
||||
{
|
||||
"name": "pending_created_at",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "发起本次域名切换的时间(无待验证域名为 null)"
|
||||
},
|
||||
{
|
||||
"name": "pending_active",
|
||||
"type": "boolean",
|
||||
"required": true,
|
||||
"description": "是否处于域名切换中(boolean,等价于 pending_domain 非空;true=待验证域名已登记、等待 TXT 校验)"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
@ -48095,15 +48383,25 @@
|
||||
}
|
||||
],
|
||||
"notes": [
|
||||
"代码位置:出口 app/service/systemMethods/frontConfig.js 的 getDomain,实现 app/service/systems/frontConfig.js 的 getDomain(buildDomainOutput)",
|
||||
"代码位置:出口 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(校验后回显)复用,字段含义一致"
|
||||
"cname 取自配置 config.frontConfig.cname(默认空字符串,非数据库字段),未设置域名时也会返回",
|
||||
"同一输出口径被 setDomain(登记后回显)与 checkDomain(校验后回显)复用,字段含义完全一致",
|
||||
"响应契约变更(本轮 9 → 16 字段,纯追加):在原有 9 字段之后依次追加 pending_domain / pending_verify_host / pending_verify_value / pending_attempts / pending_last_error / pending_created_at / pending_active。旧字段名、类型与语义一字未改,属向后兼容追加,前端可先发版兼容后再启用两阶段 UI",
|
||||
"字段来源:生效域名组读 domain / domain_status / domain_verify_host / domain_verify_token / domain_verified_at / domain_verify_attempts / domain_last_error;待验证域名组读 pending_domain / pending_verify_host / pending_verify_token / pending_verify_attempts / pending_last_error / pending_created_at,pending_active 由 pending_domain 非空推导",
|
||||
"两阶段语义:domain 是「生效域名」——切换期间(pending_active=true)仍为旧域名并继续对外正常服务;pending_domain 是等待 TXT 校验的「待验证域名」,从未生效",
|
||||
"回显口径差异(重要):生效域名的 verify_host/verify_value 在 domain_status=1 时返回空字符串;待验证域名不受此限制 —— pending_domain 非空时 pending_verify_host/pending_verify_value 始终回显,因为该域名尚未生效、用户必须据此配置 TXT 记录",
|
||||
"与 frontConfig.getByDomain 的关系:getByDomain 仍只看生效 domain 且要求 domain_status=1,因此切换验证期间旧域名继续正常服务(不会出现「改域名瞬间旧域名公共接口 404」),只有提升后新域名才放行、旧域名才 404,最终由外部脚本按 retired_domain 删除旧域名 nginx 配置后彻底下线",
|
||||
"前端改造要点:TXT 指引必须改读 pending_verify_host/pending_verify_value(不能再读 verify_host/verify_value);首次设置时 domain 为空字符串属正常态(待验证域名在 pending_domain);「切换中」状态用 pending_active/pending_attempts/pending_last_error/pending_created_at 展示;「切换完成」后提示重新上传证书",
|
||||
"发布顺序强约束:本实现走 Sequelize 全字段 SELECT,若生产库尚未执行迁移(新增 pending_* / retired_* 共 8 列不存在),setDomain / getDomain / checkDomain 乃至 getByDomain 都会报 ER_BAD_FIELD_ERROR → 必须先执行迁移、再发布代码;迁移为纯追加且可空,先跑无风险",
|
||||
"仓库未设置过域名时返回默认空值:warehouse_id 取当前仓库、domain 与 pending_domain 为空字符串、domain_status=0、pending_active=false、时间字段为 null、其余字符串字段为空字符串,不返回 404",
|
||||
"文档变更范围:methods/system.json 更新 frontConfig.setDomain / frontConfig.getDomain / frontConfig.checkDomain / frontConfig.getByDomain / frontConfig.saveCert / frontConfig.getCert 共 6 条(description + notes;其中 setDomain / getDomain / checkDomain 的 response 同步追加待验证域名组 7 字段,checkDomain 另补 409 错误码);frontConfig 分组仍 8 条、其余方法未动;methods/changes/system.json 新增 1 条变更记录;根版本 0.3.188 → 0.3.189(updatedAt 保持 2026-09-24)",
|
||||
"维护源口径冲突(仅记录,未处理):methods/*.json 的维护源是否为数据库表 wms_method_doc_meta 仍待用户决策;本次仍按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库(红线要求)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"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 字符,排障用)。",
|
||||
"description": "主动校验域名 TXT 归属记录并回写库(需登录、免权限、免鉴权,仅仓库主体可调用)。两阶段切换后本接口承担两条路径:①存在 pending_domain(切换中)→ 校验待验证域名:以 pending_verify_host 为解析目标、比对 pending_verify_token;通过则由提升逻辑把 pending_domain 提升为生效域名 domain(domain_status=1、domain_verified_at=now、domain_verify_* 由 pending_* 平移、domain_last_error 清空、清空 pending 6 列、旧域名写入 retired_domain/retired_at 下线队列、清空证书 5 列、重置同步 4 列),并清理旧域名与新域名两个公共拉取缓存,返回 verified=true;不通过只把 pending_verify_attempts+1 并写 pending_last_error,生效域名、domain_status、domain_verified_at 与证书一律不动,返回 verified=false。②无 pending_domain → 保持升级前口径:生效域名 domain_status=1 一律短路返回 verified=true、resolved_values=[],不写库、不改状态、不增加验证次数;domain 为空 → 400「请先设置域名」;domain 非空但未验证/验证失败(升级前登记的历史行)→ 用生效域名的 domain_verify_* 校验并回写 domain_status/domain_verify_attempts/domain_last_error(兼容路径,缺码则自动补发一次)。解析路径为 DoH 多端点顺序尝试(config.frontConfig.domainVerify.dohUrls,默认 https://dns.alidns.com/resolve → https://223.5.5.5/resolve → https://doh.pub/dns-query;单端点键 dohUrl 保留兼容),单端点「无记录」不再直接定论,全部端点未取到值后降级系统 DNS;仅「所有 DoH 端点都解析失败且系统 DNS 也失败」才报「DNS 解析失败:…」。失败原因经脱敏截断(≤500 字符)落库与回显。响应 = frontConfig.getDomain 的 16 字段 + verified(本次是否通过,boolean)+ resolved_values(本次解析到的 TXT 值,最多 5 条、单条截断 255 字符,排障用)。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
@ -48170,6 +48468,48 @@
|
||||
"required": true,
|
||||
"description": "最近一次验证失败原因(脱敏截断 ≤500 字符;未失败为空字符串)"
|
||||
},
|
||||
{
|
||||
"name": "pending_domain",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "待验证域名(切换中非空;未发起切换为空字符串)。frontConfig.setDomain 只登记到本字段,DNS TXT 校验通过后才被提升为生效域名 domain;本字段不参与 frontConfig.getByDomain 放行"
|
||||
},
|
||||
{
|
||||
"name": "pending_verify_host",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "待验证域名的 TXT 记录主机名(wmsv-<10 位 hex>.<pending_domain>;pending_domain 为空时返回空字符串)。该域名尚未生效,校验码始终回显,用户据此配置 TXT 记录"
|
||||
},
|
||||
{
|
||||
"name": "pending_verify_value",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "待验证域名的 TXT 记录值(32 位 hex,读 pending_verify_token 列;pending_domain 为空时返回空字符串)"
|
||||
},
|
||||
{
|
||||
"name": "pending_attempts",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "待验证域名校验尝试次数(setDomain 登记/补码时清零;checkDomain 与定时任务校验失败时 +1)"
|
||||
},
|
||||
{
|
||||
"name": "pending_last_error",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "待验证域名最近一次校验失败原因(脱敏截断 ≤500 字符;未失败或无待验证域名为空字符串)"
|
||||
},
|
||||
{
|
||||
"name": "pending_created_at",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "发起本次域名切换的时间(无待验证域名为 null)"
|
||||
},
|
||||
{
|
||||
"name": "pending_active",
|
||||
"type": "boolean",
|
||||
"required": true,
|
||||
"description": "是否处于域名切换中(boolean,等价于 pending_domain 非空;true=待验证域名已登记、等待 TXT 校验)"
|
||||
},
|
||||
{
|
||||
"name": "verified",
|
||||
"type": "boolean",
|
||||
@ -48199,15 +48539,29 @@
|
||||
{
|
||||
"code": "500",
|
||||
"message": "签约关系服务不可用 / WarehouseFrontConfig model 不可用 / 校验域名失败"
|
||||
},
|
||||
{
|
||||
"code": "409",
|
||||
"message": "域名 {domain} 已被其他仓库使用(提升待验证域名时 domain 唯一索引冲突兜底)"
|
||||
}
|
||||
],
|
||||
"notes": [
|
||||
"代码位置:出口 app/service/systemMethods/frontConfig.js 的 checkDomain,实现 app/service/systems/frontConfig.js 的 checkDomain(解析走 resolveTxtValues,单行校验走 verifyDomainRecord)",
|
||||
"代码位置:出口 app/service/systemMethods/frontConfig.js 的 checkDomain,实现 app/service/systems/frontConfig.js 的 checkDomain(路径一走 checkPendingDomainRecord → promotePendingDomain,路径二走 verifyDomainRecord;TXT 解析走 resolveTxtValues)",
|
||||
"鉴权标记: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 的行不再自动重试,但仍可通过本接口手动校验",
|
||||
"两阶段语义变更(本轮核心):有 pending_domain → 校验待验证域名的 TXT 记录(目标 pending_verify_host,比对 pending_verify_token)。通过 → 提升:domain 换为 pending_domain、domain_status=1、domain_verified_at=now、domain_verify_host/token/attempts 由 pending_* 平移、domain_last_error=NULL、清空 pending 6 列(pending_verify_attempts 归 0)、旧域名写入 retired_domain + retired_at、清空证书 5 列、重置同步 4 列(sync_status=0 / sync_attempts=0 / 清空 last_sync_error / last_synced_at),并清理旧域名与新域名两个公共拉取缓存,返回 verified=true;不通过 → 只写 pending_verify_attempts+1 与 pending_last_error,生效域名 domain / domain_status / domain_verified_at 与证书一律不动(旧域名不会被本路径断流),返回 verified=false",
|
||||
"提升并发守卫与边界:update 的 where 带 id + pending_domain(重复提升、用户已取消待切换、其他实例已提升过都不会误改);pending_domain 只有普通索引(非唯一),并发提交同一域名理论上可写入多行,最终由 domain 唯一索引在提升阶段兜底 —— 提升撞唯一索引转 409「域名 X 已被其他仓库使用」;retired_domain 只保留最近一个旧域名(多次连续切换会丢中间域名);首次设置(无生效域名)不写 retired_domain/retired_at,且提升时刻意不把 retired_domain 置 NULL —— 队列里可能还有更早的旧域名等待外部脚本消费,覆盖会丢失下线任务(孤儿由脚本兜底清理)",
|
||||
"提升后的预期噪音:提升后到用户上传新证书前,外部证书脚本会以「cert_pem 内容为空」记一次同步失败(属预期,失败只落库、不删除旧域名文件)",
|
||||
"路径二(无 pending_domain,保持升级前口径):domain_status=1 一律短路返回 verified=true、resolved_values=[],不写库、不降状态、不加 attempts(避免用户误点「校验」把生效中的域名打成验证失败而断流);domain 为空 → 400「请先设置域名」;domain_status∈{0,2} 且库内缺校验码(历史脏数据)→ 自动补发一份再校验(本次因记录尚未生效仍会失败),校验结果回写 domain_status / domain_verified_at / domain_verify_attempts / domain_last_error(兼容升级前登记的历史行)",
|
||||
"DNS 解析细节(多端点口径):默认按 config.frontConfig.domainVerify.dohUrls 顺序尝试(dns.alidns.com → 223.5.5.5 → doh.pub,单端点键 dohUrl 保留兼容),每个端点结果三分类 values(拿到至少一条 TXT 值 → 立即返回)/ empty(NODATA 或 NXDOMAIN)/ error(请求异常、超时、HTTP 非 200、响应体非合法 JSON);empty 与 error 都继续尝试下一个端点;全部端点未取到值后降级系统 DNS(node:dns,按 timeoutMs 限时)。只要有一个端点或系统 DNS 明确答复「无该记录」即判「未解析到记录」(返回空数组、不抛错),仅「所有 DoH 端点都是 error 且系统 DNS 也抛错」才抛 500「DNS 解析失败:{脱敏原因}」",
|
||||
"缓存:提升成功后清「旧域名 + 新域名」两个公共拉取缓存 key(front:config:domain:{domain}),先写库后清缓存,清失败仅记 WARN;路径二校验成功也清该域名的缓存",
|
||||
"与定时任务的关系:本接口为手动触发兜底,与 app/schedule/domain_verify_scan.js 共用同一套提升逻辑(定时任务入口为 verifyPendingDomains,逐行走 checkPendingDomainRecord / promotePendingDomain);定时任务对 pending_verify_attempts 已达 maxAttempts 的行不再自动重试(计入 skipped),但仍可通过本接口手动校验(本接口无 maxAttempts 门控)",
|
||||
"脱敏:失败原因统一经 sanitizeErrorText 处理(剥离 PEM 块内容、压缩空白、截断至 500 字符)后落库与回显,不写入原始网络错误/堆栈",
|
||||
"定时任务 lockTtlSeconds 默认 600s(略大于 interval 10m),避免上一轮未结束时重复加锁"
|
||||
"响应契约变更(本轮 11 → 18 字段,纯追加):在 last_error 之后、verified/resolved_values 之前插入待验证域名组 7 字段(pending_domain / pending_verify_host / pending_verify_value / pending_attempts / pending_last_error / pending_created_at / pending_active),既有 9 字段与 verified/resolved_values 的名称与语义均不变。本条 response 必须同步更新 —— 其口径定义为「frontConfig.getDomain 的字段 + verified + resolved_values」,getDomain 已由 9 字段扩为 16 字段,若本条不同步则文档与代码不一致",
|
||||
"errors 新增 409:提升时待验证域名已被其他仓库用为生效域名(domain 唯一索引冲突)返回 409「域名 X 已被其他仓库使用」;既有 400「请先设置域名」/ 400 未识别仓库 / 403 / 500 口径不变",
|
||||
"前端改造要点:切换中(pending_active=true)调用本接口才是「校验待验证域名」;通过后应提示「切换完成,请重新上传证书」—— 提升时证书已被清空、同步状态已重置;切换期间上传的证书属于旧域名,提升后失效",
|
||||
"定时任务头注释口径复核(未处理,建议由 wms-dev-agent 修正):app/schedule/domain_verify_scan.js 头注释仍写「扫描…已生成待校验 TXT 记录、且尚未通过验证的行,逐行解析 DNS TXT 记录并回写 domain_status / domain_verified_at / domain_verify_attempts / domain_last_error」—— 两阶段改造后实际只扫描 pending 组、回写 pending_* 并在通过时提升;本次为文档任务且约束不改 app/** 代码,故仅报告",
|
||||
"文档变更范围:methods/system.json 更新 frontConfig.setDomain / frontConfig.getDomain / frontConfig.checkDomain / frontConfig.getByDomain / frontConfig.saveCert / frontConfig.getCert 共 6 条(description + notes;其中 setDomain / getDomain / checkDomain 的 response 同步追加待验证域名组 7 字段,checkDomain 另补 409 错误码);frontConfig 分组仍 8 条、其余方法未动;methods/changes/system.json 新增 1 条变更记录;根版本 0.3.188 → 0.3.189(updatedAt 保持 2026-09-24)",
|
||||
"维护源口径冲突(仅记录,未处理):methods/*.json 的维护源是否为数据库表 wms_method_doc_meta 仍待用户决策;本次仍按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库(红线要求)"
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
@ -65,6 +65,9 @@
|
||||
"deploy:cert-sync:run": "node ./script/deploy-cert-sync.cjs production run",
|
||||
"deploy:cert-sync:status": "node ./script/deploy-cert-sync.cjs production status",
|
||||
"deploy:cert-sync:config-check": "node ./script/deploy-cert-sync.cjs production config-check",
|
||||
"deploy:cert-sync:cleanup-dry-run": "node ./script/deploy-cert-sync.cjs production cleanup-dry-run",
|
||||
"deploy:cert-sync:cleanup": "node ./script/deploy-cert-sync.cjs production cleanup",
|
||||
|
||||
"deploy:gateway-probe": "node ./script/deploy-ops.cjs production gateway-probe",
|
||||
"ops:check-root-logs": "node ./script/check-root-logs.cjs",
|
||||
"ops:clean-root-logs": "node ./script/check-root-logs.cjs production --clean",
|
||||
|
||||
@ -11,7 +11,8 @@ const {
|
||||
runSsh,
|
||||
} = require('./deploy-lib.cjs');
|
||||
|
||||
const COMMANDS = new Set([ 'precheck', 'install', 'dry-run', 'run', 'status', 'config-check' ]);
|
||||
const COMMANDS = new Set([ 'precheck', 'install', 'dry-run', 'run', 'status', 'config-check', 'cleanup-dry-run', 'cleanup' ]);
|
||||
|
||||
const LOCAL_SYNC_SCRIPT = path.join(ROOT, 'script', 'warehouse-cert-sync.cjs');
|
||||
const LOCAL_DB_CONFIG = path.join(ROOT, 'database', 'config.js');
|
||||
const LOCAL_PROD_CONFIG = path.join(ROOT, 'script', 'warehouse-cert-sync.config.prod.json');
|
||||
@ -20,14 +21,14 @@ function parseArgs(argv) {
|
||||
const options = { envName: 'production', command: '' };
|
||||
const tokens = [ ...argv ];
|
||||
if (tokens.length === 0) {
|
||||
throw new Error('missing command: precheck | install | dry-run | run | status | config-check');
|
||||
throw new Error('missing command: precheck | install | dry-run | run | status | config-check | cleanup-dry-run | cleanup');
|
||||
}
|
||||
if (!COMMANDS.has(tokens[0])) {
|
||||
options.envName = tokens[0];
|
||||
tokens.shift();
|
||||
}
|
||||
if (tokens.length === 0 || !COMMANDS.has(tokens[0])) {
|
||||
throw new Error('missing command: precheck | install | dry-run | run | status | config-check');
|
||||
throw new Error('missing command: precheck | install | dry-run | run | status | config-check | cleanup-dry-run | cleanup');
|
||||
}
|
||||
options.command = tokens[0];
|
||||
return options;
|
||||
@ -193,6 +194,17 @@ const seq = new Sequelize(client.database, client.username || client.user, clien
|
||||
} else {
|
||||
console.log("[DB_PROBE] domain_status distribution: (column missing, migration not applied; cert-sync falls back to no filter)");
|
||||
}
|
||||
const hasRetiredDomain = cols.some(r => r.cn === "retired_domain");
|
||||
console.log("[DB_PROBE] retired_domain column: " + (hasRetiredDomain ? "YES" : "NO"));
|
||||
if (hasRetiredDomain) {
|
||||
const [rCount] = await seq.query("SELECT COUNT(*) AS c FROM wms_warehouse_front_config WHERE retired_domain IS NOT NULL AND retired_domain <> ''");
|
||||
const [rPreview] = await seq.query("SELECT retired_domain AS d FROM wms_warehouse_front_config WHERE retired_domain IS NOT NULL AND retired_domain <> '' ORDER BY id ASC LIMIT 20");
|
||||
const names = rPreview.map(r => String(r.d)).join(",");
|
||||
console.log("[DB_PROBE] retired_domain pending: retired=" + rCount[0].c + (names ? ": " + names : ""));
|
||||
} else {
|
||||
console.log("[DB_PROBE] retired_domain pending: (column missing, migration not applied; cleanup flow skipped)");
|
||||
}
|
||||
|
||||
}
|
||||
} catch (e) {
|
||||
console.log("[DB_PROBE] failed: " + e.message);
|
||||
@ -201,7 +213,10 @@ const seq = new Sequelize(client.database, client.username || client.user, clien
|
||||
})();
|
||||
`;
|
||||
|
||||
/** Read-only remote precheck. */
|
||||
/**
|
||||
* Read-only remote precheck.
|
||||
* @param {Object} config deploy 配置对象。
|
||||
*/
|
||||
function runPrecheck(config) {
|
||||
const deployRoot = config.deployRoot;
|
||||
const remoteScript = [
|
||||
@ -253,7 +268,10 @@ function runPrecheck(config) {
|
||||
console.log(runSsh(config, dbProbeScript, { stdio: 'pipe' }).trim());
|
||||
}
|
||||
|
||||
/** Install: upload files, create thin shell wrapper, register root crontab. */
|
||||
/**
|
||||
* Install: upload files, create thin shell wrapper, register root crontab.
|
||||
* @param {Object} config deploy 配置对象。
|
||||
*/
|
||||
function runInstall(config) {
|
||||
const deployRoot = config.deployRoot;
|
||||
for (const [ file, label ] of [
|
||||
@ -347,21 +365,35 @@ function runInstall(config) {
|
||||
console.log(runSsh(config, installScript, { stdio: 'pipe' }).trim());
|
||||
}
|
||||
|
||||
/** Run the remote wrapper with optional extra args; returns output + exit code. */
|
||||
function runRemoteWrapper(config, extraArgs = []) {
|
||||
/**
|
||||
* Run the remote wrapper with optional extra args; returns output + exit code.
|
||||
* useFlock=true 时用与 crontab 相同的锁文件串行化(手工清理与每分钟定时任务互斥),
|
||||
* flock 不可用时只告警并降级为不加锁执行(不阻断运维操作)。
|
||||
* @param {Object} config deploy 配置对象(含 deployRoot)。
|
||||
* @param {string[]} extraArgs 透传给远端包装脚本的额外参数。
|
||||
* @param {boolean} useFlock 是否用 flock 串行化执行,默认 false。
|
||||
* @return {string} 远端输出(已 trim)。
|
||||
*/
|
||||
function runRemoteWrapper(config, extraArgs = [], useFlock = false) {
|
||||
const wrapperPath = `${config.deployRoot}/warehouse-cert-sync.sh`;
|
||||
const runLine = useFlock
|
||||
? 'FLOCK_BIN=$(command -v flock || true); if [ -n "$FLOCK_BIN" ]; then "$FLOCK_BIN" -w 30 /var/lock/warehouse-cert-sync.lock bash "$WRAPPER" $ARGS; else echo "WARN: flock not found, run without lock"; bash "$WRAPPER" $ARGS; fi'
|
||||
: 'bash "$WRAPPER" $ARGS';
|
||||
const remoteScript = [
|
||||
'set -uo pipefail',
|
||||
`WRAPPER=${quoteForBash(wrapperPath)}`,
|
||||
`ARGS=${quoteForBash(extraArgs.join(' '))}`,
|
||||
'if [ ! -f "$WRAPPER" ]; then echo "FATAL: wrapper missing: $WRAPPER"; exit 1; fi',
|
||||
'bash "$WRAPPER" $ARGS',
|
||||
runLine,
|
||||
'echo "CERT_SYNC_EXIT=$?"',
|
||||
].join('\n');
|
||||
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
|
||||
}
|
||||
|
||||
/** Status: crontab line, remote file list, log tail. */
|
||||
/**
|
||||
* Status: crontab line, remote file list, log tail.
|
||||
* @param {Object} config deploy 配置对象。
|
||||
*/
|
||||
function runStatus(config) {
|
||||
const deployRoot = config.deployRoot;
|
||||
const remoteScript = [
|
||||
@ -378,7 +410,10 @@ function runStatus(config) {
|
||||
console.log(runSsh(config, remoteScript, { stdio: 'pipe' }).trim());
|
||||
}
|
||||
|
||||
/** 只读核对服务器 prod 配置文件:存在性 + JSON 合法性 + 内容展示(无凭据,可安全输出)。 */
|
||||
/**
|
||||
* 只读核对服务器 prod 配置文件:存在性 + JSON 合法性 + 内容展示(无凭据,可安全输出)。
|
||||
* @param {Object} config deploy 配置对象。
|
||||
*/
|
||||
function runConfigCheck(config) {
|
||||
const deployRoot = config.deployRoot;
|
||||
const remoteScript = [
|
||||
@ -428,6 +463,16 @@ function main() {
|
||||
console.log(runRemoteWrapper(config, []));
|
||||
return;
|
||||
}
|
||||
if (options.command === 'cleanup-dry-run') {
|
||||
console.log('[CLEANUP-DRY-RUN] remote retired-domain cleanup dry-run (read-only: no file deletes, no db updates, no reload)');
|
||||
console.log(runRemoteWrapper(config, [ '--cleanup-only', '--dry-run' ], true));
|
||||
return;
|
||||
}
|
||||
if (options.command === 'cleanup') {
|
||||
console.log('[CLEANUP] remote retired-domain cleanup (real execution: deletes retired conf/cert files, then nginx -t + reload)');
|
||||
console.log(runRemoteWrapper(config, [ '--cleanup-only' ], true));
|
||||
return;
|
||||
}
|
||||
if (options.command === 'status') {
|
||||
runStatus(config);
|
||||
return;
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
const ROOT = process.cwd();
|
||||
const OUTPUT_DIR = path.join(ROOT, 'temp', 'method-output');
|
||||
@ -128,28 +127,76 @@ function pickProject(headers) {
|
||||
return project;
|
||||
}
|
||||
|
||||
async function createDbConnection(cfg) {
|
||||
const db = cfg.mysql.clients.wms;
|
||||
return mysql.createConnection({
|
||||
host: db.host,
|
||||
port: Number(db.port),
|
||||
user: db.user,
|
||||
password: db.password,
|
||||
database: db.database,
|
||||
});
|
||||
/** 接口流水日志目录:优先取环境变量,其次为本地开发目录 <repo>/logs(与 config.logPaths.base 一致) */
|
||||
function resolveApiLogDir() {
|
||||
if (process.env.WMS_LOG_DIR) return process.env.WMS_LOG_DIR;
|
||||
return path.join(ROOT, 'logs');
|
||||
}
|
||||
|
||||
async function loadRecentSystemLogCases(conn, methodDocs, limit, username) {
|
||||
const [rows] = await conn.query(`
|
||||
SELECT id, method, body, headers, auth, device, result, created_at
|
||||
FROM wms_system_log
|
||||
WHERE method IS NOT NULL
|
||||
AND method <> ''
|
||||
AND body IS NOT NULL
|
||||
AND body <> ''
|
||||
ORDER BY id DESC
|
||||
LIMIT 1200
|
||||
`);
|
||||
/**
|
||||
* 解析一行接口日志。
|
||||
*
|
||||
* 行格式为 `HH:mm:ss {JSON}`(行首时分秒前缀由 app/lib/api_log_sink.js 写入)。
|
||||
* 为兼容不带前缀的历史行,先尝试整体 parse,失败再截到第一个 `{` 重试。
|
||||
*
|
||||
* @param {string} line 原始行。
|
||||
* @return {Object|null} 解析出的记录;不是有效对象时返回 null。
|
||||
*/
|
||||
function parseApiLogLine(line) {
|
||||
const trimmed = String(line || '').trim();
|
||||
if (!trimmed) return null;
|
||||
const braceIndex = trimmed.indexOf('{');
|
||||
const candidates = braceIndex > 0 ? [ trimmed, trimmed.slice(braceIndex) ] : [ trimmed ];
|
||||
for (const text of candidates) {
|
||||
const parsed = safeJsonParse(text, null);
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取 wms-api.log 及其按天轮转的历史文件,按“最近优先”返回记录。
|
||||
*
|
||||
* 背景:接口流水原写入 wms_system_log 表,该表已下线
|
||||
* (见 database/migrations/20260927090000-offline-wms-system-log.js),
|
||||
* 现由 Egg 自定义 logger 落盘为一行一条的平铺 JSON,字段与旧表一一对应,
|
||||
* 因此回放样本改为从日志文件读取;返回结构保持与旧 SQL 结果同形
|
||||
* (method / body / headers / auth / device / result / created_at,并补 id 作为来源标识)。
|
||||
*
|
||||
* @return {Array<Object>} 记录列表,最近优先;目录/文件缺失时返回空数组。
|
||||
*/
|
||||
function loadRecentApiLogRows() {
|
||||
const dir = resolveApiLogDir();
|
||||
if (!fs.existsSync(dir)) return [];
|
||||
|
||||
const files = fs.readdirSync(dir)
|
||||
.filter(name => name === 'wms-api.log' || name.startsWith('wms-api.log.'))
|
||||
.map(name => ({
|
||||
full: path.join(dir, name),
|
||||
mtime: fs.statSync(path.join(dir, name)).mtimeMs,
|
||||
}))
|
||||
.sort((a, b) => a.mtime - b.mtime);
|
||||
|
||||
const rows = [];
|
||||
for (const file of files) {
|
||||
const text = fs.readFileSync(file.full, 'utf8');
|
||||
for (const line of text.split('\n')) {
|
||||
const row = parseApiLogLine(line);
|
||||
// 日志行没有自增 id,用 created_at 充当来源标识
|
||||
if (row && row.method) {
|
||||
rows.push(Object.assign({ id: row.created_at }, row));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 日志为追加写,倒序即“最近优先”,与原 SQL 的 ORDER BY id DESC 语义一致
|
||||
return rows.reverse();
|
||||
}
|
||||
|
||||
function loadRecentApiLogCases(methodDocs, limit, username) {
|
||||
const rows = loadRecentApiLogRows();
|
||||
|
||||
const preferred = [];
|
||||
const fallback = [];
|
||||
@ -173,7 +220,7 @@ async function loadRecentSystemLogCases(conn, methodDocs, limit, username) {
|
||||
const historySuccess = typeof row.result === 'string' && row.result.includes('"status":200');
|
||||
|
||||
const item = {
|
||||
source: 'wms_system_log',
|
||||
source: 'wms-api.log',
|
||||
sourceId: row.id,
|
||||
sourceCreatedAt: row.created_at,
|
||||
method: row.method,
|
||||
@ -278,65 +325,63 @@ async function runBaseline() {
|
||||
const cfg = readLocalConfig();
|
||||
const baseUrl = buildBaseUrl(cfg);
|
||||
const methodDocs = loadSystemMethodDocs();
|
||||
const conn = await createDbConnection(cfg);
|
||||
|
||||
try {
|
||||
const selected = await loadRecentSystemLogCases(conn, methodDocs, LIMIT, TEST_USERNAME);
|
||||
if (!selected.length) {
|
||||
throw new Error('未从 wms_system_log 找到可回放的只读 method 样本');
|
||||
}
|
||||
|
||||
const login = await callSystemMethod(
|
||||
baseUrl,
|
||||
'user.login',
|
||||
{ username: TEST_USERNAME, password: TEST_PASSWORD },
|
||||
{ platform: 'web', project: 'wms' },
|
||||
''
|
||||
const selected = loadRecentApiLogCases(methodDocs, LIMIT, TEST_USERNAME);
|
||||
if (!selected.length) {
|
||||
throw new Error(
|
||||
`未从 ${path.join(resolveApiLogDir(), 'wms-api.log')} 找到可回放的只读 method 样本`
|
||||
+ '(需先用真实账号跑一批只读接口,让日志里先有样本)'
|
||||
);
|
||||
const token = extractToken(login);
|
||||
if (!token) {
|
||||
throw new Error('登录成功但未拿到 token,请检查 user.login 返回结构');
|
||||
}
|
||||
|
||||
const cases = [];
|
||||
for (const item of selected) {
|
||||
const call = await callSystemMethod(baseUrl, item.method, item.body, item.headers, token);
|
||||
cases.push({
|
||||
method: item.method,
|
||||
source: item.source,
|
||||
sourceId: item.sourceId,
|
||||
sourceCreatedAt: item.sourceCreatedAt,
|
||||
headers: item.headers,
|
||||
requestBody: item.body,
|
||||
doc: methodDocs.get(item.method) || null,
|
||||
httpStatus: call.httpStatus,
|
||||
response: call.response,
|
||||
normalized: call.normalized,
|
||||
});
|
||||
}
|
||||
|
||||
const baseline = {
|
||||
generatedAt: new Date().toISOString(),
|
||||
baseUrl,
|
||||
user: TEST_USERNAME,
|
||||
note: 'Before-change baseline generated from recent system logs and methods/system.json',
|
||||
login: {
|
||||
httpStatus: login.httpStatus,
|
||||
normalized: login.normalized,
|
||||
},
|
||||
cases,
|
||||
};
|
||||
|
||||
ensureOutputDir();
|
||||
fs.writeFileSync(BASELINE_FILE, JSON.stringify(baseline, null, 2), 'utf8');
|
||||
fs.writeFileSync(BASELINE_SUMMARY, renderBaselineMarkdown(baseline), 'utf8');
|
||||
|
||||
console.log(`BASELINE_OK cases=${cases.length}`);
|
||||
console.log(`BASELINE_FILE ${BASELINE_FILE}`);
|
||||
console.log(`BASELINE_SUMMARY ${BASELINE_SUMMARY}`);
|
||||
} finally {
|
||||
await conn.end();
|
||||
}
|
||||
|
||||
const login = await callSystemMethod(
|
||||
baseUrl,
|
||||
'user.login',
|
||||
{ username: TEST_USERNAME, password: TEST_PASSWORD },
|
||||
{ platform: 'web', project: 'wms' },
|
||||
''
|
||||
);
|
||||
const token = extractToken(login);
|
||||
if (!token) {
|
||||
throw new Error('登录成功但未拿到 token,请检查 user.login 返回结构');
|
||||
}
|
||||
|
||||
const cases = [];
|
||||
for (const item of selected) {
|
||||
const call = await callSystemMethod(baseUrl, item.method, item.body, item.headers, token);
|
||||
cases.push({
|
||||
method: item.method,
|
||||
source: item.source,
|
||||
sourceId: item.sourceId,
|
||||
sourceCreatedAt: item.sourceCreatedAt,
|
||||
headers: item.headers,
|
||||
requestBody: item.body,
|
||||
doc: methodDocs.get(item.method) || null,
|
||||
httpStatus: call.httpStatus,
|
||||
response: call.response,
|
||||
normalized: call.normalized,
|
||||
});
|
||||
}
|
||||
|
||||
const baseline = {
|
||||
generatedAt: new Date().toISOString(),
|
||||
baseUrl,
|
||||
user: TEST_USERNAME,
|
||||
note: 'Before-change baseline generated from recent wms-api.log samples and methods/system.json',
|
||||
login: {
|
||||
httpStatus: login.httpStatus,
|
||||
normalized: login.normalized,
|
||||
},
|
||||
cases,
|
||||
};
|
||||
|
||||
ensureOutputDir();
|
||||
fs.writeFileSync(BASELINE_FILE, JSON.stringify(baseline, null, 2), 'utf8');
|
||||
fs.writeFileSync(BASELINE_SUMMARY, renderBaselineMarkdown(baseline), 'utf8');
|
||||
|
||||
console.log(`BASELINE_OK cases=${cases.length}`);
|
||||
console.log(`BASELINE_FILE ${BASELINE_FILE}`);
|
||||
console.log(`BASELINE_SUMMARY ${BASELINE_SUMMARY}`);
|
||||
}
|
||||
|
||||
async function runCompare() {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
445
test/app/service/systems/order_packing.list.operatorText.test.js
Normal file
445
test/app/service/systems/order_packing.list.operatorText.test.js
Normal file
@ -0,0 +1,445 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const Sequelize = require('sequelize');
|
||||
const { Op } = Sequelize;
|
||||
const OrderPackingService = require('../../../../app/service/systems/order_packing');
|
||||
const { matchesWhere } = require('../../../support/where_matcher');
|
||||
|
||||
const TEST_WAREHOUSE_ID = 100000;
|
||||
|
||||
/**
|
||||
* 打包员筛选 fixture:operator_text 为多人姓名逗号拼接快照(如 '小吴哥,阿猫')。
|
||||
* 额外包含 % / _ 字面量行,用于校验通配符转义。
|
||||
* @param {Array<Object>} rows 行定义({ order_id, operator_text, wave_no?, warehouse_id? })。
|
||||
* @return {Array<Object>} 打包任务行。
|
||||
*/
|
||||
function buildOperatorTextRows(rows) {
|
||||
return rows.map((item, index) => ({
|
||||
id: index + 1,
|
||||
order_id: item.order_id,
|
||||
warehouse_id: item.warehouse_id === undefined ? TEST_WAREHOUSE_ID : item.warehouse_id,
|
||||
wave_id: item.wave_id || 0,
|
||||
wave_no: item.wave_no || '',
|
||||
pack_mode: item.pack_mode || 1,
|
||||
status: 1,
|
||||
operator_text: item.operator_text === undefined ? '' : item.operator_text,
|
||||
start_time: null,
|
||||
end_time: null,
|
||||
create_time: null,
|
||||
update_time: null,
|
||||
deleted_at: null,
|
||||
workbench: null,
|
||||
videos: [],
|
||||
expresses: [],
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 order.packing.list 服务测试环境(复用 waybill 测试文件的 harness 结构)。
|
||||
* mock 模型通过 matchesWhere 按真实 where 语义过滤 fixture 行。
|
||||
* @param {Object} [options={}] 测试配置。
|
||||
* @return {{service: OrderPackingService, calls: Object}} 测试上下文。
|
||||
*/
|
||||
function createOperatorTextHarness(options = {}) {
|
||||
const packTaskRows = buildOperatorTextRows(options.packTaskRows || []);
|
||||
const expressRows = Array.isArray(options.expressRows) ? options.expressRows.map(item => ({ ...item })) : [];
|
||||
const orderDeliveryRows = Array.isArray(options.orderDeliveryRows)
|
||||
? options.orderDeliveryRows.map(item => ({ ...item }))
|
||||
: [];
|
||||
const waveBatchRows = Array.isArray(options.waveBatchRows) ? options.waveBatchRows.map(item => ({ ...item })) : [];
|
||||
|
||||
const calls = {
|
||||
expressFindAllWheres: [],
|
||||
packTaskFindAndCountAllWhere: null,
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
app: {
|
||||
Sequelize,
|
||||
config: {},
|
||||
formatDate(value) {
|
||||
return value === null || value === undefined ? null : String(value);
|
||||
},
|
||||
},
|
||||
user: { store_id: TEST_WAREHOUSE_ID },
|
||||
logger: { info() {}, warn() {}, error() {} },
|
||||
model: {
|
||||
OrderExpress: {
|
||||
async findAll(query = {}) {
|
||||
calls.expressFindAllWheres.push(query.where || null);
|
||||
return expressRows.filter(item => matchesWhere(item, query.where || {}));
|
||||
},
|
||||
},
|
||||
OrderDeliveryFactory: {
|
||||
async getCurrentModel() {
|
||||
return {
|
||||
async findAll(query = {}) {
|
||||
return orderDeliveryRows.filter(item => matchesWhere(item, query.where || {}));
|
||||
},
|
||||
};
|
||||
},
|
||||
async getDispatchModel() {
|
||||
return {
|
||||
async findAll(query = {}) {
|
||||
return orderDeliveryRows.filter(item => matchesWhere(item, query.where || {}));
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
WaveBatch: {
|
||||
async findAll(query = {}) {
|
||||
return waveBatchRows.filter(item => matchesWhere(item, query.where || {}));
|
||||
},
|
||||
},
|
||||
PrintComputer: {
|
||||
async findOne() {
|
||||
return null;
|
||||
},
|
||||
},
|
||||
Workbench: {},
|
||||
PackTaskVideo: {},
|
||||
Camera: {},
|
||||
PackTask: {
|
||||
async count(query = {}) {
|
||||
return packTaskRows.filter(item => matchesWhere(item, query.where || {})).length;
|
||||
},
|
||||
async findAll(query = {}) {
|
||||
calls.packTaskFindAndCountAllWhere = query.where || null;
|
||||
const filtered = packTaskRows.filter(item => matchesWhere(item, query.where || {}));
|
||||
const pageSize = Number(query.limit) || filtered.length;
|
||||
const offset = Number(query.offset) || 0;
|
||||
return filtered.slice(offset, offset + pageSize).map(row => ({
|
||||
get() {
|
||||
return { ...row };
|
||||
},
|
||||
}));
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
service: new OrderPackingService(ctx),
|
||||
calls,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从结果中提取 order_id 列表(升序)。
|
||||
* @param {Object} result 服务返回结果。
|
||||
* @return {Array<number>} order_id 列表。
|
||||
*/
|
||||
function resultOrderIds(result) {
|
||||
return (result && result.data && result.data.list ? result.data.list : [])
|
||||
.map(item => Number(item.order_id))
|
||||
.sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
const OPERATOR_TEXT_ROWS = [
|
||||
{ order_id: 201, operator_text: '小吴哥,阿猫' },
|
||||
{ order_id: 202, operator_text: '阿猫,小张' },
|
||||
{ order_id: 203, operator_text: '李四' },
|
||||
{ order_id: 204, operator_text: '100%合格' },
|
||||
{ order_id: 205, operator_text: '1000合格' },
|
||||
{ order_id: 206, operator_text: '王五_临时' },
|
||||
{ order_id: 207, operator_text: '王五X临时' },
|
||||
];
|
||||
|
||||
describe('test/app/service/systems/order_packing.list.operatorText.test.js', () => {
|
||||
describe('order.packing.list where.operator_text 打包员筛选', () => {
|
||||
it('单值 like(type=text)应命中 operator_text 逗号拼接快照中的任一姓名', async () => {
|
||||
const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS });
|
||||
|
||||
const result = await service.list(
|
||||
{ operator_text: { operator: 'like', value: '小吴哥', type: 'text' } },
|
||||
{ page: 1, pageSize: 20 },
|
||||
{}
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
calls.packTaskFindAndCountAllWhere.operator_text,
|
||||
{ [Op.like]: '%小吴哥%' },
|
||||
'应生成 operator_text LIKE %小吴哥%'
|
||||
);
|
||||
assert.deepEqual(resultOrderIds(result), [ 201 ], '仅含小吴哥的行命中');
|
||||
assert.equal(result.data.pagination.total, 1);
|
||||
});
|
||||
|
||||
it('多值数组 like 应取并集(Op.or 经 Op.and 承载,不占用顶层 Op.or)', async () => {
|
||||
const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS });
|
||||
|
||||
const result = await service.list(
|
||||
{ operator_text: { operator: 'like', value: [ '小吴哥', '李四' ], type: 'text' } },
|
||||
{ page: 1, pageSize: 20 },
|
||||
{}
|
||||
);
|
||||
|
||||
const where = calls.packTaskFindAndCountAllWhere;
|
||||
assert.equal(where.operator_text, undefined, '多值 like 不得生成顶层 operator_text 键');
|
||||
const andConditions = where[Op.and];
|
||||
assert.ok(Array.isArray(andConditions) && andConditions.length === 1, '应追加一条 Op.and 条件');
|
||||
assert.deepEqual(
|
||||
andConditions[0][Op.or],
|
||||
[
|
||||
{ operator_text: { [Op.like]: '%小吴哥%' } },
|
||||
{ operator_text: { [Op.like]: '%李四%' } },
|
||||
],
|
||||
'Op.or 应包含两个 operator_text LIKE 条件'
|
||||
);
|
||||
assert.deepEqual(resultOrderIds(result), [ 201, 203 ], '命中任一姓名的行都应返回(并集)');
|
||||
assert.equal(result.data.pagination.total, 2);
|
||||
});
|
||||
|
||||
it('eq 单值应为等值匹配(快照列整体相等,而非子串)', async () => {
|
||||
const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS });
|
||||
|
||||
const result = await service.list(
|
||||
{ operator_text: { operator: 'eq', value: '小吴哥,阿猫', type: 'text' } },
|
||||
{ page: 1, pageSize: 20 },
|
||||
{}
|
||||
);
|
||||
|
||||
assert.equal(calls.packTaskFindAndCountAllWhere.operator_text, '小吴哥,阿猫');
|
||||
assert.deepEqual(resultOrderIds(result), [ 201 ], '仅快照整体相等的行命中');
|
||||
});
|
||||
|
||||
it('eq 多值应生成 Op.in', async () => {
|
||||
const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS });
|
||||
|
||||
const result = await service.list(
|
||||
{ operator_text: { operator: 'eq', value: [ '小吴哥,阿猫', '李四' ], type: 'text' } },
|
||||
{ page: 1, pageSize: 20 },
|
||||
{}
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
calls.packTaskFindAndCountAllWhere.operator_text,
|
||||
{ [Op.in]: [ '小吴哥,阿猫', '李四' ] },
|
||||
'多值 eq 应生成 Op.in'
|
||||
);
|
||||
assert.deepEqual(resultOrderIds(result), [ 201, 203 ]);
|
||||
});
|
||||
|
||||
it('ne 应排除命中的行(取首值)', async () => {
|
||||
const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS });
|
||||
|
||||
const result = await service.list(
|
||||
{ operator_text: { operator: 'ne', value: '小吴哥,阿猫', type: 'text' } },
|
||||
{ page: 1, pageSize: 20 },
|
||||
{}
|
||||
);
|
||||
|
||||
assert.deepEqual(calls.packTaskFindAndCountAllWhere.operator_text, { [Op.ne]: '小吴哥,阿猫' });
|
||||
assert.deepEqual(resultOrderIds(result), [ 202, 203, 204, 205, 206, 207 ], '小吴哥,阿猫 行应被排除');
|
||||
});
|
||||
|
||||
it('notlike 多值应逐个排除(含任一关键词的行都不返回)', async () => {
|
||||
const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS });
|
||||
|
||||
const result = await service.list(
|
||||
{ operator_text: { operator: 'notlike', value: [ '小吴哥', '李四' ], type: 'text' } },
|
||||
{ page: 1, pageSize: 20 },
|
||||
{}
|
||||
);
|
||||
|
||||
const where = calls.packTaskFindAndCountAllWhere;
|
||||
assert.equal(where.operator_text, undefined, '多值 notlike 不得生成顶层 operator_text 键');
|
||||
assert.deepEqual(
|
||||
where[Op.and],
|
||||
[
|
||||
{ operator_text: { [Op.notLike]: '%小吴哥%' } },
|
||||
{ operator_text: { [Op.notLike]: '%李四%' } },
|
||||
],
|
||||
'应生成两个 NOT LIKE 条件'
|
||||
);
|
||||
assert.deepEqual(resultOrderIds(result), [ 202, 204, 205, 206, 207 ], '含任一关键词的行都应被排除');
|
||||
});
|
||||
|
||||
it('空串不得产生 operator_text 条件(不过滤任何数据)', async () => {
|
||||
for (const emptyValue of [{ operator: 'eq', value: '' }, { operator: 'like', value: '' }]) {
|
||||
const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS });
|
||||
|
||||
const result = await service.list(
|
||||
{ operator_text: emptyValue },
|
||||
{ page: 1, pageSize: 20 },
|
||||
{}
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
Object.prototype.hasOwnProperty.call(calls.packTaskFindAndCountAllWhere, 'operator_text'),
|
||||
false,
|
||||
`空串形态 ${JSON.stringify(emptyValue)} 不得生成 operator_text 条件`
|
||||
);
|
||||
assert.deepEqual(resultOrderIds(result), [ 201, 202, 203, 204, 205, 206, 207 ], '所有行都应返回');
|
||||
}
|
||||
});
|
||||
|
||||
it('空数组不得产生 operator_text 条件(不过滤任何数据)', async () => {
|
||||
for (const emptyValue of [{ operator: 'in', value: [] }, { operator: 'like', value: [] }]) {
|
||||
const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS });
|
||||
|
||||
const result = await service.list(
|
||||
{ operator_text: emptyValue },
|
||||
{ page: 1, pageSize: 20 },
|
||||
{}
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
Object.prototype.hasOwnProperty.call(calls.packTaskFindAndCountAllWhere, 'operator_text'),
|
||||
false,
|
||||
`空数组形态 ${JSON.stringify(emptyValue)} 不得生成 operator_text 条件`
|
||||
);
|
||||
assert.deepEqual(resultOrderIds(result), [ 201, 202, 203, 204, 205, 206, 207 ], '所有行都应返回');
|
||||
}
|
||||
});
|
||||
|
||||
it('value=null 不得产生 operator_text 条件(当前实现缺陷:会生成非法条件过滤全部数据)', async () => {
|
||||
// 复现:normalizeWhereParams 会把 null 归一为 { operator: 'eq', value: null },
|
||||
// _buildListWhere 的 `value ?? where.operator_text` 将整个条件对象回退并 String 化为 '[object Object]',
|
||||
// 导致生成 operator_text = '[object Object]'(eq)或 LIKE '%[object Object]%'(like),过滤掉全部数据。
|
||||
for (const emptyValue of [{ operator: 'eq', value: null }, { operator: 'like', value: null }]) {
|
||||
const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS });
|
||||
|
||||
const result = await service.list(
|
||||
{ operator_text: emptyValue },
|
||||
{ page: 1, pageSize: 20 },
|
||||
{}
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
Object.prototype.hasOwnProperty.call(calls.packTaskFindAndCountAllWhere, 'operator_text'),
|
||||
false,
|
||||
`null 形态 ${JSON.stringify(emptyValue)} 不得生成 operator_text 条件(当前实现生成了 ${JSON.stringify(calls.packTaskFindAndCountAllWhere.operator_text)})`
|
||||
);
|
||||
assert.deepEqual(resultOrderIds(result), [ 201, 202, 203, 204, 205, 206, 207 ], '所有行都应返回');
|
||||
}
|
||||
});
|
||||
|
||||
it('通配符转义:% / _ 不得扩大匹配范围', async () => {
|
||||
const percentHarness = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS });
|
||||
const percentResult = await percentHarness.service.list(
|
||||
{ operator_text: { operator: 'like', value: '100%', type: 'text' } },
|
||||
{ page: 1, pageSize: 20 },
|
||||
{}
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
percentHarness.calls.packTaskFindAndCountAllWhere.operator_text,
|
||||
{ [Op.like]: '%100\\%%' },
|
||||
'% 应被转义为字面量'
|
||||
);
|
||||
assert.deepEqual(
|
||||
resultOrderIds(percentResult),
|
||||
[ 204 ],
|
||||
'搜 100% 仅命中含字面量 100% 的行,不得命中 1000 合格'
|
||||
);
|
||||
|
||||
const underscoreHarness = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS });
|
||||
const underscoreResult = await underscoreHarness.service.list(
|
||||
{ operator_text: { operator: 'like', value: '王五_临时', type: 'text' } },
|
||||
{ page: 1, pageSize: 20 },
|
||||
{}
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
underscoreHarness.calls.packTaskFindAndCountAllWhere.operator_text,
|
||||
{ [Op.like]: '%王五\\_临时%' },
|
||||
'_ 应被转义为字面量'
|
||||
);
|
||||
assert.deepEqual(
|
||||
resultOrderIds(underscoreResult),
|
||||
[ 206 ],
|
||||
'搜 王五_临时 仅命中含字面量下划线的行,不得命中 王五X临时'
|
||||
);
|
||||
});
|
||||
|
||||
it('与 quickWhere 共存时顶层 Op.or 不被覆盖(多值打包员走 Op.and)', async () => {
|
||||
const { service, calls } = createOperatorTextHarness({
|
||||
packTaskRows: [
|
||||
{ order_id: 301, operator_text: '小吴哥,阿猫', wave_no: 'W7-A1' },
|
||||
{ order_id: 302, operator_text: '李四', wave_no: 'W7-A2' },
|
||||
{ order_id: 303, operator_text: '小吴哥,王五', wave_no: 'B9-X1' },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.list(
|
||||
{
|
||||
operator_text: { operator: 'like', value: [ '小吴哥', '李四' ], type: 'text' },
|
||||
quickWhere: 'W7',
|
||||
},
|
||||
{ page: 1, pageSize: 20 },
|
||||
{}
|
||||
);
|
||||
|
||||
const where = calls.packTaskFindAndCountAllWhere;
|
||||
assert.ok(Array.isArray(where[Op.or]) && where[Op.or].length === 1, '顶层 Op.or 应仅承载 quickWhere 条件');
|
||||
assert.deepEqual(where[Op.or], [{ wave_no: { [Op.like]: '%W7%' } }], 'quickWhere 的 Op.or 不得被打包员条件覆盖');
|
||||
assert.ok(Array.isArray(where[Op.and]), '打包员多值条件应走 Op.and');
|
||||
assert.deepEqual(
|
||||
where[Op.and][0][Op.or],
|
||||
[
|
||||
{ operator_text: { [Op.like]: '%小吴哥%' } },
|
||||
{ operator_text: { [Op.like]: '%李四%' } },
|
||||
],
|
||||
'打包员并集条件嵌套在 Op.and 内'
|
||||
);
|
||||
assert.deepEqual(resultOrderIds(result), [ 301, 302 ], '波次 W7 且打包员为 小吴哥/李四 的行命中');
|
||||
});
|
||||
|
||||
it('warehouse_id 隔离仍生效(其他仓库的行不可见)', async () => {
|
||||
const { service, calls } = createOperatorTextHarness({
|
||||
packTaskRows: [
|
||||
{ order_id: 401, operator_text: '小吴哥', warehouse_id: TEST_WAREHOUSE_ID },
|
||||
{ order_id: 402, operator_text: '小吴哥', warehouse_id: 999999 },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.list(
|
||||
{ operator_text: { operator: 'like', value: '小吴哥', type: 'text' } },
|
||||
{ page: 1, pageSize: 20 },
|
||||
{}
|
||||
);
|
||||
|
||||
assert.equal(calls.packTaskFindAndCountAllWhere.warehouse_id, TEST_WAREHOUSE_ID);
|
||||
assert.deepEqual(resultOrderIds(result), [ 401 ], '仅测试仓库内的行返回');
|
||||
});
|
||||
|
||||
it('打包员条件与 wave_no 条件可共存(不互相覆盖)', async () => {
|
||||
const { service, calls } = createOperatorTextHarness({
|
||||
packTaskRows: [
|
||||
{ order_id: 501, operator_text: '小吴哥', wave_no: 'W8-01' },
|
||||
{ order_id: 502, operator_text: '李四', wave_no: 'W8-01' },
|
||||
{ order_id: 503, operator_text: '小吴哥', wave_no: 'W8-02' },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.list(
|
||||
{
|
||||
operator_text: { operator: 'like', value: '小吴哥', type: 'text' },
|
||||
wave_no: { operator: 'eq', value: 'W8-01' },
|
||||
},
|
||||
{ page: 1, pageSize: 20 },
|
||||
{}
|
||||
);
|
||||
|
||||
const where = calls.packTaskFindAndCountAllWhere;
|
||||
assert.equal(where.wave_no, 'W8-01');
|
||||
assert.deepEqual(where.operator_text, { [Op.like]: '%小吴哥%' });
|
||||
assert.deepEqual(resultOrderIds(result), [ 501 ], '两个条件应同时生效');
|
||||
});
|
||||
|
||||
it('缺省 operator(未指定)应保持历史模糊行为', async () => {
|
||||
const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS });
|
||||
|
||||
const result = await service.list(
|
||||
{ operator_text: { value: '小吴哥', type: 'text' } },
|
||||
{ page: 1, pageSize: 20 },
|
||||
{}
|
||||
);
|
||||
|
||||
assert.deepEqual(calls.packTaskFindAndCountAllWhere.operator_text, { [Op.like]: '%小吴哥%' });
|
||||
assert.deepEqual(resultOrderIds(result), [ 201 ]);
|
||||
});
|
||||
});
|
||||
});
|
||||
222
test/app/service/systems/return_unpack.list.unpackerName.test.js
Normal file
222
test/app/service/systems/return_unpack.list.unpackerName.test.js
Normal file
@ -0,0 +1,222 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const Sequelize = require('sequelize');
|
||||
const { Op } = Sequelize;
|
||||
const ReturnUnpackService = require('../../../../app/service/systems/return_unpack');
|
||||
const { matchesWhere } = require('../../../support/where_matcher');
|
||||
|
||||
/**
|
||||
* returnUnpack.list where.unpacker_name(拆包人快照列)筛选单元测试。
|
||||
*
|
||||
* 背景:_buildListWhere 将 unpacker_name 加入 textFields;_resolveConditionValue 的 like 分支
|
||||
* 新增数组支持(多值 → { [Op.or]: [ { [Op.like]: '%值%' }, ... ] }),标量行为不变。
|
||||
* 本文件 mock 的 count/findAll 通过 matchesWhere 按真实 where 语义过滤 fixture 行,
|
||||
* 同时断言条件真实透传到 ReturnUnpack.count({ where }) 与 ReturnUnpack.findAll({ where })。
|
||||
*/
|
||||
|
||||
const WAREHOUSE_ID = 100000;
|
||||
|
||||
/**
|
||||
* 拆包单 fixture:unpacker_name 覆盖等值/拼接快照两种形态,unpack_no/waybill_code 用于回归断言。
|
||||
* @return {Array<Object>} 拆包单行。
|
||||
*/
|
||||
function createRows() {
|
||||
const defs = [
|
||||
{ id: 1, unpacker_name: '阿猫', unpack_no: 'RP20260900001', waybill_code: 'SF00001' },
|
||||
{ id: 2, unpacker_name: '阿猫,小李', unpack_no: 'RP20260900002', waybill_code: 'SF00002' },
|
||||
{ id: 3, unpacker_name: '张三', unpack_no: 'RP20260900003', waybill_code: 'SF00003' },
|
||||
{ id: 4, unpacker_name: '李四', unpack_no: 'RP20260910001', waybill_code: 'YT00001' },
|
||||
];
|
||||
return defs.map(item => ({
|
||||
...item,
|
||||
warehouse_id: WAREHOUSE_ID,
|
||||
store_id: 1000000,
|
||||
order_express_id: null,
|
||||
unpacker_id: item.id,
|
||||
camera_ids: '[1,2]',
|
||||
total_items: 1,
|
||||
total_quantity: 2,
|
||||
unpack_date: '2026-09-10',
|
||||
start_time: '2026-09-10 09:00:00',
|
||||
end_time: '2026-09-10 09:05:00',
|
||||
created_at: '2026-09-10 09:06:00',
|
||||
updated_at: '2026-09-10 09:06:00',
|
||||
videos: [],
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 returnUnpack.list 服务测试环境。
|
||||
* count 不带 include(对齐既有测试口径);count/findAll 均按真实 where 语义过滤。
|
||||
* @return {{service: ReturnUnpackService, captured: Object, allRows: Array<Object>}} 测试上下文。
|
||||
*/
|
||||
function createHarness() {
|
||||
const allRows = createRows();
|
||||
const captured = {
|
||||
countCalls: [],
|
||||
findAllCalls: [],
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
app: {
|
||||
Sequelize,
|
||||
formatDate(value, fmt) {
|
||||
if (value instanceof Date) {
|
||||
const iso = value.toISOString();
|
||||
return fmt === 'YYYY-MM-DD' ? iso.slice(0, 10) : iso.slice(0, 19).replace('T', ' ');
|
||||
}
|
||||
return value === null || value === undefined ? '' : String(value);
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
warn() {},
|
||||
info() {},
|
||||
error() {},
|
||||
},
|
||||
model: {
|
||||
ReturnUnpack: {
|
||||
async count(opts = {}) {
|
||||
captured.countCalls.push(opts);
|
||||
return allRows.filter(item => matchesWhere(item, opts.where || {})).length;
|
||||
},
|
||||
async findAll(opts = {}) {
|
||||
captured.findAllCalls.push(opts);
|
||||
const offset = Number(opts.offset || 0);
|
||||
const limit = Number(opts.limit || allRows.length);
|
||||
return allRows
|
||||
.filter(item => matchesWhere(item, opts.where || {}))
|
||||
.slice(offset, offset + limit)
|
||||
.map(row => ({ ...row }));
|
||||
},
|
||||
},
|
||||
PrintComputer: {
|
||||
async findOne() {
|
||||
return { id: 9 };
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const service = new ReturnUnpackService(ctx);
|
||||
return { service, captured, allRows };
|
||||
}
|
||||
|
||||
/**
|
||||
* 从结果中提取 id 列表(升序)。
|
||||
* @param {Object} result 服务返回结果。
|
||||
* @return {Array<number>} id 列表。
|
||||
*/
|
||||
function resultIds(result) {
|
||||
return (result && result.list ? result.list : []).map(item => Number(item.id)).sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
describe('test/app/service/systems/return_unpack.list.unpackerName.test.js', () => {
|
||||
describe('returnUnpack.list where.unpacker_name 拆包人筛选', () => {
|
||||
it('标量 like 应生成 { [Op.like]: "%阿猫%" } 且实际过滤命中', async () => {
|
||||
const { service, captured } = createHarness();
|
||||
|
||||
const result = await service.list(
|
||||
{ warehouse_id: WAREHOUSE_ID, unpacker_name: { operator: 'like', value: '阿猫' } },
|
||||
{ page: 1, pageSize: 20 }
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
captured.countCalls[0].where.unpacker_name,
|
||||
{ [Op.like]: '%阿猫%' },
|
||||
'unpacker_name 应生成 LIKE %阿猫%'
|
||||
);
|
||||
// 条件真实透传到 count 与 findAll,且 count 不带 include(保持既有口径)
|
||||
assert.deepEqual(captured.findAllCalls[0].where, captured.countCalls[0].where);
|
||||
assert.equal(
|
||||
Object.prototype.hasOwnProperty.call(captured.countCalls[0], 'include'),
|
||||
false,
|
||||
'count 调用不得携带 include'
|
||||
);
|
||||
assert.deepEqual(resultIds(result), [ 1, 2 ], '含阿猫的行(含拼接快照)命中');
|
||||
assert.equal(result.pagination.total, 2);
|
||||
});
|
||||
|
||||
it('数组 like 应生成 Op.or 多个 LIKE 并集', async () => {
|
||||
const { service, captured } = createHarness();
|
||||
|
||||
const result = await service.list(
|
||||
{ warehouse_id: WAREHOUSE_ID, unpacker_name: { operator: 'like', value: [ '阿猫', '张三' ] } },
|
||||
{ page: 1, pageSize: 20 }
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
captured.countCalls[0].where.unpacker_name,
|
||||
{
|
||||
[Op.or]: [
|
||||
{ [Op.like]: '%阿猫%' },
|
||||
{ [Op.like]: '%张三%' },
|
||||
],
|
||||
},
|
||||
'数组 like 应生成 Op.or 多个 LIKE'
|
||||
);
|
||||
assert.deepEqual(captured.findAllCalls[0].where, captured.countCalls[0].where);
|
||||
assert.deepEqual(resultIds(result), [ 1, 2, 3 ], '命中任一姓名的行都应返回');
|
||||
assert.equal(result.pagination.total, 3);
|
||||
});
|
||||
|
||||
it('eq 应为精确等值、ne 应排除命中行', async () => {
|
||||
const eqHarness = createHarness();
|
||||
const eqResult = await eqHarness.service.list(
|
||||
{ warehouse_id: WAREHOUSE_ID, unpacker_name: { operator: 'eq', value: '阿猫' } },
|
||||
{ page: 1, pageSize: 20 }
|
||||
);
|
||||
|
||||
assert.equal(eqHarness.captured.countCalls[0].where.unpacker_name, '阿猫', 'eq 应直接等值');
|
||||
assert.deepEqual(resultIds(eqResult), [ 1 ], '仅快照整体相等的行命中(阿猫,小李 不命中)');
|
||||
|
||||
const neHarness = createHarness();
|
||||
const neResult = await neHarness.service.list(
|
||||
{ warehouse_id: WAREHOUSE_ID, unpacker_name: { operator: 'ne', value: '阿猫' } },
|
||||
{ page: 1, pageSize: 20 }
|
||||
);
|
||||
|
||||
assert.deepEqual(neHarness.captured.countCalls[0].where.unpacker_name, { [Op.ne]: '阿猫' });
|
||||
assert.deepEqual(resultIds(neResult), [ 2, 3, 4 ], '阿猫 行应被排除');
|
||||
});
|
||||
|
||||
it('空数组 like 应退化为 %%(全匹配、不过滤)', async () => {
|
||||
const { service, captured } = createHarness();
|
||||
|
||||
const result = await service.list(
|
||||
{ warehouse_id: WAREHOUSE_ID, unpacker_name: { operator: 'like', value: [] } },
|
||||
{ page: 1, pageSize: 20 }
|
||||
);
|
||||
|
||||
assert.deepEqual(captured.countCalls[0].where.unpacker_name, { [Op.like]: '%%' });
|
||||
assert.deepEqual(resultIds(result), [ 1, 2, 3, 4 ], '空数组不得过滤任何数据');
|
||||
assert.equal(result.pagination.total, 4);
|
||||
});
|
||||
});
|
||||
|
||||
describe('returnUnpack.list 既有文本筛选回归', () => {
|
||||
it('unpack_no 标量 like 保持 %值% 行为', async () => {
|
||||
const { service, captured } = createHarness();
|
||||
|
||||
const result = await service.list(
|
||||
{ warehouse_id: WAREHOUSE_ID, unpack_no: { operator: 'like', value: 'RP2026090' } },
|
||||
{ page: 1, pageSize: 20 }
|
||||
);
|
||||
|
||||
assert.deepEqual(captured.countCalls[0].where.unpack_no, { [Op.like]: '%RP2026090%' });
|
||||
assert.deepEqual(resultIds(result), [ 1, 2, 3 ]);
|
||||
});
|
||||
|
||||
it('waybill_code 标量 like 保持 %值% 行为', async () => {
|
||||
const { service, captured } = createHarness();
|
||||
|
||||
const result = await service.list(
|
||||
{ warehouse_id: WAREHOUSE_ID, waybill_code: { operator: 'like', value: 'SF00' } },
|
||||
{ page: 1, pageSize: 20 }
|
||||
);
|
||||
|
||||
assert.deepEqual(captured.countCalls[0].where.waybill_code, { [Op.like]: '%SF00%' });
|
||||
assert.deepEqual(resultIds(result), [ 1, 2, 3 ]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -167,6 +167,12 @@ function createQueryOrderHarness(options = {}) {
|
||||
return options.currentTask;
|
||||
},
|
||||
},
|
||||
WorkbenchMember: {
|
||||
async count() {
|
||||
// 当前工作台打包成员人数(默认 1,可配置)
|
||||
return options.memberCount === undefined ? 1 : options.memberCount;
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@ -263,7 +269,13 @@ function createPackOrderHarness(options = {}) {
|
||||
},
|
||||
WorkbenchMember: {
|
||||
async findAll() {
|
||||
return [];
|
||||
// 当前工作台绑定成员(默认 1 人,可配置)
|
||||
const memberCount = options.memberCount === undefined ? 1 : options.memberCount;
|
||||
return Array.from({ length: memberCount }, (_, index) => ({
|
||||
id: index + 1,
|
||||
user_id: 100000 + index,
|
||||
user_name: `成员${index + 1}`,
|
||||
}));
|
||||
},
|
||||
},
|
||||
PackTask: {
|
||||
@ -275,7 +287,13 @@ function createPackOrderHarness(options = {}) {
|
||||
},
|
||||
async create(data) {
|
||||
created.push({ ...data });
|
||||
return { id: 777, ...data };
|
||||
return {
|
||||
id: 777,
|
||||
...data,
|
||||
async update() {
|
||||
// mock:更新任务无操作
|
||||
},
|
||||
};
|
||||
},
|
||||
async destroy() {
|
||||
return 0;
|
||||
@ -285,6 +303,10 @@ function createPackOrderHarness(options = {}) {
|
||||
async destroy() {
|
||||
return 0;
|
||||
},
|
||||
async bulkCreate() {
|
||||
// mock:写入打包人无操作
|
||||
return [];
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
@ -317,17 +339,25 @@ describe('workbench 大团购打包系数回归(wave_scope 落库 / 倒计时
|
||||
});
|
||||
|
||||
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 () => {
|
||||
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
|
||||
// 散单打包数=1,系数=3,成员默认 1 人 → 等待秒数=1×3/1=3
|
||||
assert.strictEqual(result.pack_wait_seconds, 3);
|
||||
assert.ok(result.pack_start_time > 0, 'wave_scope=1 时应下发开始打包时间');
|
||||
});
|
||||
|
||||
it('wave_scope=1 且工作台 2 人打包:等待秒数按人数分摊(1×3/2=1.5)', async () => {
|
||||
const harness = createPackOrderHarness({ orderWaveScope: 1, waveScopeParam: 1, memberCount: 2 });
|
||||
const result = await harness.service._packOrder(harness.packParams);
|
||||
|
||||
assert.strictEqual(result.pack_wait_seconds, 1.5);
|
||||
assert.ok(result.pack_start_time > 0);
|
||||
});
|
||||
|
||||
it('未上报 wave_scope:兜底订单行 wave_scope=1 落库,并下发倒计时字段', async () => {
|
||||
const harness = createPackOrderHarness({ orderWaveScope: 1 });
|
||||
const result = await harness.service._packOrder(harness.packParams);
|
||||
@ -361,7 +391,7 @@ describe('workbench 大团购打包系数回归(wave_scope 落库 / 倒计时
|
||||
},
|
||||
});
|
||||
|
||||
// 需要 10×3=30 秒,仅过去 5 秒 → 未到时 → 不同波次拦截
|
||||
// 需要 10×3/1=30 秒,仅过去 5 秒 → 未到时 → 不同波次拦截
|
||||
await assert.rejects(
|
||||
() => harness.service._queryOrder(harness.queryParams),
|
||||
error => error && error.message === '打包时长不足'
|
||||
@ -404,6 +434,44 @@ describe('workbench 大团购打包系数回归(wave_scope 落库 / 倒计时
|
||||
assert.strictEqual(result.order.wave_id, TEST_WAVE_ID);
|
||||
});
|
||||
|
||||
it('工作台 3 人打包时等待秒数按人数分摊(10×3/3=10 秒):未到 10 秒拦截,超过 10 秒放行', async () => {
|
||||
const notReached = createQueryOrderHarness({
|
||||
memberCount: 3,
|
||||
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/3=10 秒,仅过去 5 秒 → 未到时 → 拦截
|
||||
await assert.rejects(
|
||||
() => notReached.service._queryOrder(notReached.queryParams),
|
||||
error => error && error.message === '打包时长不足'
|
||||
);
|
||||
|
||||
const reached = createQueryOrderHarness({
|
||||
memberCount: 3,
|
||||
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() - 12 * 1000),
|
||||
create_time: new Date(Date.now() - 12 * 1000),
|
||||
},
|
||||
});
|
||||
|
||||
// 需要 10 秒,已过 12 秒 → 已到时 → 放行
|
||||
const result = await reached.service._queryOrder(reached.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 },
|
||||
|
||||
153
test/support/where_matcher.js
Normal file
153
test/support/where_matcher.js
Normal file
@ -0,0 +1,153 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Sequelize where 条件匹配器(测试专用)。
|
||||
* 供 service 层测试的 mock 模型复用:在内存中按真实 where 语义过滤 fixture 行,
|
||||
* 重点支持 Op.like(含 % _ 与反斜杠转义语义),避免只断言到「假行为」。
|
||||
*/
|
||||
|
||||
const Sequelize = require('sequelize');
|
||||
|
||||
const { Op } = Sequelize;
|
||||
|
||||
/**
|
||||
* 宽松等值比较:先严格比较,再对数字做数值化比较(兼容字符串/数字混用)。
|
||||
* @param {*} left 左值。
|
||||
* @param {*} right 右值。
|
||||
* @return {boolean} 是否等值。
|
||||
*/
|
||||
function looseEqual(left, right) {
|
||||
if (left === right) return true;
|
||||
if (left === null || right === null || left === undefined || right === undefined) return false;
|
||||
|
||||
const leftNum = Number(left);
|
||||
const rightNum = Number(right);
|
||||
if (String(left).trim() !== '' && String(right).trim() !== ''
|
||||
&& Number.isFinite(leftNum) && Number.isFinite(rightNum)) {
|
||||
return leftNum === rightNum;
|
||||
}
|
||||
|
||||
return String(left) === String(right);
|
||||
}
|
||||
|
||||
/**
|
||||
* 转义正则元字符。
|
||||
* @param {string} ch 单个字符。
|
||||
* @return {string} 转义后的字符。
|
||||
*/
|
||||
function escapeRegExpChar(ch) {
|
||||
return ch.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 SQL LIKE 模式转换为等价正则(支持 \ 转义 % _ \)。
|
||||
* @param {string} pattern LIKE 模式。
|
||||
* @return {RegExp} 等价正则。
|
||||
*/
|
||||
function likeToRegExp(pattern) {
|
||||
let body = '^';
|
||||
for (let index = 0; index < pattern.length; index++) {
|
||||
const ch = pattern[index];
|
||||
if (ch === '\\') {
|
||||
const next = pattern[index + 1];
|
||||
if (next !== undefined) {
|
||||
body += escapeRegExpChar(next);
|
||||
index++;
|
||||
} else {
|
||||
body += '\\\\';
|
||||
}
|
||||
} else if (ch === '%') {
|
||||
body += '.*';
|
||||
} else if (ch === '_') {
|
||||
body += '.';
|
||||
} else {
|
||||
body += escapeRegExpChar(ch);
|
||||
}
|
||||
}
|
||||
body += '$';
|
||||
return new RegExp(body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断字段值是否命中 LIKE 模式。
|
||||
* @param {*} value 字段值。
|
||||
* @param {string} pattern LIKE 模式。
|
||||
* @return {boolean} 是否命中。
|
||||
*/
|
||||
function matchLike(value, pattern) {
|
||||
return likeToRegExp(String(pattern)).test(String(value === null || value === undefined ? '' : value));
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断单条条件对象是否命中。
|
||||
* @param {Object} row 待匹配行。
|
||||
* @param {string} field 字段名。
|
||||
* @param {Object} condition 条件对象。
|
||||
* @return {boolean} 是否命中。
|
||||
*/
|
||||
function matchConditionObject(row, field, condition) {
|
||||
const symbols = Object.getOwnPropertySymbols(condition);
|
||||
if (symbols.length > 0) {
|
||||
return symbols.every(symbol => {
|
||||
const value = condition[symbol];
|
||||
if (symbol === Op.eq) return looseEqual(row[field], value);
|
||||
if (symbol === Op.ne) return !looseEqual(row[field], value);
|
||||
if (symbol === Op.in) return Array.isArray(value) && value.some(item => looseEqual(row[field], item));
|
||||
if (symbol === Op.notIn) return Array.isArray(value) && !value.some(item => looseEqual(row[field], item));
|
||||
if (symbol === Op.like || symbol === Op.iLike) return matchLike(row[field], value);
|
||||
if (symbol === Op.notLike) return !matchLike(row[field], value);
|
||||
if (symbol === Op.gt) return Number(row[field]) > Number(value);
|
||||
if (symbol === Op.gte) return Number(row[field]) >= Number(value);
|
||||
if (symbol === Op.lt) return Number(row[field]) < Number(value);
|
||||
if (symbol === Op.lte) return Number(row[field]) <= Number(value);
|
||||
if (symbol === Op.or) return Array.isArray(value) && value.some(item => matchConditionObject(row, field, item));
|
||||
if (symbol === Op.and) return Array.isArray(value) && value.every(item => matchConditionObject(row, field, item));
|
||||
if (symbol === Op.not) return !matchConditionObject(row, field, value);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
if (Object.keys(condition).length > 0) {
|
||||
return matchesWhere(row[field], condition);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 mock 行数据是否匹配 where 条件(支持 Op.and / Op.or / Op.not / Op.like 等)。
|
||||
* @param {Object|*} row 待匹配行。
|
||||
* @param {Object|Array|*} where Sequelize where 条件。
|
||||
* @return {boolean} 是否匹配。
|
||||
*/
|
||||
function matchesWhere(row, where) {
|
||||
if (where === null || where === undefined) return true;
|
||||
if (typeof where !== 'object') return looseEqual(row, where);
|
||||
if (Array.isArray(where)) return where.some(item => matchesWhere(row, item));
|
||||
|
||||
if (Array.isArray(where[Op.and]) && !where[Op.and].every(item => matchesWhere(row, item))) {
|
||||
return false;
|
||||
}
|
||||
if (Array.isArray(where[Op.or]) && !where[Op.or].some(item => matchesWhere(row, item))) {
|
||||
return false;
|
||||
}
|
||||
if (where[Op.not] !== undefined && matchesWhere(row, where[Op.not])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Object.entries(where).every(([ field, condition ]) => {
|
||||
if (condition && typeof condition === 'object' && !Array.isArray(condition)) {
|
||||
return matchConditionObject(row, field, condition);
|
||||
}
|
||||
if (Array.isArray(condition)) {
|
||||
return condition.some(item => looseEqual(row[field], item));
|
||||
}
|
||||
return looseEqual(row[field], condition);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
looseEqual,
|
||||
matchLike,
|
||||
matchesWhere,
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user